2011-12-02 53 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