Search code examples
c++stdvectorstd-pair

C++ is there another way to access members first and second than using a range for loop for std::vector <std::pair <int, int>>?


I solved another problem the other day involving a std::vector <std::pair<int,int>> called name.

My question is, how do I access the name.first and name.second of this type?

I ended up using a ranged-for loop, that solved my issue

for(i : name) { i->first , i->second}

But, is there another way? I am particularly interested in how to access this in a normal for loop, e.g

for(int i = 0; i < name.size(); i++) { std::vector::std::pair::name.first}

Can anybody shed some light on this for me?


Solution

  • The usual way

    for (size_t i = 0; i < name.size(); i++)
    {
         cout << name[i].first;
         cout << name[i].second;
    }
    

    This is just the typical way to access a vector (or array) of structs.

    BTW the code you said worked in fact does not, for(i : name) { i->first , i->second} should be for(i : name) { i.first , i.second}. Your version would work for a vector of pair pointers, but not for a vector of pairs.