反向迭代器算法
Reverse Iterator Arithmetic
所有,我试图在列表中的元素之间反向进行O(n^2)比较,所以我使用反向迭代器。
代码如下所示
#include <list>
struct Element {
double a;
double b;
};
typedef std::list<Element> ElementList;
class DoStuff {
public:
DoStuff();
void removeDuplicates(ElementList & incList) const {
for(ElementList::reverse_iterator stackIter = incList.rbegin(); stackIter != incList.rend(); ++stackIter) {
bool uniqueElement = true;
for(ElementList::reverse_iterator searchIter = stackIter+1; searchIter != incList.rend() && uniqueElement; ++searchIter) {
//Check stuff and make uniqueElement = true;
}
}
}
};
int main() {
std::list<Element> fullList;
DoStuff foo;
foo.removeDuplicates(fullList);
}
我得到一个编译错误的searchIter
创建…为什么…
这是有效的,但它是愚蠢的阅读:
ElementList::reverse_iterator searchIter = stackIter;
searchIter++;
for( ; searchIter != incList.rend() && uniqueElement; ++searchIter) {
}
错误如下:
In file included from /usr/local/include/c++/6.1.0/bits/stl_algobase.h:67:0,
from /usr/local/include/c++/6.1.0/list:60,
from main.cpp:1:
/usr/local/include/c++/6.1.0/bits/stl_iterator.h: In instantiation of 'std::reverse_iterator<_Iterator> std::reverse_iterator<_Iterator>::operator+(std::reverse_iterator<_Iterator>::difference_type) const [with _Iterator = std::_List_iterator<Element>; std::reverse_iterator<_Iterator>::difference_type = long int]':
main.cpp:16:66: required from here
/usr/local/include/c++/6.1.0/bits/stl_iterator.h:233:41: error: no match for 'operator-' (operand types are 'const std::_List_iterator<Element>' and 'std::reverse_iterator<std::_List_iterator<Element> >::difference_type {aka long int}')
{ return reverse_iterator(current - __n); }
对于某些迭代器it
和整数n
,语法it + n
要求该迭代器为"随机访问迭代器"。列表迭代器不满足这个要求。
要解决"stupid To read"的问题,您可以使用std::next
:
for(ElementList::reverse_iterator searchIter = std::next(stackIter); ...
或者,输入更少:
for(auto searchIter = std::next(stackIter); ...
相关文章:
- 如何为指向复杂值的迭代器专门化算法?
- 为什么范围算法与 std 的迭代器不兼容?
- 当迭代器(输入参数)通常不是constexpr时,constexpr算法真的有用吗
- 在 stl 算法中移动迭代器
- 指针算法是否适用于迭代器?
- 用于双向迭代器的高德纳-莫里斯-普拉特算法
- 在目标函数中使用迭代器的 STL 算法
- stl风格的算法:如何管理输出迭代器
- 为什么C++ STL 中算法、迭代器和容器是分开的
- C++前向迭代器算法
- 具有四个迭代器的类似复制的算法
- C++算法在条件为真时推进迭代器
- 将我的自定义迭代器与 STL 算法一起使用
- 哪些 STL 算法可以安全地与单通道输入迭代器一起使用
- 在find_if算法中将 char* 转换为字符串::迭代器
- 从搜索算法返回的约定 - 索引或迭代器
- 常量迭代器与可变迭代器:相同的算法不同的代码
- 自定义迭代器和 STL 算法出错
- 为什么STL算法使用指针比std::向量迭代器快得多
- c++算法的迭代器类别要求