【问题标题】:Printing map values with only STL loops仅使用 STL 循环打印地图值
【发布时间】:2016-03-28 16:12:25
【问题描述】:

我遇到了一个问题,我看不到该怎么做。我必须仅使用 STL 循环打印地图值,我不能使用 for 循环 while 循环等。

这是我的地图std::map<std::string, Borrowed*> map;

我宁愿自己不声明另一个函数,除非真的有必要这样做

编辑:我尝试使用 for_each 和复制功能,但如果这是你应该使用的,我不知道你会如何使用它们

【问题讨论】:

  • 我猜你想要 std::for_each
  • @DieterLücking 是的,但我如何使用它,我尝试以合乎逻辑的方式使用,但我没有看到
  • 还有:带有 std::ostream_iterator 的 std::copy
  • @DieterLücking 也试过了,但我将如何打印字符串和指针的值
  • 什么是“STL 循环”?

标签: c++ stl


【解决方案1】:

只需将 std::for_each 与打印元素的 lambda 一起使用(简单地说,使用 map<string, int>,使用您自己的代码打印 Borrowed* 元素)。

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>

int main()
{
    std::map<std::string, int> m = { { "bla", 1 }, { "yada", 2 } };
    std::for_each(m.begin(), m.end(), [](auto const& elem) {
        std::cout << "{ " << elem.first << ", " << elem.second << "}, ";
    });
}

Live Example

请注意,这使用 C++14 通用 lambda(使用 auto 推断参数类型)。在 C++11 中,您必须明确地写出它,而在 C++98 中,您必须将自己的函数对象写入 lambda 的工作。

【讨论】:

    【解决方案2】:

    假设您的意思是 STL 算法:

    这是一个std::for_each 示例(c++11):

    #include <algorithm>
    #include <iostream>
    
    std::for_each(map.cbegin(), map.cend(), 
      [&](const std::pair<std::string, Borrowed*> &pair) {
        std::cout << pair.first // std::string (key)
          << " " << pair.second->XXX // Borrowed* (value) or whatever you want to print here
          << "\n";
    }); 
    

    http://en.cppreference.com/w/cpp/algorithm/for_each

    【讨论】:

    • 谢谢,这似乎有效!但我不明白和帮助我们在这里做什么
    • 我们没有在这里捕获变量map,因为我们没有在 lambda 中使用它。我们实际上可以在这里省略&amp;http://en.cppreference.com/w/cpp/language/lambda
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2017-06-07
    • 1970-01-01
    相关资源
    最近更新 更多