21xrx.com
2025-04-14 10:11:44 Monday
文章检索 我的文章 写文章
如何在C++中获取Map的键(key)
2023-07-10 04:42:40 深夜i     15     0
C++ Map 获取 方法

在C++中使用Map是非常常见的,通过Map,我们可以实现很多基于键值对的操作。当我们需要获取Map中的键(key)时,我们需要使用一些特殊的技巧。以下是在C++中获取Map键的方法。

1.使用迭代器

使用迭代器是C++中获取Map键值的最常用方法。我们可以使用Map的begin()和end()函数得到Map的迭代器,然后使用迭代器提供的first成员来获取Map的键。示例代码如下:

std::map<int, std::string> myMap;
myMap[0] = "zero";
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
for (auto it = myMap.begin(); it != myMap.end(); ++it)
  std::cout << it->first << std::endl;

2.使用std::transform

std::transform函数可以遍历Map,并将其输出到另一个容器中。我们可以在输出中获取键。示例代码如下:

std::map<int, std::string> myMap;
myMap[0] = "zero";
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
std::vector<int> keys(myMap.size());
std::transform(myMap.begin(), myMap.end(), keys.begin(),
  [](auto const& pair) return pair.first; );
for (auto const& key : keys)
  std::cout << key << std::endl;

3.使用boost::adaptors::map_keys

使用Map获取键的第三种方法是使用boost库。boost::adaptors::map_keys可以获取Map的键并将其输出到另一个容器中。示例代码如下:

#include <boost/range/adaptor/map.hpp>
#include <iostream>
#include <map>
#include <vector>
int main()
{
  std::map<int, std::string> myMap;
  myMap[0] = "zero";
  myMap[1] = "one";
  myMap[2] = "two";
  myMap[3] = "three";
  std::vector<int> keys;
  boost::copy(myMap | boost::adaptors::map_keys, std::back_inserter(keys));
  for (auto const& key : keys)
  
    std::cout << key << std::endl;
  
  return 0;
}

总之,获取C++中的Map键有很多种方法,具体选择哪种取决于你的代码实现和个人偏好。使用这些技巧,可以轻松地获取Map键。

  
  

评论区

请求出错了