更改原始矢量不会在集合中更改它

时间:2011-12-02 00:08:32

标签: c++ pointers reference

为什么我会得到不同的输出?我怎样才能解决这个问题?我希望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 ;

2 个答案:

答案 0 :(得分: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 :(得分: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;
}