如何遍历/迭代 STL 映射?

发布于 2024-10-03 08:23:43 字数 63 浏览 9 评论 0原文

我想遍历一张STL地图。我不想使用它的密钥。我不关心顺序,我只是寻找一种访问它包含的所有元素的方法。我该怎么做?

I want to traverse an STL map. I don't want to use its key. I don't care about the ordering, I just look for a way to access all elements it contains. How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

刘备忘录 2024-10-10 08:23:43

是的,您可以遍历标准库map。这是用于遍历 map 的基本方法,并可作为遍历任何标准库集合的指导:

C++03/C++11:

#include <cstdlib>
#include <map>
#include <string>
using namespace std;

int main()
{
    typedef map<int,string> MyMap;
    MyMap my_map;
    // ... magic

    for( MyMap::const_iterator it = my_map.begin(); it != my_map.end(); ++it )
    {
      int key = it->first;
      string value = it->second;
    }
}

如果需要修改元素:

  • 使用 iterator 而不是 const_iterator
  • 不要从迭代器中复制值,而是获取引用并通过它修改值。

    for( MyMap::iterator it = my_map.begin(); it != my_map.end(); ++it )
    {
    int key = it->first;
    字符串&值=它->第二个;
    如果(值==“foo”)
    值=“栏”;
    }

就是您通常手动遍历标准库容器的方式。最大的区别是,对于 map 来说,*it 的类型是一个 pair 而不是元素本身

C++11

如果您有如果受益于 C++11 编译器(例如带有 --std=c++11 的最新 GCC 或 MSVC),那么您还有其他选择。

首先,您可以使用 auto 关键字来摆脱所有令人讨厌的冗长内容:

#include <cstdlib>
#include <map>
#include <string>
using namespace std;

int main()
{
    map<int,string> my_map;
    // ... magic

    for( auto it = my_map.begin(); it != my_map.end(); ++it )
    {
      int key = it->first;
      string& value = it->second;
    }
}

其次,您还可以使用 lambda。与 decltype 结合使用,这可能会产生更清晰的代码(尽管需要权衡):

#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    map<int,string> my_map;
    // ... magic

    for_each(my_map.begin(), my_map.end(), [](decltype(*my_map.begin()) val)
    {
        string& value = val.second;
        int key = val.first;
    });
}

C++11 还引入了范围基 for 循环的概念,您可以使用它识别为与其他语言类似。然而,一些编译器尚未完全支持这一点——尤其是 MSVC。

#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    map<int,string> my_map;
    // ... magic

    for(auto val : my_map )
    {
        string& value = val.second;
        int key = val.first;
    }
}

Yes, you can traverse a Standard Library map. This is the basic method used to traverse a map, and serves as guidance to traverse any Standard Library collection:

C++03/C++11:

#include <cstdlib>
#include <map>
#include <string>
using namespace std;

int main()
{
    typedef map<int,string> MyMap;
    MyMap my_map;
    // ... magic

    for( MyMap::const_iterator it = my_map.begin(); it != my_map.end(); ++it )
    {
      int key = it->first;
      string value = it->second;
    }
}

If you need to modify the elements:

  • Use iterator rather than const_iterator.
  • Instead of copying the values out of the iterator, get a reference and modify the values through that.

    for( MyMap::iterator it = my_map.begin(); it != my_map.end(); ++it )
    {
    int key = it->first;
    string& value = it->second;
    if( value == "foo" )
    value = "bar";
    }

This is how you typically traverse Standard Library containers by hand. The big difference is that for a map the type of *it is a pair rather than the element itself

C++11

If you have the benefit of a C++11 compiler (for example, latest GCC with --std=c++11 or MSVC), then you have other options as well.

First you can make use of the auto keyword to get rid of all that nasty verbosity:

#include <cstdlib>
#include <map>
#include <string>
using namespace std;

int main()
{
    map<int,string> my_map;
    // ... magic

    for( auto it = my_map.begin(); it != my_map.end(); ++it )
    {
      int key = it->first;
      string& value = it->second;
    }
}

Second, you can also employ lambdas. In conjunction with decltype, this might result in cleaner code (though with tradeoffs):

