交换向量和指针无效
c++: swapping vectors and pointer invalidation?
我似乎有一个问题,交换两个向量的元素。我有两个向量,x
和y
,它们包含类型为myclass
的对象。myclass
只有一个公共成员w
。我创建了一个指向x
的成员w
的指针向量,然后交换向量x
和y
。我希望指针向量仍然指向x
的w
成员,但情况似乎并非如此。
这里有一个简单的例子来重现我的问题。
#include <iostream>
#include <vector>
using namespace std;
struct myclass
{
double w;
};
int main()
{
vector<myclass> x(10);
for(int i=0; i!=10; i++) x[i].w = i;
for(auto el : x) std::cout << el.w << std::endl; /* prints i */
std::cout << std::endl;
vector<double *> px(10);
for(int i=0; i!=10; i++) px[i] = &x[i].w;
for(auto el : px) std::cout << *el << std::endl; /* prints i */
std::cout << std::endl;
vector<myclass> y(10);
for(int i=0; i!=10; i++) y[i].w = 2*i;
for(auto el : y) std::cout << el.w << std::endl; /* prints 2*i */
std::cout << std::endl;
y.swap(x);
for(auto &el : x) std::cout << &el.w << " " << el.w << std::endl; /* prints 2*i as it should */
std::cout << std::endl;
for(auto &el : px) std::cout << el << " " << *el << std::endl; /* should print 2*i, but prints i */
std::cout << std::endl;
}
注意x
和y
交换了元素,但px
仍然指向旧的元素。我读到使用swap
不应该使指针/迭代器无效。这是对的吗,还是我遗漏了什么?提前感谢!
指针和迭代器不会失效,但它们遵循容器的内容。
x
的内容被交换到y
,但是迭代器和指向这些值的指针仍然指向它们(即使它们现在在y
中)。
想想看,它怎么可能以其他方式工作呢?如果交换两个长度不等的容器,则指向较长容器末尾附近元素的指针在较短容器中指向什么?如果每个容器的元素都必须在内存中移动以确保指针保持有效,那么如何在O(1)
中实现swap()
呢?
相关文章:
- 如何实现容纳整数和无效指针的双向链表?
- 在基数排序中,我得到 munmap_chunk():无效指针和中止(核心转储).为什么?
- 应用地址清理器后,免费无效指针消失
- C++ 在具有数组成员的类上无效指针/双精度释放
- 不断得到分段错误和free()无效指针
- 使用无效指针初始化指针声明符的行为是否未定义?
- 结构作为参数的函数产生错误:free():无效指针:0x00007efd47b
- 无效指针、隔离标识符等
- c++ 无效指针从空闲列表中取消排队
- C++ munmap_chunk(): 无效指针:
- 为什么我的简单C++程序使用队列和 fstream 错误到无效指针
- 无效指针和非初始化的指针之间的差异
- 如何用无效指针初始化unique_ptr的向量
- 地址清理器在静态强制转换无效指针时报告错误
- MS4:Free(Free()无效指针0xB74E74E0 ***
- ***检测到的GLIBC *** MS2:free():无效指针:0xB7526FF4 ***
- 无效指针功能的输出
- 有人能告诉我这是如何在main()中实现的吗?(关于无效指针的问题)
- C++11使用智能指针,但得到无效指针
- 无效指针的相关性