以下代码可以正常工作:
#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;
}
但是,如果容器的类型从 vector 更改为列表,则编译将失败。它显示以下错误:
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
并非随机访问迭代器,并且不支持减法。
供以后引用,如果您发布一段代码和带有行号的错误,则应以某种方式指出代码中的哪一行。因此,在代码段中不包含行号,即使包含代码行,我们也无法保证它们实际上与您编译的代码对齐(即您未在某些地方剪断某些行)。
关于c++ - 如果在以下代码中使用list而不是vector,为什么在尝试在迭代器之间执行减法的行中编译失败?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50550119/