Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Access an element of pair inside vector

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

like image 250
Romaan Avatar asked Oct 08 '12 16:10

Romaan


3 Answers

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.

like image 161
Benj Avatar answered Sep 29 '22 13:09

Benj


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;
}
like image 43
John Dibling Avatar answered Sep 29 '22 13:09

John Dibling


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();
}
like image 22
Praetorian Avatar answered Sep 29 '22 13:09

Praetorian