简体   繁体   中英

How to remove duplicates from a vector of pair<int, Object>

This is what I am trying right now. I made a comparison function:

bool compare(const std::pair<int, Object>& left, const std::pair<int, Object>& right)
{
    return (left.second.name == right.second.name) && (left.second.time == right.second.time) && 
        (left.second.value == right.second.value);
}

After I add an element I call std::unique to filter duplicates:

data.push_back(std::make_pair(index, obj));
data.erase(std::unique(data.begin(), data.end(), compare), data.end());

But it seems that this doesn't work. And I don't know what the problem is.
From my understanding std::unique should use the compare predicate.

How should I update my code to make this work ?
I am using C++03.

edit:

I have tried to sort it too, but still doens't work.

bool compare2(const std::pair<int, Object>& left, const std::pair<int, Object>& right)
{
    return (left.second.time< right.second.time);
}

std::sort(simulatedLatchData.begin(), simulatedLatchData.end(), compare2);

std::unique requires the range passed to it to have all the duplicate elements next to one another in order to work.

You can use std::sort on the range before you a call unique to achieve that as sorting automatically groups duplicates.

Sorting and filtering is nice, but since you never want any duplicate, why not use std::set ?
And while we're at it, these pairs look suspiciously like key-values, so how about std::map ?

If you want to keep only unique objects, then use an appropriate container type, such as a std::set (or std::map ). For example

bool operator<(object const&, object const&); 

std::set<object> data;
object obj = new_object(/*...*/);
data.insert(obj);    // will only insert if unique

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM