C++ 为什么矢量的内容在这里打印错误? #包括 #包括 #包括 使用名称空间std; int main() { int检验=0; 向量{1,2,3}; 对于(自动i=v.cbegin();i!=v.cend();++i) { ++试验; 如果(测试==2) { v、 推回(4); } cout

C++ 为什么矢量的内容在这里打印错误? #包括 #包括 #包括 使用名称空间std; int main() { int检验=0; 向量{1,2,3}; 对于(自动i=v.cbegin();i!=v.cend();++i) { ++试验; 如果(测试==2) { v、 推回(4); } cout,c++,c++11,vector,C++,C++11,Vector,如果新项不适合向量容量(内部大小),则push_back可以更改开始和结束迭代器。在您的示例中,push_back意味着重新分配内部缓冲区,并且开始和结束迭代器获取新值。在您的示例中,问题是将为每个步骤计算结束迭代器,它获取新值,但开始迭代器仍保留旧(无效)值,这会导致未定义的行为。 以下更改将说明发生的情况: #include <iostream> #include <string> #include <vector> using namespace st

如果新项不适合向量容量(内部大小),则push_back可以更改开始和结束迭代器。在您的示例中,push_back意味着重新分配内部缓冲区,并且开始和结束迭代器获取新值。在您的示例中,问题是将为每个步骤计算结束迭代器,它获取新值,但开始迭代器仍保留旧(无效)值,这会导致未定义的行为。 以下更改将说明发生的情况:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    int test=0;
    vector<int>v{1,2,3};
    for(auto i=v.cbegin();i!=v.cend();++i)
    {
        ++test;
        if(test==2)
        {
            v.push_back(4);
        }
        cout<<*i<<endl;
    }
    return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
int检验=0;
向量{1,2,3};
对于(自动i=v.cbegin();i!=v.cend();++i)
{
++试验;
如果(测试==2)
{

std::cout
v.push_back(4);
使迭代器无效(如果需要移动向量的内容,这里可能就是这种情况),这意味着之后的一切都在调用未定义的行为。你在遍历向量时正在更改向量?这是一个奇怪的想法。我想测试一下如果我这样做会发生什么,但输出是意外的,因此出现了问题。请发布文本输出,而不是在单独的图像中(图像可能会随着时间而失效)请注意,
push_-back()
仅在必须重新分配基础数组时(当新的
size()
将超过当前的
capacity()
)才会使现有的非结束迭代器失效。我的观点是,“push_-back更改开始迭代器和结束迭代器”有点误导。它可能会更改
开始
迭代器,也可能不会更改。这取决于
推回()时向量的当前
大小
容量
被调用。但它会更改
结束
迭代器,因为它是在向量的末尾插入的。@RemyLebeau我同意你的意见,并更新了答案
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
    int test=0;
    vector<int>v{1,2,3};
    for(auto i=v.cbegin();i!=v.cend();++i)
    {
        ++test;
        if(test==2)
        {
            std::cout << &*v.cbegin()<<std::endl;
            std::cout << &*v.cend()<<std::endl;
            v.push_back(4);
            std::cout << &*v.cbegin()<<std::endl;
            std::cout << &*v.cend()<<std::endl;
        }
        cout<<*i<<endl;
    }
    return 0;
}