迭代器不能被另一个相同大小的向量重用吗?
Iterators can't be reused by another vector of the same size?
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++)
{
// ...
}
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 为什么 c++ 不能打印向量 B[0]?
- C++ 不能在cout中使用向量和字符串文字
- 目标C++不能在枚举块中使用向量push_back
- 对于循环增量器不能用作字符串向量的索引
- 为什么我不能返回向量<向量<int>>(进程返回 -1073741819 (0xC0000005))
- 为什么我不能更改实例化对象内部的向量?
- C++11 向量包含 2 个不同的子类,但不能同时进行
- 为什么不能将此参数包直接解压缩到向量初始值设定项列表中?
- 为什么我不能将元素移动到不可复制的向量中?
- 为什么不能使用std :: get()获得向量的成员
- 不能在向量向量上emplace_back() 支撑初始值设定项
- 不能从文件到指针向量的对象复制
- STL 中的排序方法不能交换向量中的内容
- 特征不能直接从矩阵均值创建向量
- 为什么这个向量不能给我与数组相同的输出?
- 为什么 stl 向量不能包含协程对象?
- ofstream*的向量不能打开任何元素
- 由用户定义类型组成的向量不能使用 vector::erase();
- 带有结构体的c++向量不能工作