C++ 访问向量内的元素对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12785287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:37:17  来源:igfitidea点击:

C++ Access an element of pair inside vector

c++vectorcontainers

提问by Romaan

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.

我有一个向量,每个元素都是一对。我对语法感到困惑。有人可以告诉我如何遍历每个向量,然后依次遍历 pair 的每个元素来访问该类。

    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.

另外,请注意,我将在函数之间传递值,因此 VectorOfPairs 在我的代码的某些地方由指针传递,即 *VectorOfPairs。

Appreciate your help. Thanks

感谢你的帮助。谢谢

回答by Benj

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

这应该可以工作(假设你有一个 C++11 兼容的编译器)

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 autoyou'll have to use std::vector<std::pair<MyClass *, MyClass *>>::iteratorinstead.

如果你没有,auto你将不得不使用std::vector<std::pair<MyClass *, MyClass *>>::iterator

回答by John Dibling

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

这是一个示例。请注意,我使用 typedef 为那个又长又丑的 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;
}

回答by Praetorian

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

如果你有一个 C++11 兼容的编译器,另一个选择是使用基于范围的for循环

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