[英]How can i erase duplicated elements from a multimap<int, std::pair<int, bool>>?
I have a multimap with duplicates.我有一个重复的多地图。 When I finished the collection of the elements i would like to erase the dups.
当我完成元素的收集时,我想删除重复项。
Here is the container:这是容器:
std::multimap<int, std::pair<int, bool>> container;
This following code is inside an iteration.(it is a simpler version of the original)以下代码在迭代中。(它是原始版本的更简单版本)
container.emplace(LeafId, std::make_pair(NodeId, isElectronic));
Is it good solution?是好的解决方案吗?
std::pair<int, std::pair<int, bool>> lastValue {-1 , {-1, -1}};
for (auto it = container.cbegin(); it != container.cend();)
{
if (it->first == lastValue.first && it->second == lastValue.second)
{
it = container.erase(it);
} else
{
lastValue = *it;
++it;
}
}
Is it good solution?
是好的解决方案吗?
Unless you keep internal pair sorted inside multimap, no it is not a good solution as it would miss duplicates.除非您在 multimap 内保持内部对排序,否则这不是一个好的解决方案,因为它会错过重复项。 If you can change data type then you can use:
如果您可以更改数据类型,那么您可以使用:
std::map<int, std::vector<std::pair<int, bool>>>
instead of std::multimap
and then for each element sort vector and remove duplicates using standard algorithms as described here Removing duplicates in a vector of strings而不是
std::multimap
,然后对每个元素排序向量并使用标准算法删除重复项,如此处所述删除字符串向量中的重复项
if you cannot I suggest to use additional std::set
or std::unordered_set
:如果你不能,我建议使用额外的
std::set
或std::unordered_set
:
std::set<std::pair<int, bool>> tset;
int lastValue = 0;
for (auto it = container.cbegin(); it != container.cend();)
{
if( it->first != lastValue ) {
tset.clear();
lastValue = it->first;
}
if( !tset.insert( it->second ).second )
it = container.erase( it );
else
++it;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.