C ++ Accessing an element of a pair inside a vector

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

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

Also, note that I will pass values ​​between functions, so VectorOfPairs will be passed in with a pointer, which is * VectorOfPairs in some places in my code.

Appreciate your help. Thanks

+4
source share
3 answers

Here is an example. Notice that I'm using typedef for an alias, which is a 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; } 
+7
source

This should work (if 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 do not have auto , you will have to use std::vector<std::pair<MyClass *, MyClass *>>::iterator instead.

+8
source

Another option, if you have a C ++ 11 compatible compiler, use for loops ranges

 for( auto const& v : VectorOfPairs ) { // v is a reference to a vector element v.first->foo(); v.second->bar(); } 
+4
source

Source: https://habr.com/ru/post/1438450/


All Articles