如何从 stl 集中获取唯一的值对
我有一组 stl 整数,我想迭代所有唯一的整数值对,其中通过唯一性,我认为 val1,val2 和 val2,val1 是相同的,我应该只看到该组合一次。
我在 python 中编写了这个,其中使用列表(簇)的索引:
for i in range(len(clusters) - 1):
for j in range(i+1,len(clusters)):
#Do something with clusters[i],clusters[j])
但是如果没有索引,我不确定如何使用 stl 集和迭代器实现相同的效果。我尝试过:
for (set<int>::iterator itr = myset.begin(); itr != myset.end()-1; ++itr) {
cout << *itr;
}
但这失败了,因为迭代器没有 - 运算符。
我怎样才能实现这一点,或者我必须使用不同的容器?
I have a stl set of integers and I would like to iterate through all unique pairs of integer values, where by uniqueness I consider val1,val2 and val2,val1 to be the same and I should only see that combination once.
I have written this in python where I use the index of a list (clusters):
for i in range(len(clusters) - 1):
for j in range(i+1,len(clusters)):
#Do something with clusters[i],clusters[j])
but without an index I am not sure how I can achieve the same thing with a stl set and iterators. I tried out:
for (set<int>::iterator itr = myset.begin(); itr != myset.end()-1; ++itr) {
cout << *itr;
}
but this fails as an iterator doesn't have a - operator.
How can I achieve this, or must I use a different container?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
遵循以下几行怎么样:
这会产生所有
N*(N-1)/2
唯一对,其中N
是集合中整数的数量。顺便说一句:每当您迭代容器而不修改任何内容时,请使用 const_iterator ,它是很好的风格并且可能具有更好的性能。
编辑:修改代码以反映 Steve Jessop 提出的建议。
How about something along the following lines:
This yields all
N*(N-1)/2
unique pairs, whereN
is the number of integers in your set.As an aside: use a
const_iterator
whenever you iterate over a container without modifying anything, it's good style and might have better performance.EDIT: Modified the code to reflect the suggestion made by Steve Jessop.
您不需要执行
end() - 1
,因为end()
是一个指向容器中最后一个元素之后的迭代器。更正后的代码为:
You don't need to do
end() - 1
sinceend()
is an iterator that points after the last element in the container.The corrected code is:
将数据放入 boost::bimap 中,然后双向迭代,将结果复制到标准 STL 映射中,以强制唯一性。
Put your data in a boost::bimap, then iterate it both ways, copying the results into a standard STL map which will enforce uniqueness.