如何从pair <int,object =“”>的向量中删除重复项

时间:2017-05-18 13:15:21

标签: c++

这就是我现在正在尝试的。我做了一个比较函数:

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);
}

添加元素后,我调用std::unique来过滤重复项:

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

但似乎这不起作用。我不知道问题是什么 根据我的理解std::unique应该使用compare谓词。

我应该如何更新我的代码才能使其正常工作? 我正在使用C ++ 03。

编辑:

我也尝试过对它进行排序,但仍然无法正常工作。

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);

3 个答案:

答案 0 :(得分:3)

std::unique要求传递给它的范围使所有重复元素彼此相邻才能工作。

您可以在调用unique之前使用std::sort来实现该范围,因为排序会自动对重复项进行分组。

答案 1 :(得分:2)

排序和过滤很不错,但由于从不想要任何重复,为什么不使用std::set? 虽然我们在这里,但这些对看起来像是关键值,所以std::map怎么样?

答案 2 :(得分:0)

如果您只想保留唯一对象,请使用适当的容器类型,例如std::set(或std::map)。例如

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

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