理解std :: swap的指针和std :: vectors

时间:2016-11-23 14:04:43

标签: c++ swap

我有以下玩具示例:

#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] ...时不是这种情况......

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
交换向量交换他们指向的内容;它不会交换里面的实际数据。