简体   繁体   中英

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

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.

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;
}

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();
}

You can access the element of pairs in c++17 in this style by ranged based for loop:

for (auto& [x, y] : pts) {//& is used for taking inputs 
    cin >> x >> y;
}

where pts is a vector of pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM