vector iterator in c++
// EXAMPLE
vector<string> vData;
vData.push_back("zeroth");
vData.push_back("first");
vData.push_back("second");
vData.push_back("third");
std::vector<string>::iterator itData;
for (itData = vData.begin(); itData != vData.end() ; itData++)
{
auto ElementIndex = itData-vData.begin();
auto ElementValue = vData[ElementIndex]; // vData[ElementIndex] = *itData
cout << "[ElementIndex:" << ElementIndex << "][ElementValue:" << ElementValue << "]\n";
}
/* HEADER(S)
#include <vector>
#include <iostream>
using namespace std;
*/
// C++ program to demonstrate iterators
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Declaring a vector
vector<int> v = { 1, 2, 3 };
// Declaring an iterator
vector<int>::iterator i;
int j;
cout << "Without iterators = ";
// Accessing the elements without using iterators
for (j = 0; j < 3; ++j)
{
cout << v[j] << " ";
}
cout << "\nWith iterators = ";
// Accessing the elements using iterators
for (i = v.begin(); i != v.end(); ++i)
{
cout << *i << " ";
}
// Adding one more element to vector
v.push_back(4);
cout << "\nWithout iterators = ";
// Accessing the elements without using iterators
for (j = 0; j < 4; ++j)
{
cout << v[j] << " ";
}
cout << "\nWith iterators = ";
// Accessing the elements using iterators
for (i = v.begin(); i != v.end(); ++i)
{
cout << *i << " ";
}
return 0;
}
// C++ code to demonstrate the working of
// iterator, begin() and end()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
// Declaring iterator to a vector
vector<int>::iterator ptr;
// Displaying vector elements using begin() and end()
cout << "The vector elements are : ";
for (ptr = ar.begin(); ptr < ar.end(); ptr++)
cout << *ptr << " ";
return 0;
}