I have a vector of pointers to vectors:
main(...)
{
//...
std::vector< std::vector<double> * > ds = getDS(...)
//...
}
std::vector<std::vector<double> * > getDS(int m, ...)
{
std::vector<std::vector<double> * > wavefunctions = *(new std::vector<std::vector<double>*>(m));
int n = int( params.rmax() / params.dr() );
std::ifstream input_wf;
input_wf.open(filename.c_str());
input_wf.setf(std::ios::showpoint | std::ios::scientific);
for(int i=0; i < nbasis; i++)
{
std::vector<double> *wf = new std::vector<double>(n);
//(wavefunctions[i]) = new std::vector<double>(n);
for (unsigned int ir=0; ir < wf->size(); ir++)
input_wf >> ( *wf )[ir];
wavefunctions.push_back(wf);
}
input_wf.close();
return wave functions;
}
However, I keep getting a EXC_BAD_ACCESS error when I try to access wavefunctions[0]->at(some legal value) after going through the loop once, during debugging. (There should be something there, but I’m not sure why there isn’t… Any ideas?
The following line,
is problematic in your case for two reasons –
newis copied intowavefunctions, and then the pointer to it is lost. This is not Java…mentries in your vector. Subsequentpush_back‘s add to thatmentries, so when you try to accesswavefunctions[0]you actually access an entry which was created in this line, not the first one to be pushed in theforloop.To solve the problem, change the line to
The
reservemethod makes sure you will not have reallocations during thepush_back‘s.As a last note, depending on the circumstenses, the compiler may or may not be able to optimize away the inherent copy of vectors that is performed on return from the function. To be sure, you might want to learn more about r-value references (
&&) or simply return the vector by address (that is, as another parameter of typevector<...> *and return typevoid).