0

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;
}
  • In general, never use `std::list`. It's not python. Use `std::vector` by default. But in some cases `std::unique_ptr` or `std::deque` are more suitable. – ALX23z May 18 '19 at 23:29
  • `std::list` is fantastic in some circumstances. It has very forgiving [iterator invalidation rules](https://stackoverflow.com/questions/6438086/iterator-invalidation-rules), for example. – user4581301 May 19 '19 at 02:48

1 Answers1

1

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • Thanks. find.cc:35:28: error: no matching function for call to ‘find(LI&, std::__cxx11::list::iterator, Ent&)’ i = find(i, l.end(), e1); –  May 18 '19 at 23:21
  • Change `typedef list::const_iterator LI;` to `typedef list::iterator LI;`. – Paul Sanders May 18 '19 at 23:45
  • Thanks! That worked! I'm assuming const_iterator worked before because a new const random access iterator was returned each time, vs incrementing the iterator in place. –  May 18 '19 at 23:52