简体   繁体   中英

C++ store vector in array during loop

Hi I'm new to C++ and am trying to do something that is very easy to do with Matlab. I have a for loop which computes a vector. I would like to then store this vector so that I can access it outside of the loop.

for(ii=0; ii < numObs; ii++} {
    someVector = ...
    someMatrix[ii][:] = someVector
}

The someMatrix[ii][:] doesn't work of course, but that's what I would like to do. Any help's appreciated, thanks!

Clarification: someVector is an 1xn element vector which is computed each time in the loop. I simply want to store it in either a matrix or array (not sure what) so that I can call someMatrix[ii] and get the vector back.

You're probably looking for something like:

std::vector<std::vector<double>> matrix; // matrix - vector of vectors
for(int i = 0; i < numObs; ++i) {
    std::vector<double> vec = ... // your calculations go here
    // if no C++11 - don't use std::move
    matrix.push_back(std::move(vec)); 
}

One of the drawbacks here is that you have to assure in calculation code that each vector will have same number of elements (the code above doesn't verify it).

Note, that this is definitely not the optimal way for handling matrices and I'd recommend you to take a look at some dedicated libraries (boost::numeric, OpenCV for image processing, Armadillo or one of a dozen others) if you want to perform serious computations on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM