迭代器不能被另一个相同大小的向量重用吗?

Iterators can't be reused by another vector of the same size?

本文关键字:向量 不能 另一个 迭代器      更新时间:2023-10-16
vector< vector<int> >::iterator row;
vector<int>::iterator col;
vector<int>::iterator col2;

for (row = vec.begin(); row != vec.end(); row++) {
    col2 = row->begin(); //this needs to be row2 and row2 must be assigned with vec2.begin();
    for (col = row->begin(); col != row->end(); col++) {
    vec[col] = 23; //doesn't work because col is a pointer
    *col = 23;
    *col2 = 23; //overrides value pointed by *col

    col2++; 
    }

}

我很困惑,因为当我打印迭代器时,我得到了索引值,所以我假设 <<运算符被重载以为您提供索引值而不是迭代器指向的地址。

您的问题的简短回答是否定的,您不能安全地在另一个容器的一个实例中重用迭代器。 如果您将迭代器视为指针,这一点会更加清楚。

int* pI = &some_int;

如果我取消引用pI,我希望得到some_int的值。 它不能同时指向some_other_int

如果没有一些特定的有用代码,我无法提出替代解决方案。 但是,由于std::vector支持随机访问,如果您想访问相同大小的不同向量的 2 个元素,您可以改用索引:

std::vector<int> vec1(100, 1); // 100 elements initialized to 1
std::vector<int> vec2(100, 2); // 100 elements initialized to 2
std::vector<int> vec3(100);
for (std::size_t i = 0; i < vec1.size(); ++i) // we already know vec1, vec2, and vec3 are all the same size
{
    vec3[i] = vec1[i] + vec2[i];
}
我想

你想要:

vector< vector<int> >::iterator row;
vector<int>::iterator col;
vector<int>::iterator col2;
for (row = vec.begin(); row != vec.end(); row++) {
    col2 = row->begin();
    for (col = row->begin(); col != row->end(); col++) {
        vec[col - row->begin()] = 23;
        *col = 23;
        *col2 = 23;
        col2++;
    }
}
row2 = vec2->begin();
for (row = vec.begin(); row != vec.end(); row++)
{
    // ...
    row2++; 
}
只是语法困扰

你吗?事实上,一个迭代器在循环头中处理,而另一个迭代器在其他地方处理?因为可以在循环标头中处理两个迭代器:

for (row = vec.begin(), row2 = vec2->begin(); row != vec.end(); row++, row2++)
{
    // ...
}