迭代列表以查找元素的出现.代码问题

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

本文关键字:代码 问题 元素 列表 查找 迭代      更新时间:2023-10-16

有人知道此代码怎么了吗?我遇到以下汇编错误。目的是找到字符串" P"的出现,然后我从Stroustrup P57中获取了这个想法。我的假设是,我可以将迭代器递增以查找其他出现,但这不起作用。谢谢

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;
}

列表迭代器是双向迭代器,而不是随机访问迭代器。因此,它们没有operator+,而只有operator++。你可以写

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

而不是。