Search code examples
c++stdlist

Detect equal elements in a std::list


Is there a better way of finding elements of a std::list that have the same value as manually going over the sorted list and comparing each element like this:

for(auto it = l.begin(); it != l.end(); it++) {
        auto nextElement = it;
        nextElement++;

        if(nextElement == l.end())
            break;

        if(*it == *nextElement)
            cout << "Equal" << endl;
}

Solution

  • Use the STL algorithm adjacent_find:

    auto it = l.begin()
    while((it = std::adjacent_find(it, l.end())) != l.end()){
      std::cout << "Equal\n";
      ++it;
    }