如果我在下面的代码中使用 list 而不是 vector,为什么在我尝试在迭代器之间执行减法的行中编译失败?
If I use list instead of vector in the following code, why compilation is failed in the line where I try to perform subtraction in between iterators?
以下代码工作正常:
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
vector<int> v1;
vector<int>::iterator it, low, up;
for (int i=1; i<=10; i++)
v1.push_back(i);
cout << "elements are- n";
for(it=v1.begin(); it!=v1.end(); it++)
cout << *it << " ";
sort(v1.begin(), v1.end());
low = lower_bound(v1.begin(), v1.end(), 3);
up = upper_bound(v1.begin(), v1.end(), 6);
cout << "npos of low- " << (low-v1.begin()) << "n";
cout << "pos of up- " << (up-v1.begin()) << endl;
return 0;
}
但是,如果将容器的类型从向量更改为列表,则编译将失败。它显示以下错误:
In function 'int main()': 20:35: error: no match for 'operator-'
(operand types are 'std::list<int>::iterator {aka
std::_List_iterator<int>}' and 'std::list<int>::iterator {aka
std::_List_iterator<int>}')
std::lower_bound
工作正常。(尽管它没有达到应有的效率。没有的是你试图从一个迭代器中减去另一个迭代器,因为std::list::iterator
不是随机访问迭代器,不支持减法。
为了将来参考,如果您发布一段代码和一个带有行号的错误,您应该以某种方式指出代码中的哪一行。SO在其代码片段中不包含行号,即使包含行号,我们也不能保证它们实际上与您编译的代码一致(即您没有在某处剪切某些行(。
相关文章:
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 对于C++随机访问迭代器(矢量迭代器),迭代器之间的差异是如何计算的?
- 如果我的容器位于两个现有值之间,那么伪造迭代器类别是否合理
- 迭代器和标量对象之间的未定义行为有什么区别吗?
- 如果我在下面的代码中使用 list 而不是 vector,为什么在我尝试在迭代器之间执行减法的行中编译失败?
- 正则表达式使用提升令牌迭代器在单引号和括号之间提取值
- const矢量和const迭代器之间的差异
- C STL,我想知道地图中的双向迭代器和操作员[]之间有什么不同
- 遍历std ::映射,效果少于迭代器之间的比较
- 如何计算标准::矢量::<int>迭代器和标准::矢量<int>::reverse_iterator之间的距离?
- 映射::擦除:按键擦除或迭代器擦除之间的区别
- 如何获取两个迭代器之间的元素总数
- std::set::迭代器和std::set::const_iterator之间是否存在操作差异
- 一对迭代器之间的子序列的gtest/gmock匹配器
- 检查对象之间的冲突时,列表迭代器不可递增
- 容器末端和指向内部项的迭代器之间的区别.C++
- 迭代器和const_iterator之间的比较是否效率低下
- MapValue 和迭代器 C++ 之间的比较
- C++:对迭代器之间计算距离的类型感到困惑
- 在两个迭代器之间获取“std::string”的子字符串