abi.ravi0901
abi.ravi0901

Reputation: 111

How to initialize a 2-d vector with vectors of different sizes

I am looking to initialize a 2-D vector with vectors of different sizes. The number of vectors (of doubles) within the 2-d vector as well as the size of each vector is already known. I initially just thought of having the sizes of each vector in a separate vector and using a for loop to initialize the code. However, i found this very costly in run-time and was looking to use an optimized method.

In the header file, I already set many of the sizes for other vectors, but cannot seem to determine a method to initialize the vectors with different sizes.

std::vector<std::vector<double>> assetWeight = std::vector<std::vector<double>>(10); //initialization of the 2-d vector
for(int i = 0; i < sectorNum; i++){
    assetWeight[i].resize(sectorSize[i]); 
} //current method of setting the individual vector sizes

Upvotes: 5

Views: 1777

Answers (1)

A M
A M

Reputation: 15267

There is no easy answer. Basically, IMHO, you are already on the right track. If the inner std::vectors would have the same size, then it would be easy:

vector< vector<double>> vector2D(ROWS, vector<double>(COLS));

But if you want to set different sizes, then you need to specify those sizes. This will happen at runtime with a std::vector. There are many ways to do that, for example, resize in a for loop or resize explicitely or emplace back inner std::vectors.

See 2 possible solutions:

    std::vector<std::vector<double>> v1;
    v1.emplace_back(std::vector<double>(3));
    v1.emplace_back(std::vector<double>(4));
    v1.emplace_back(std::vector<double>(5));

    // or 
    std::vector<std::vector<double>> v2(3);
    v2[0].resize(3);
    v2[1].resize(4);
    v2[2].resize(5);

There are many more.

If you want compile time operations, std::vector will not work. Then std::array maybe your friend.

Upvotes: 2

Related Questions