go through map c++

go through map c++

本文关键字:c++ map through go      更新时间:2023-10-16

所以,我有一个std::map<int, my_vector>,我想遍历每个int并分析向量。我还没到分析向量的部分,我还在试着找出如何遍历图上的每一个元素。我知道有迭代器是可能的,但我不太明白它是如何工作的,而且,我不知道是否有更好的方法来做我想做的事情

您可以简单地遍历映射。每个映射元素都是一个std::pair<key, mapped_type>,所以first给你键,second给你元素。

std::map<int, my_vector> m = ....;
for (std::map<int, my_vector>::const_iterator it = m.begin(); it != m.end(); ++it)
{
  //it-->first gives you the key (int)
  //it->second gives you the mapped element (vector)
}
// C++11 range based for loop
for (const auto& elem : m)
{
  //elem.first gives you the key (int)
  //elem.second gives you the mapped element (vector)
}

迭代器是完美的选择。环顾四周http://www.cplusplus.com/reference/map/map/begin/