Search code examples
c++vectorcontainers

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


Solution

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