C ++设置:-不匹配-运算符
我有一个集合,即multiset类型,我正在尝试使用upper_bound函数查找迭代器返回的元素的索引.通常与向量一起使用,如果我得到迭代器并从中减去vector.begin()以获得答案,它就可以工作.
但是,当我尝试使用一个集合时,它会出现STL错误,在...(省略STL详细信息)中说操作符不匹配-"
I have a set, namely of type multiset , I'm trying to use the upper_bound function to find the index of the element returned by the iterator. Usually with vectors, it works if I get the iterator and subtract vector.begin() from it to get the answer.
However, when I try this with a set it gives an STL error, saying "no match for operator -' in ...(omitting STL details)
这是否有一个根本原因(集被实现为RB树).如果是这样,有人可以建议替代吗?(我正在尝试在编程站点上解决问题)
Is there a fundamental reason for this ( sets being implemented as RB-trees and all). If so, can anyone suggest an alternate to this? ( I'm trying to solve a question on a programming site)
谢谢!
是的,有不同类型的迭代器,并且不是随机访问的set迭代器不支持 operator-
.
Yes, there are different types of iterators and operator-
is not supported for set iterators which are not random access.
您可以使用 std :: distance(mySet.begin(),iter);
我认为对于std :: set(和多集)来说,它可能是 O(log N)
操作,相比之下,它对于矢量来说是恒定时间,对于列表来说是线性时间.
I think that for std::set (and multiset) this is likely to be an O(log N)
operation compared to it being constant time for vector and linear for list.
您确定要将数据存储在 std :: multiset
中吗?您可以改用排序向量.如果向量需要定期编辑,则向量会变慢,也就是说,您尝试在保持其排序状态的同时从任何位置插入和删除元素.如果将数据一次构建然后多次访问,则排序后的向量有时会更有效.
Are you sure you want to be storing your data in a std::multiset
? You could use a sorted vector instead. Where the vector would be slower is if it is regularly edited, i.e. you are trying to insert and remove elements from anywhere, whilst retaining its sorted state.
If the data is built once then accessed many times, a sorted vector can sometimes be more efficient.
如果数据集很大,请考虑使用 std :: deque
而不是 std :: vector
,因为 deque
在不需要连续的内存块.
IF the data set is very large, consider using std::deque
rather than std::vector
because deque
is more scalable in not requiring a contiguous memory block.