Simple program ↓
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec = {10, 20, 30};
vec.push_back(40);
vec.push_back(50);
// vec.pop_back(); // remove the last element
// Access elements using indexing
cout << "Element at index 1: " << vec[1] << endl;
// Iterate over the vector using a for loop
cout << "Elements: ";
for (int i = 0; i < vec.size(); ++i)
{
cout << vec[i] << " ";
}
cout << endl;
// Get the size of the vector
cout << "Size: " << vec.size() << endl;
// Clear the vector
vec.clear();
cout << "Size after clearing: " << vec.size() << endl;
return 0;
}
Simple program ↓
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> myList = {5, 10, 20};
// Access elements
cout << "First element: " << myList.front() << endl;
cout << "Last element: " << myList.back() << endl;
// Iterate over the list using a for loop
cout << "Elements: ";
for (const auto element : myList)
{
cout << element << " ";
}
cout << endl;
// Insert an element at a specific position
auto it = next(myList.begin()); // Get iterator to the second element
myList.insert(it, 15);
// Remove an element from the list
myList.pop_front();
// Check if the list is empty
if (myList.empty())
{
cout << "List is empty" << endl;
}
else
{
cout << "List is not empty" << endl;
}
return 0;
}
Simple program ↓
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int> myMap = {{"John", 25}, {"Alice", 30}, {"Bob", 40}};
// Access values using keys
cout << "Age of Alice: " << myMap["Alice"] << endl;
// Iterate over the map using a for loop
cout << "Name - Age pairs: ";
for (const auto &pair : myMap)
{
cout << pair.first << ":" << pair.second << " ";
}
cout << endl;
// Check if a key exists in the map
string name = "John";
if (myMap.count(name) > 0)
{
cout << name << " exists in the map" << endl;
}
else
{
cout << name << " does not exist in the map" << endl;
}
// Erase an element from the map
myMap.erase("Bob");
return 0;
}