#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    map<int,string> my_map;
    // ... magic

    for_each(my_map.begin(), my_map.end(), [](decltype(*my_map.begin()) val)
    {
        string& value = val.second;
        int key = val.first;
    });
}

C++11 also instroduces the concept of a range-bases for loop, which you may recognize as similar to other languages. However, some compilers do not fully support this yet -- notably, MSVC.

#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    map<int,string> my_map;
    // ... magic

    for(auto val : my_map )
    {
        string& value = val.second;
        int key = val.first;
    }
}
温柔少女心 2024-10-10 08:23:43

与任何 STL 容器一样,begin()end() 方法返回可用于迭代映射的迭代器。取消引用映射迭代器会生成 std::pair

As with any STL container, the begin() and end() methods return iterators that you can use to iterate over the map. Dereferencing a map iterator yields a std::pair<const Key, Value>.

来日方长 2024-10-10 08:23:43

C++17

C++17 起,您可以使用 基于范围的 for 循环结构化绑定,用于迭代地图。生成的代码(例如用于打印地图的所有元素)简短且易读:

std::map<int, std::string> m{ {3, "a"}, {5, "b"}, {9, "c"} };

for (const auto &[k, v] : m)
    std::cout << "m[" << k << "] = " << v << std::endl;

输出:

m[3] = a
m[5] = b
m[9] = c

Coliru 上的代码

C++17

Since C++17 you can use range-based for loops together with structured bindings for iterating over a map. The resulting code, e.g. for printing all elements of a map, is short and well readable:

std::map<int, std::string> m{ {3, "a"}, {5, "b"}, {9, "c"} };

for (const auto &[k, v] : m)
    std::cout << "m[" << k << "] = " << v << std::endl;

Output:

m[3] = a
m[5] = b
m[9] = c

Code on Coliru

蓝天白云 2024-10-10 08:23:43

您可以像任何其他 STL 容器一样遍历 STL 映射:使用迭代器,例如

for (std::map<key, value>::const_iterator
     i = myMap.begin(), end = myMap.end(); i != end; ++i)
{
    // *i is a key-value pair
}

You can traverse STL map in the same way as any other STL container: using iterators, e.g.

for (std::map<key, value>::const_iterator
     i = myMap.begin(), end = myMap.end(); i != end; ++i)
{
    // *i is a key-value pair
}
北渚 2024-10-10 08:23:43

对于 C++11 及以上版本,将 forauto 结合

map<int,int> map_variable; //you can use any data type for keys, as well as value

for(auto &x:map_variable)
{ 
    cout<<x.first ;// gives the key
    cout<<x.second; //gives the value
}

使用 使用 autofor 的新格式引入于C++11

赋予它类似某些高级语言(例如 python)的功能

其中已经存在此类迭代的实现

, :map 变量对值进行排序,因此在迭代时您将获得按排序顺序的键

Using for with auto for C++11 and above usage

map<int,int> map_variable; //you can use any data type for keys, as well as value

for(auto &x:map_variable)
{ 
    cout<<x.first ;// gives the key
    cout<<x.second; //gives the value
}

The newer format of for using auto was introduced in C++11

To give it functionality like some higher level languages like python

Where there was already an implementation of such type of iteration

P.S. : map variable keeps values sorted, so when iterating you will get keys in sorted order

感情废物 2024-10-10 08:23:43

您可以使用自动迭代器来迭代映射。

代码片段:

#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);
      map<string, int> mp;

      mp["a"]=500;
      mp["b"]=200;
      mp["d"]=300;
      mp["c"]=400;

      for(auto it=mp.begin(); it != mp.end(); it++)
      {
         cout<<it->first <<" : "<<it->second<<endl;
      }
      return 0;
}

You can iterate map by using auto iterator.

Code Snippet:

#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);
      map<string, int> mp;

      mp["a"]=500;
      mp["b"]=200;
      mp["d"]=300;
      mp["c"]=400;

      for(auto it=mp.begin(); it != mp.end(); it++)
      {
         cout<<it->first <<" : "<<it->second<<endl;
      }
      return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文