Hawk
Hawk

Reputation: 1

Dynamic vector creation in C++

I am trying to create an X number of vectors. The number of X would be determined during run time. That is, if the user says they need 2 vectors, we create two vectors, if they say they need 3, we create 3 vectors, etc. What would be the best way to do this in C++ and how can I use these after creation?

Upvotes: 0

Views: 474

Answers (1)

MxNx
MxNx

Reputation: 1374

Assuming that by vector you mean std::vector, then one solution to your problem is to use a vector of vectors (no pun intended). For example:

#include <iostream>
#include <vector>

int main()
{
    // Create a vector containing vectors of integers
    std::vector <std::vector<int>> v;

    int X = 2; // Say you want 2 vectors. You can read this from user.
    for(int i = 0; i < X; i++)
    {
        std::vector<int> n = {7, 5, 16, 8}; // or read them from user
        v.push_back(n);
    }
    // Iterate and print values of vector
    for(std::vector<int> n : v) 
    {
        for(int nn : n )
            std::cout << nn << '\n';
        std::cout << std::endl;
    }
}

Upvotes: 1

Related Questions