Declaring a vector<vector<pair<int, int>> with a specific size and inserting elements?

11,814

Somehow you are contradicting yourself: When creating a vector you can either pass the number of elements in the constructor or you start with an empty vector and push the elements you want to have in the vector. If you start with size 10 and then push 10 more there are 20. They way around is to either use

std::vector<T> vect(10);
for (size_t i=0;i<10;i++){
    vect[i] = whatever;
}

or

std::vector<T> vect;
for (size_t i=0;i<10;i++){
     vect.push_back(whatever);
}

Maybe you are confusing the size of the vector with its capacity. This you can set via:

std::vector<T> vect;
vect.reserve(10);
for (size_t i=0;i<10;i++){
     vect.push_back(whatever);
}

For your vector of vectors you have to make sure, that there is a vector at that index before you start pushing elements into it:

std::vector<std::vector<T>> mat;
for (size_t i=0;i<10;i++){
    mat.push_back(std::vector<T>());
    for (size_t j=0;j<10;j++){
        mat[i].push_back(whatever);
    }
}
Share:
11,814
Abhishek Kusnoor
Author by

Abhishek Kusnoor

Updated on June 05, 2022

Comments

  • Abhishek Kusnoor
    Abhishek Kusnoor almost 2 years

    I want to represent a graph data structure and I am using vector of vector of pairs in c++ stl. Example:

    vector<vector<pair<int, int>>> G;
    

    Now I can do, G[u].push_back(make_pair(v, w));

    The problem: I need to specify this data structure a size. If I don't I get a segmentation fault when I try to push elements to this data structure. If I do give a size like:

    vector< vector<ii> > adj(10, std::vector<ii>(10));
    

    The problem now is the first 10 pairs of vector are initialized to zero. If I push back an element now, it gets pushed to the 11th position. The first 10 being 0s. I don't want to do this. I want to insert elements in the order I need. A snippet to give you an idea about what I am trying to do:

     for(int i=0;i<E-1;i++)
            {
                cin >> p >> q >> l;
                adj[p].push_back(ii(q, l));
                adj[q].push_back(ii(p, l));
            } 
    

    The output for the above would be 10 zeros followed by the values pushed. Any way to get around this?

  • user1887915
    user1887915 almost 8 years
    I want to know what is the problem to my answer? Could anybody give me a reason to these down votes?