如果我在下面的代码中使用 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?

本文关键字:之间 迭代器 执行 失败 编译 代码 在下面 list 如果 vector 为什么      更新时间:2023-10-16

以下代码工作正常:

#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在其代码片段中不包含行号,即使包含行号,我们也不能保证它们实际上与您编译的代码一致(即您没有在某处剪切某些行(。