【发布时间】:2016-03-09 14:22:32
【问题描述】:
我需要找出std::set 中有多少元素低于给定元素。
我认为正确的函数是std::lower_bound,它返回一个迭代器到第一个大于或等于给定元素的元素..所以这个迭代器的索引就是我要找的.. .但我无法从迭代器中找到索引:
#include <iostream>
#include <algorithm>
#include <set>
int main()
{
std::set<int> mySet;
mySet.insert( 1 );
mySet.insert( 2 );
mySet.insert( 3 );
mySet.insert( 4 );
std::set<int>::const_iterator found = std::lower_bound( mySet.begin(), mySet.end(), 2 );
if ( found != mySet.end() )
std::cout << "Value 2 was found at position " << ( found - mySet.begin() ) << std::endl;
else
std::cout << "Value 2 was not found" << std::endl;
}
这不会编译:
16:63: error: no match for 'operator-' (operand types are 'std::set<int>::const_iterator {aka std::_Rb_tree_const_iterator<int>}' and 'std::set<int>::iterator {aka std::_Rb_tree_const_iterator<int>}')
16:63: note: candidates are:
In file included from /usr/include/c++/4.9/vector:65:0,
from /usr/include/c++/4.9/bits/random.h:34,
from /usr/include/c++/4.9/random:49,
from /usr/include/c++/4.9/bits/stl_algo.h:66,
from /usr/include/c++/4.9/algorithm:62,
from 3:
使用 std::vector 代替 std::set 可以工作perfectly。
看起来 operator- 对 std::set::iterator 无效。为什么?
那么,你怎么能轻松地(不调用std::previous 或std::next 直到达到界限......这不会有效)找到给定迭代器在容器中的位置?如果不能,那么我可以使用什么替代方法来查找给定元素的索引...?
【问题讨论】: