[英]Iterator assignment in a condition - vector iterators incompatible
I have a wrapper for std::vector
and I've implemented function that replaces a section within a vector with another vector. 我有一个
std::vector
的包装器,我已经实现了用另一个向量替换向量中的一个部分的函数。 I've tried to put the assignment of an iterator directly in the if
condition and got unexpected results . 我试图将迭代器的赋值直接放在
if
条件中,并得到意想不到的结果 。
I'm using Visual Studio 2013 and with FAIL
defined I get Debug Assertion Failed! 我正在使用Visual Studio 2013并且使用
FAIL
定义我得到Debug Assertion失败! - vector iterators incompatible . - 矢量迭代器不兼容 。 Is it possible that the condition is being evaluated from right to left?
是否有可能从右到左评估病情? I can't get over it.
我无法克服它。
This is a (poorly implemented) code that reproduces my problem - meant to replace 3rd and 4th elements of vec
with 1st and 2nd elements of vec_second
: 这是一个(执行不佳)代码,它可以重现我的问题 - 用
vec_second
第一和第二个元素替换vec
第三和第四个元素:
#include <iostream>
#include <vector>
#include <iterator>
using std::cout;
//#define FAIL
int main()
{
std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int> vec_second = {6, 7};
auto it = vec.begin() + 2;
#ifndef FAIL
it = vec.erase(it, it + vec_second.size());
if(it == vec.end())
#else
if((it = vec.erase(it, it + vec_second.size())) == vec.end())
#endif
vec.reserve(vec.size() + vec_second.size());
vec.insert(it, vec_second.begin(), vec_second.end());
for(auto const& x : vec)
cout << x << " ";
}
But runs fine on Coliru's GCC . 但在Coliru的GCC上运行良好。
if((it = vec.erase(it, it + vec_second.size())) == vec.end())
Since there is no sequence point between them, a compiler is free to call erase
and end
in either order. 由于它们之间没有序列点,因此编译器可以自由调用
erase
并以任何顺序end
。 If end
gets called first, that iterator is immediately invalidated by erase
, leading to undefined behavior. 如果首先调用
end
,那么迭代器会立即因erase
失效,从而导致未定义的行为。
Your #ifndef FAIL
code is the safe way to do this. 你的
#ifndef FAIL
代码是安全的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.