首页 > 解决方案 > 使用 std::for_each 迭代和打印 std::map

问题描述

最近,我了解了 STL 类型和模板,作为练习 STL 和习惯使用它的一部分,我们遇到了挑战:

  1. 迭代一个std::map<std::string, size_t>
  2. 打印其内容

限制:

  1. 只能使用:std::vector, std::map, std::string, std::algorithm,std::functional

  2. 无法定义复杂类型或模板

  3. 无法使用. (member access), -> (member access via pointer), * (dereference) operators

  4. 不能使用for, while, do-while nor if-else, switch和其他条件

  5. 可以使用std::for_each函数模板的其他函数来迭代元素集合

  6. 没有 lambda

  7. std::cout,,std::cerr等等std::ostream

  8. 没有自动类型

  9. 可以使用其他 STL 模板,只要它们包含在 (1) 中描述的标题中

允许使用这些功能:

void print(const std::string& str)
{
    std::cout << str << std::endl;
}
std::string split(const std::pair<std::string, size_t> &r)
{
    std::string name;
    std::tie(name, std::ignore) = r;
    return name;
}

最初,我想用它std::for_each(std::begin(mymap), std::end(mymap), print)来遍历地图,然后使用打印功能打印出内容。然后我意识到我实际上正在与之合作,std::pair<std::string, size_t>这让我考虑使用std::bindstd::tie分手std::pair。但是由于我认为我需要在std::for_each表达式中执行此操作,我怎么能打破std::pairwhile 还调用元素上的 print 呢?

我也考虑过使用Structured Binding,但我不允许使用auto.

所以,问题是,我如何利用 STL 迭代映射以提取然后使用提供的辅助函数打印出键?显然,如果没有这些限制,挑战将非常容易,但鉴于此,我不知道 STL 中的哪种功能是合适的。

标签: c++stlc++17stdbind

解决方案


我从你的函数中使用了一个 "std::pair& 作为 for_each 第三个参数。

我使用 printf() 打印值。

#include <string>
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;


std::string Split(const std::pair<std::string, size_t> &r)
{
    std::string name;
    std::tie(name, std::ignore) = r;
    return name;
}

int main()
{
    string name1{ "John" };
    string name2{ "Jack" };

    std::map<std::string, size_t> sample = { {name1, 31}, {name2, 35} };
    static vector<std::string> names;

    std::for_each(sample.begin(), sample.end(), [](std::pair<std::string, size_t> pickup)
    {
        static int i = 0;
        names.push_back(Split(pickup));
        printf("%s\n", names[i].c_str());
        i++;
    });

}

推荐阅读