C++ Access an element of pair inside vector

38,636

Solution 1

Here is a sample. Note I'm using a typedef to alias that long, ugly typename:

typedef std::vector<std::pair<MyClass*, MyClass*> > MyClassPairs;

for( MyClassPairs::iterator it = VectorOfPairs.begin(); it != VectorOfPairs.end(); ++it )
{
  MyClass* p_a = it->first;
  MyClass* p_b = it->second;
}

Solution 2

This should work (assuming you have a C++11 compatible compiler)

for ( auto it = VectorOfPairs.begin(); it != VectorOfPairs.end(); it++ )
{
   // To get hold of the class pointers:
   auto pClass1 = it->first;
   auto pClass2 = it->second;
}

If you don't have auto you'll have to use std::vector<std::pair<MyClass *, MyClass *>>::iterator instead.

Solution 3

Yet another option if you have a C++11 compliant compiler is using range based for loops

for( auto const& v : VectorOfPairs ) {
  // v is a reference to a vector element
  v.first->foo();
  v.second->bar();
}
Share:
38,636
Romaan
Author by

Romaan

I am a Human. CAPTCHA Verified :)

Updated on June 21, 2020

Comments

  • Romaan
    Romaan almost 4 years

    I have a vector with each element being a pair. I am confused with the syntax. Can someone please tell me how to iterate over each vector and in turn each element of pair to access the class.

        std::vector<std::pair<MyClass *, MyClass *>> VectorOfPairs;
    

    Also, please note, I will be passing the values in between the function, hence VectorOfPairs with be passed by pointer that is *VectorOfPairs in some places of my code.

    Appreciate your help. Thanks