Answers for "stl iterator"

C++
5

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';
Posted by: Guest on March-09-2020
1

c++ vector iterator

// 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;
*/
Posted by: Guest on June-02-2020
0

stl iterator

#include <iostream>
#include <algorithm>
 
template<long FROM, long TO>
class Range {
public:
    // member typedefs provided through inheriting from std::iterator
    class iterator: public std::iterator<
                        std::input_iterator_tag,   // iterator_category
                        long,                      // value_type
                        long,                      // difference_type
                        const long*,               // pointer
                        long                       // reference
                                      >{
        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() {
    // std::find requires an input iterator
    auto range = Range<15, 25>();
    auto itr = std::find(range.begin(), range.end(), 18);
    std::cout << *itr << '\n'; // 18
 
    // Range::iterator also satisfies range-based for requirements
    for(long l : Range<3, 5>()) {
        std::cout << l << ' '; // 3 4 5
    }
    std::cout << '\n';
}
Posted by: Guest on December-13-2020
0

declaring iterator in cpp

vector<int>::iterator ptr;
Posted by: Guest on June-12-2020

Browse Popular Code Answers by Language