2

有时我会想使用算法库中函数返回的迭代器。当我在修改函数和非修改函数之间切换时,就会出现我面临的问题。因为在非修改函数中我想使用const_iterator. 作为一个玩具示例:

vector<int> v = { 1, 8, 7, 4, 3, 6, 2, 5 };
auto it = partition(begin(v), end(v), bind(greater<int>(), placeholders::_1, 3));

cout << (find(cbegin(v), it, 13) != cend(v)) << endl;

当我尝试编译此代码时,出现错误:

没有匹配的调用函数find(std::vector<int>::const_iterator, __gnu_cxx::__normal_iterator<int*, std::vector<int> >&, int)

我遇到的问题是我能找到的唯一转换过程可能很昂贵:auto cit = next(cbegin(v), distance(begin(v), it))

有没有办法让这个工作?或者我是卡住转换还是只使用非const_iterators?

4

3 回答 3

4

您可以指定模板参数:

find<decltype(cbegin(v))>(cbegin(v), it, 13) != cend(v)

演示

于 2017-02-16T20:19:52.720 回答
3

It's much less expensive to simply cast the mutable iterator to a constant iterator:

cout << (find(cbegin(v), vector<int>::const_iterator{it}, 13)
      != cend(v)) << endl;

A mutable iterator should always be castable into a constant iterator.

EDIT: I found the part of the standard that guarantees that an iterator is convertible to a constant iterator.

Table 96 in section 23.2 "Container requirements" specifies that the expression X::iterator results in:

any iterator category that meets the forward iterator requirements. convertible to X::const_iterator.

于 2017-02-16T20:15:17.043 回答
1

有三种方法。

第一个是写

cout << (find( begin(v), it, 13) != cend(v)) << endl;
               ^^^^^

第二个是写

cout << (find(cbegin(v), static_cast<std::vector<int>::const_iterator>( it )
, 13) != cend(v)) << endl;

或者更短

cout << (find(cbegin(v), static_cast<decltype( v.cbegin())>( it )
, 13) != cend(v)) << endl;

第三个是写

cout << (find<std::vector<int>>::const_iterator>( cbegin(v), it, 13) != cend(v)) << endl;

或更短

cout << (find<decltype( v.cbegin())>( cbegin(v), it, 13) != cend(v)) << endl;
于 2017-02-16T20:21:18.477 回答