重命名向量而不是复制它

时间:2012-04-03 08:58:54

标签: c++ stl reference rename swap

我想做以下事情。但不知道如何:

    //have two vectors: vector1 (full of numbers), vector2 (empty)
    //with vectors, I mean STL vectors
    //outer loop
    {
    //inner loop 
    {
    //vector2 gets written more and more over iterations of inner loop
    //elements of vector1 are needed for this
    } //end of inner loop
    //now data of vector1 is not needed anymore and vector2 takes the role of
    //vector 1 in the next iteration of the outer loop

    //old approach (costly):
    //clear vector1 ,copy vector2's data to vector1, clear vector2

    //wanted: 
    //forget about vector1's data
    //somehow 'rename' vector2 as 'vector1' 
    //(e.g. call vector2's data 'vector1')
    //do something so vector2 is empty again
    //(e.g. when referring to vector2 in the next
    //iteration of outer loop it should be an empty vector in the
    //beginning.)

    } // end of outer loop

我在尝试

     vector<double> &vector1 = vector2;
     vector2.clear();

但我认为问题是vector1然后是对vector2的引用,然后将其删除。

有什么想法吗?

4 个答案:

答案 0 :(得分:5)

可能使用std::vector::swap

vector<double> vector1;
vector1.swap(vector2);

答案 1 :(得分:4)

您是否了解此功能:http://www.cplusplus.com/reference/stl/vector/swap/

// swap vectors
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  unsigned int i;
  vector<int> first;   // empty
  vector<int> second (5,200);  // five ints with a value of 200

  first.swap(second);

  cout << "first contains:";
  for (i=0; i<first.size(); i++) cout << " " << first[i];

  cout << "\nsecond contains:";
  for (i=0; i<second.size(); i++) cout << " " << second[i];

  cout << endl;

  return 0;
}

此功能的复杂性保证不变。

答案 2 :(得分:3)

尝试交换。

std::vector<double> vector2;

{
    std::vector<double> vector1;
    // ... fill vector1
    std::swap(vector1,vector2);  
}

// use vector2 here.

答案 3 :(得分:1)

您可以执行以下操作(如果要保留其值,请不要使用对其他向量的引用):

  • 重载复制构造函数(请参阅here),以便旧向量的元素将被复制到新向量(仅当向量的元素不是原始向量时才需要)
  • 使用复制构造函数

另一种方法是使用交换功能。