Removing duplicate values from std::list

This is a discussion on Removing duplicate values from std::list within the C++ Programming forums, part of the General Programming Boards category; I have an std::list<BallPair> list, where BallPair is a custom class that overloads operator==. In the list there are duplicate ...

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    27

    Removing duplicate values from std::list

    I have an std::list<BallPair> list, where BallPair is a custom class that overloads operator==. In the list there are duplicate values, which I want to remove. I tried the following:

    Code:
    typedef std::list<BallPair>::iterator BallPairListItor;
    Code:
    for(BallPairListItor i = l.begin(); i != l.end(); ++i)
            for(BallPairListItor j = l.begin() + 1; j != l.end()  - 1; ++j)
                if(*i == *j)
                    j = l.erase(j);
    but unfortunately list iterators do not provide operator + or operator -.

    I also tried list::unique but at unique - C++ Reference says:
    Notice that an element is only removed from the list if it is equal to the element immediately preceding it.
    Any ideas?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,725
    Is it okay for you to sort the linked list? That is one way to get it to work with std::unique, and is certainly more efficient.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jul 2010
    Posts
    27
    The BallPair class just holds two pointers(to Ball objects). If b1, b2 are pointers then
    BallPair(b1, b2) will be equal to BallPair(b2, b1).

    So, no, there isn't a way to sort the list to make unique work.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,725
    In that case, a possible solution is to go through the list of BallPair objects, and then swap the pointers such that the second pointer is not less than the first pointer. Then, you can sort them according to the first and second pointers.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 07-28-2009, 03:15 PM
  2. Replies: 12
    Last Post: 04-12-2009, 05:49 PM
  3. disposing error
    By dropper166 in forum C# Programming
    Replies: 2
    Last Post: 03-30-2009, 11:53 PM
  4. Sending values to a control
    By Zyk0tiK in forum C Programming
    Replies: 6
    Last Post: 12-02-2005, 05:29 PM
  5. Duplicate values in Array
    By TONYMX3 in forum C++ Programming
    Replies: 2
    Last Post: 01-30-2002, 02:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21