我有以下玩具示例:
#include<iostream>
#include<vector>
int main(){
std::vector<int> a={1, 2, 3};
std::vector<int> b={4, 5, 6};
int* pa = a.data();
int* pb = b.data();
std::swap(pa,pb);
std::cout<<"after std::swap(pa,pb)\n";
std::cout<<"a= "<<a[0]<<" "<<a[1]<<" "<<a[2]<<"\n";
std::cout<<"b= "<<b[0]<<" "<<b[1]<<" "<<b[2]<<"\n";
std::cout<<"pa= "<<pa[0]<<" "<<pa[1]<<" "<<pa[2]<<"\n";
std::cout<<"pb= "<<pb[0]<<" "<<pb[1]<<" "<<pb[2]<<"\n";
std::swap(a,b);
std::cout<<"after std::swap(a,b)\n";
std::cout<<"a= "<<a[0]<<" "<<a[1]<<" "<<a[2]<<"\n";
std::cout<<"b= "<<b[0]<<" "<<b[1]<<" "<<b[2]<<"\n";
std::cout<<"pa= "<<pa[0]<<" "<<pa[1]<<" "<<pa[2]<<"\n";
std::cout<<"pb= "<<pb[0]<<" "<<pb[1]<<" "<<pb[2]<<"\n";
}
交换之后会发生什么(pa,pb)对我来说很清楚,我希望pa指向b.data(),但是在交换(a,b)之后,我希望b.data()现在指向&#34 ; 1 2 3&#34;,但打印出pa [0],pa [1],pa [2] ...时不是这种情况......
答案 0 :(得分:2)
http://en.cppreference.com/w/cpp/container/vector/swap注意到:
所有迭代器和引用仍然有效。过去的迭代器无效。
这意味着内存分配保持不变,矢量字段交换
std::vector<int> a={1, 2, 3}; // data lays at pa
std::vector<int> b={4, 5, 6}; // data lays at pb
int* c = a.data(); // == pa
int* d = b.data(); // == pb
std::swap(c,d); // c == pb, d == pa
std::cout<<"after std::swap(c,d)\n";
std::cout<<"a= "<<a[0]<<" "<<a[1]<<" "<<a[2]<<"\n";
std::cout<<"b= "<<b[0]<<" "<<b[1]<<" "<<b[2]<<"\n";
std::cout<<"c= "<<c[0]<<" "<<c[1]<<" "<<c[2]<<"\n";
std::cout<<"d= "<<d[0]<<" "<<d[1]<<" "<<d[2]<<"\n";
std::swap(a,b); // c == pb, d == pa, a == pb, b == pa
std::cout<<"after std::swap(a,b)\n";
std::cout<<"a= "<<a[0]<<" "<<a[1]<<" "<<a[2]<<"\n";
std::cout<<"b= "<<b[0]<<" "<<b[1]<<" "<<b[2]<<"\n";
std::cout<<"c= "<<c[0]<<" "<<c[1]<<" "<<c[2]<<"\n";
std::cout<<"d= "<<d[0]<<" "<<d[1]<<" "<<d[2]<<"\n";
答案 1 :(得分:0)
向量倾向于使用指向数据的指针来实现。所以,假设内存中有一个名为foo
的地方,其中 是{1, 2, 3}
和bar
的起始位置,其中 {4, 5, 6}
的起始位置
std::vector<int> a={1, 2, 3};
std::vector<int> b={4, 5, 6};
a
是一个指针指向foo
的向量
b
是一个指针指向bar
int* c = a.data();
int* d = b.data();
c
是一个指向a
指针当前指向的指针; foo
d
是一个指针,指向b
指针当前指向的内容; bar
现在,让我们做一些交换......
std::swap(c, d);
c
是一个指针,现在指向d
指向的内容; bar
d
是一个指针,现在指向c
所指向的内容; foo
因此,c
现在指向{4, 5, 6}
,而d
现在将指向{1, 2, 3}
std::swap(a, b);
a
的指针现在指向b
指针指向的内容; bar
b
的指针现在指向a
指针指向的内容; foo
交换向量交换他们指向的内容;它不会交换里面的实际数据。