2012-04-03 93 views
1

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

//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

回答

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; 
} 

此功能的複雜性是保證恆定。

+0

非常感謝。交換工作完美,易於使用,比我之前使用的複製指令更有效率 – user1304680 2012-04-03 09:19:34

3

嘗試交換。

std::vector<double> vector2; 

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

// use vector2 here. 
1

你可以做以下的(如果你想保持自己的價值觀不使用參考其他載體):

  • 超載的拷貝構造函數(見here),使老向量的元素將會被複制到新的載體(這一點,如果您的向量的元素不是原始的,才需要)
  • 使用拷貝構造函數

的人ternative是使用交換功能。