简体   繁体   中英

What does the C++ standard say about std::vector<int> v1,v2; std::distance(v1.begin(),v2.begin())?

I have this code

#include <vector>
#include <iostream>

int main(int argc, char* argv[])
{
   std::vector<int> v1,v2;
   std::cout << std::distance(v1.begin(),v2.begin());
   return 0;
}

and it has a bug because it is not meaningful to compare the iterators of two different vectors.

I had a look at N3376 at 24.4.4 Iterator operations at page 815:

 template<class InputIterator> typename iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last); 

Requires : If InputIterator meets the requirements of random access iterator, last shall be reachable from first or first shall be reachable from last ; otherwise, last shall be reachable from first .

Now I think that Requires is not fulfilled.

What does the standard state should happen in this case?

[iterator.requirements.general]:

An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j .

The problem is that once you incremented v1.begin() v1.size()-1 times, the next increment operation induces undefined behavior, so v2.begin() cannot be reached from v1.begin() . The same argument makes v1.begin() unreachable from v2.begin() .


In case your question was "What happens if a condition in a Requires section is violated?", look at [res.on.required]:

Violation of the preconditions specified in a function's Requires: paragraph results in undefined behavior unless the function's Throws: paragraph specifies throwing an exception when the precondition is violated.

In some implementations of std::distance , the first iterator is incremented until it reaches the second iterator. The iterations are counted:

unsigned int counts = 0;
while (iter1 != iter2)
{
  ++counts;
  ++iter1;
}

If the iterators point to containers in different address spaces, the loop many not terminate. Using the terms in the standard, the second iterator is not reachable .

不满足requires ,这意味着代码具有未定义的行为:任何事情都可能发生。

In this case will be undefined behavior. Because last is not reachable from first by (possibly repeatedly) incrementing first .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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