更名矢量而不是复制它

更名矢量而不是复制它

问题描述:

我想要做以下事情。但不知道如何:更名矢量而不是复制它

//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(); 

,但我认为这个问题是向量1则是vector2参考,然后将其删除。

任何想法?

+2

您不能使用对另一个向量的引用,然后删除向量中的数据。如果你想删除vector2中的数据,但仍然保存在vector1中,你需要做一个**拷贝**,没有两种方法。 – 2012-04-03 09:01:46

+0

所以我必须复制数据,尽管我想要的是一些现有数据的不同名称?我知道这不适用于这样的参考,但希望有一个想法。 – user1304680 2012-04-03 09:04:25

+0

让我问你“重命名一个矢量”的整个点是什么 – 2012-04-03 09:19:12

你知道这个功能: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; 
} 

此功能的复杂性是保证恒定。

+0

非常感谢。交换工作完美,易于使用,比我之前使用的复制指令更有效率 – user1304680 2012-04-03 09:19:34

一种可能性是使用std::vector::swap

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

尝试交换。

std::vector<double> vector2; 

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

// use vector2 here. 

你可以做以下的(如果你想保持自己的价值观不使用参考其他载体):

  • 超载的拷贝构造函数(见here),使老向量的元素将会被复制到新的载体(这一点,如果您的向量的元素不是原始的,才需要)
  • 使用拷贝构造函数

的人ternative是使用交换功能。