Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 546
Abhishek Kusnoor Avatar asked Oct 26 '25 12:10

Abhishek Kusnoor


1 Answers

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);
    }
}
like image 69
463035818_is_not_a_number Avatar answered Oct 28 '25 01:10

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!