“No match for operator-” error on simple iterator difference

做~自己de王妃 提交于 2019-12-04 18:53:50

Because this operation can't be implemented efficiently on a std::set, it is not provided. std::set provides (Constant) Bidirectional Iterators, that can be moved in either direction, but not jumped arbitrary distances, like the Random Access Iterators provided by std::vector. You can see the hierarchy of iterator concepts here.

Instead, use the std::distance function, but be aware that for this case, this is an O(n) operation, having to walk along every step between the two iterators, so be cautious about using this on large std::sets, std::lists, etc.

std::set iterators are BidirectionalIterators, not RandomAccessIterators. The former do not define operator-. Use std::distance to calculate the difference between the iterators.

#include <iterator>
// ...
auto x = std::distance(st.begin(), st.find(1));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!