0

I've got a list of elements stored in stl c++ list. How to remove only one of repeating values?

#include <list>
int main() {
    std::list<int> listOfInts({ 1, 2, 3, 3, 4, 5 });
    listOfInts.remove(3);
    return 0;
}

My list will now look like this: 1, 2, 4, 5. Is there a way to make it look like this: 1, 2, 3, 4, 5?

I know it might be very easy, but it's my first time with stl list and I appreciate all tips.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
sra.mik
  • 11
  • See https://stackoverflow.com/questions/1041620/whats-the-most-efficient-way-to-erase-duplicates-and-sort-a-vector – Quarra Dec 07 '20 at 13:02
  • Does this answer your question? [What's the most efficient way to erase duplicates and sort a vector?](https://stackoverflow.com/questions/1041620/whats-the-most-efficient-way-to-erase-duplicates-and-sort-a-vector) – Quarra Dec 07 '20 at 13:05
  • I'll look into it – sra.mik Dec 07 '20 at 13:09
  • 1
    @Quarra: Removing duplicates will reduce the number of copies **to** one, not **by** one. E.g. if the input was `1,2,3,3,3,4,5`, removing only the first occurrence of `3` would leave `1,2,3,3,4,5` - still a duplicate. – MSalters Dec 07 '20 at 13:13

2 Answers2

3

Use the standard algorithm std::find

#include <list>
#include <iterator>
#include <algorithm>

//...
auto it = std::find( std::begin( listOfInts ), std::end( listOfInts ), 3 );

if ( it != std::end( listOfInts ) ) listOfInts.erase( it );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You can do as

#include <list>
#include <algorithm>

using namespace std;

int main() {
    list<int> listOfInts({ 1, 2, 3, 3, 4, 5 });

    auto itr = find(listOfInts.begin(), listOfInts.end(), 3);

    if (itr != listOfInts.end()) {
        listOfInts.erase(itr);
    }

    return 0;
}
starboy_jb
  • 899
  • 1
  • 6
  • 13