iterator c++ code example
Example 1: c++ vector iterator
#include <iostream>
#include <vector>
using namespace std;
vector<int> myvector;
for (vector<int>::iterator it = myvector.begin();
it != myvector.end();
++it)
cout << ' ' << *it;
cout << '\n';
Example 2: c++ array interator
#include <array>
#include <vector>
#include <iterator>
int main()
{
int c_array[5] = {};
std::array<int, 5> cpp_array = {};
std::vector<int> cpp_dynarray(5);
auto c_array_begin = std::begin(c_array);
auto c_array_end = std::end(c_array);
auto cpp_array_begin = std::begin(cpp_array);
auto cpp_array_end = std::end(cpp_array);
auto cpp_dynarray_begin = std::begin(cpp_dynarray);
auto cpp_dynarray_end = std::end(cpp_dynarray);
}
Example 3: c++ vector iterator
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];
cout << "[ElementIndex:" << ElementIndex << "][ElementValue:" << ElementValue << "]\n";
}
Example 4: declaring iterator in cpp
vector<int>::iterator ptr;
Example 5: reverse iterator c++
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int>::reverse_iterator r_iter;
for (r_iter = vec.rbegin(); r_iter != vec.rend(); r_iter++) {
std::cout << *r_iter << std::endl;
}
return 0;
}
Example 6: stl iterator
#include <iostream>
#include <algorithm>
template<long FROM, long TO>
class Range {
public:
class iterator: public std::iterator<
std::input_iterator_tag,
long,
long,
const long*,
long
>{
long num = FROM;
public:
explicit iterator(long _num = 0) : num(_num) {}
iterator& operator++() {num = TO >= FROM ? num + 1: num - 1; return *this;}
iterator operator++(int) {iterator retval = *this; ++(*this); return retval;}
bool operator==(iterator other) const {return num == other.num;}
bool operator!=(iterator other) const {return !(*this == other);}
reference operator*() const {return num;}
};
iterator begin() {return iterator(FROM);}
iterator end() {return iterator(TO >= FROM? TO+1 : TO-1);}
};
int main() {
auto range = Range<15, 25>();
auto itr = std::find(range.begin(), range.end(), 18);
std::cout << *itr << '\n';
for(long l : Range<3, 5>()) {
std::cout << l << ' ';
}
std::cout << '\n';
}