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?
            Asked
            
        
        
            Active
            
        
            Viewed 414 times
        
    0
            
            
        - 
                    3A [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) is a dynamic array allocated at runtime. Since you want a dynamic number of vectors, use a vector of vectors. Consult a [good C++ book](https://stackoverflow.com/questions/388242/) on how to use `std::vector`. StackOverflow is not a tutorial site. – Remy Lebeau Mar 11 '19 at 05:02
1 Answers
1
            
            
        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;
    }
}
 
    
    
        MxNx
        
- 1,342
- 17
- 28
- 
                    This isn't quite right, since the vectors named `n` in the loop are never added to `v`. – Peter Mar 11 '19 at 07:11
- 
                    
