Home > OS >  Can I create a set of list::iterators? Will they still point to the same node after I erase/insert o
Can I create a set of list::iterators? Will they still point to the same node after I erase/insert o

Time:02-06

I want to create a set of list::iterators, so that when I update other nodes in the list, my iterator still points to the same node.

int n;
string s;
cin >> n >> s;

list<char> str;
for (char c : s) {
    str.push_back(c);
}

vector<set<list<char>::iterator>> locations(10);
for (auto it = str.begin(); it != str.end();   it) {
    auto next = it;
      next;

    if (next != str.end()) {
        int l = *it - '0', r = *next - '0';
        if ((l   1) % 10 == r) {
            locations[l].insert(it);
        }
    }
}

I get a compile error saying

error: no match for ‘operator<’ (operand types are ‘const std::_List_iterator’ and ‘const std::_List_iterator’) 386 | { return __x < __y; }

What am I doing wrong? Is this possible in C ? Or should I create my own node structure and store pointers to it?

PS - I am trying to solve a problem from Google Kickstart (https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435914/00000000008d94f5) and the string s contains only digits from 0-9.

CodePudding user response:

You'd need a custom comparator. E.g. something like this:

struct CompareIterators {
  template <typename It>
  bool operator()(It iter1, It iter2) const {
    using Ptr = decltype(&*iter1);
    return std::less<Ptr>{}(&*iter1, &*iter2);
  }
};

using MySet = set<list<char>::iterator, CompareIterators>;
vector<MySet> locations(10);

The order of elements in MySet will be essentially random, unpredictable. It won't necessarily correspond to the order of nodes in the list. All it ensures is that, if you insert an iterator to the same element twice, it will only appear in the set once.

  •  Tags:  
  • Related