简体   繁体   English

std :: iterator的运算子

[英]Operators of std::iterator

I have assumed that iterators had overloaded their operator+ and operator- to return an iterator. 我假设迭代器已重载了他们的operator +和operator-以返回迭代器。 I also assumed that iterators had overloaded operator int(), which made the following compile: 我还假设迭代器已重载了运算符int(),从而进行了以下编译:

std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);

std::vector<int>::iterator low = std::lower_bound(v.begin(), v.end(), 2);

int i = low - v.begin();

But when I tried assigning the result to an iterator instead of an int i got a compile error: 但是当我尝试将结果分配给迭代器而不是int时,出现了编译错误:

std::vector<int>::iterator i = low - v.begin();

Why doesnt subtracting an iterator from another result in an iterator? 为什么不从另一个迭代器中减去一个迭代器导致一个迭代器?

I cant find any information on cplusplus.com/reference or anywhere else on exactly what the interface of an iterator contains. 我无法在cplusplus.com/reference上找到任何信息,也无法在迭代器的接口所包含的任何其他地方找到任何信息。

"Why doesnt subtracting an iterator from another result in an iterator?" “为什么不从另一个结果中减去一个迭代器会导致迭代器出现?”

Why would it, subtracting 2 pointers does not result in another pointer. 为什么这样做,减去2个指针不会导致另一个指针。

If anything I would expect it to return the distance between the 2 iterators in units of contained elements - ie an int 如果有什么期望的话,它会返回两个迭代器之间的距离,以包含元素为单位-即一个int

and a quick test shows that it does return the distance 快速测试表明它确实返回了距离

vector<int> test;
test.push_back(1);
  test.push_back(2);
int d = test.begin() - test.end();
cout << d;
return 0;

says : -2 说:-2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM