C++ Set: No match for - operator

∥☆過路亽.° 提交于 2021-02-16 20:06:35

问题


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)

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)

Thanks!


回答1:


Yes, there are different types of iterators and operator- is not supported for set iterators which are not random access.

You can use std::distance( mySet.begin(), iter );

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.

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.

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.



来源:https://stackoverflow.com/questions/13515261/c-set-no-match-for-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!