Using iterators with containers - C++ STL

C++ examples for STL:iterator

Description

Using iterators with containers

Demo Code

#include <iostream>
#include <list>
#include <algorithm>
#include <string>
#include <iterator>

using namespace std;

static const int ARRAY_SIZE = 5;

template<typename T, typename FwdIter>
FwdIter fixOutliersUBound(FwdIter p1, FwdIter p2, const T& oldVal, const T& newVal) {
  for (; p1 != p2; ++p1) {
    if (greater<T>(*p1, oldVal)) {
      *p1 = newVal;//from   ww w . j  a v a  2 s  .c  o  m
    }
  }
}

int main() {
  list<string> lstStr;

  lstStr.push_back("A");
  lstStr.push_back("B");
  lstStr.push_back("C");
  lstStr.push_back("D");

  // Create an iterator for stepping through the list
  for (list<string>::iterator p = lstStr.begin(); p != lstStr.end(); ++p) {
    cout << *p << endl;
  }

  for (list<string>::reverse_iterator p = lstStr.rbegin(); p != lstStr.rend(); ++p) {
    cout << *p << endl;
  }

  string arrStr[ARRAY_SIZE] = { "this", "is", "a", "test", "over" };

  for (string* p = &arrStr[0]; p != &arrStr[ARRAY_SIZE]; ++p) {
    cout << *p << endl;
  }

  list<string> lstStrDest;
  unique_copy(&arrStr[0], &arrStr[ARRAY_SIZE], std::back_inserter(lstStrDest));
}

Result


Related Tutorials