2011-12-02 50 views
2

爲什麼我會得到不同的輸出?我怎樣才能解決這個問題?我想trainingVector [0]引用A.更改原始矢量不會改變它的集合

vector<double> A(4,0); 
vector<vector<double > > trainingVector; 
A[0]=1; 
trainingVector.push_back(A); 
A[0]=2; 
cout << A[0] << endl ; 
cout << trainingVector[0][0] << endl ; 
+0

請添加更多的細節,包括如何聲明並分配變量。 –

+0

好的,我將其包含在內。現在嘗試下面的答案:) – sks

回答

2

不能存儲在STD容器引用,所以你問什麼是不可能的。如果你想trainingVector指針存儲A,這是完全可行的:

vector<double> A(4,0); 
vector<vector<double>*> trainingVector; 

A[0] = 1; 
trainingVector.push_back(&A); 
A[0] = 2; 

// notice that you have to dereference trainingVector[0] to get to A 
cout << (*trainingVector[0])[0] << endl; // prints 2 
+1

謝謝。它工作:) – sks

0

你可以存儲指向A代替:

#include <iostream> 
#include <vector> 

int main() 
{ 
    std::vector<int> A(1); 
    A[0] = 1; 
    std::vector<std::vector<int>*> trainingVector; 
    trainingVector.push_back(&A); 
    A[0] = 2; 
    std::cout << A[0] << std::endl; 
    std::cout << (*trainingVector[0])[0] << std::endl; 
    return 0; 
} 

或者,如果你真的想在語法中的問題指定的,你可以做這樣的事情:

#include <iostream> 
#include <vector> 

template <typename T> 
class VecRef 
{ 
private: 
    std::vector<T> *m_v; 

public: 
    VecRef(std::vector<T>& v) 
    : m_v(&v) 
    {} 

    T& operator[](int i) 
    { 
     return (*m_v)[i]; 
    } 
}; 

int main() 
{ 
    std::vector<int> A(1); 
    A[0] = 1; 
    std::vector<VecRef<int>> trainingVector; 
    trainingVector.push_back(A); 
    A[0] = 2; 
    std::cout << A[0] << std::endl; 
    std::cout << trainingVector[0][0] << std::endl; 
    return 0; 
} 
+0

謝謝,我已經改變了語法,所以第一個解決方案爲我工作!對不起,我無法接受兩個答案:( – sks