I am trying to return a vector of some of the elements in a vector. I wish to modify one of the elements in this new vector and have it automatically update the value in the original vector.
I tried this:
#include <iostream>
#include <vector>
class TestClass
{
public:
TestClass();
void OutputData();
//std::vector<double&> GetOddElements(); // can't do this!
std::vector<double*> GetOddElements();
double& GetElement();
private:
std::vector<double> Data;
};
/*
// Can't do this!
std::vector<double&> TestClass::GetOddElements()
{
std::vector<double&> oddElements;
oddElements.push_back(this->Data[1]);
}
*/
std::vector<double*> TestClass::GetOddElements()
{
std::vector<double*> oddElements;
oddElements.push_back(&(this->Data[1]));
}
TestClass::TestClass()
{
this->Data.push_back(0);
this->Data.push_back(1);
this->Data.push_back(2);
}
void TestClass::OutputData()
{
for(unsigned int i = 0; i < this->Data.size(); i++)
{
std::cout << Data[i] << " ";
}
}
int main(int argc, char *argv[])
{
TestClass test;
test.OutputData();
std::cout << std::endl;
std::vector<double*> oddElements = test.GetOddElements();
std::cout << oddElements.size();
//*(oddElements[0]) = 6;
test.OutputData();
return 0;
}
but it doesn't work (it outputs
0 1 2 3
3020671560 1 2 3
when I would expect/want to see:
0 1 2 3
0 6 2 3
)
And it also segfaults upon exit.
Can anyone see where I've gone wrong here?
Thanks,
David