Search code examples
c++vectorstdvector

C++ std::vectors with predefined sizes


While taking a look at a solution for a problem, I came across this implementation of a vector.

const int MX = 100000;
std::vector <int> adj[MX];

The push_back() function doesn't work with this implementation of the vector class, and to add an element, the following code was used:

std::ifstream fin ("file.in");
int N = 5;
for (int i = 0; i < (N-1); i++) {
    int A,B; fin >> A >> B;             // reading values from another file
    adj[A].pb(B), adj[B].pb(A);
}

The way this code is adding is adding pushing back a value to a certain part of the list, which I imagine as a vector inside the vector of the form:

{
    { },
    { }
}

In addition, how would I loop through this vector because for (int n : adj) does not work. I am not sure what the form of this vector is because this method of looping does not work.


Solution

  • What you have is C style array of vectors, off the bat you could replace that with std::array:

    std::array<std::vector<int>, MX> adj;
    

    To loop through these you would have to use a nested one, the outer loop to go through the array, and the inner one to go through each vector, something like this:

    const int MX = 3;
    
    //array of 3 vectors
    std::array<std::vector<int>, MX> adj {{{1,2,3,4}, {5,6,7,8}, {9, 10, 11, 12}}};
    
    for(auto &v : adj){    //for the array
        for(auto i : v){   //for each vector
            std::cout << i << " "; 
        } 
        std::cout << "\n";      
    }
    

    Output:

    1 2 3 4
    5 6 7 8
    9 10 11 12
    

    You can also access individual elements using C style indexing:

    std::cout << adj[1][0]; // vector element index 0 of array index 1
    

    Or in a safer way, using container member at:

    std::cout << adj.at(1).at(0);
    

    This would output 5.

    You should be careful though, when randomly filling the array, an array is not meant to have empty elements, otherwise the loops will go through uninitialized array members, which is not ideal, perhaps you are looking for some other kind of container.