c++iteratorlistiterator

Iterating over list to find occurrences of element. Issue with code


Does anyone know what's wrong with this code? I'm getting the following compilation error. The goal is to find the occurrences of a string "p" and I took the idea from Stroustrup P57. My assumption is that I could just increment the iterator to find additional occurrences, but that is not working. Thanks

find.cc: In function ‘int main(int, char**)’:
find.cc:34:16: error: no match for ‘operator+’ (operand types are ‘LI {aka std::_List_const_iterator<Ent>}’ and ‘int’)
     i = find(i + 1, l.end(), e1);
#include <iostream>
#include <algorithm>
#include <list>
#include <string>

using namespace std;

struct Ent {
  string name;
  Ent(const string& name) : name(name) { }
  bool operator== (const Ent& right) const {
    return name == right.name;
  }
};

int main(int argc, char *argv[])
{
  list<Ent> l;

  for (char c = 'a'; c <= 'z'; c++) {
    Ent e(string(1, c));
    l.push_back(e);
  }

  Ent e1("p");

  typedef list<Ent>::const_iterator LI;

  LI i = find(l.begin(), l.end(), e1);

  int n = 0;
  while (i != l.end()) {
    ++n;
    i = find(i + 1, l.end(), e1);
  }

  cout << "find(" << e1.name << ") = " << n << endl;

  return 0;
}

Solution

  • Lists iterators are bidirectional iterators but not randomaccess iterators. Hence they have no operator+, but only a operator++. You can write

    ++i;
    i = find(i , l.end(), e1);
    

    instead.