如何在C ++中将变换应用到STL映射 [英] How to apply transform to an STL map in C++

查看:99
本文介绍了如何在C ++中将变换应用到STL映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我使用transform将地图的所有值更改为大写。

In C++, I'm using transform to change all the values of a map to uppercase.

  std::map<std::string, std::string> data = getData();

  // make all values uppercase
  std::transform(data.begin(), data.end(), data.begin(),
         [](std::pair<std::string, std::string>& p) {
           boost::to_upper(p.second);
           return(p);
         });

这给我以下编译错误:

/opt/local/include/gcc46/c++/bits/stl_algo.h:4805:2: error: no match for call to '(main(int, char**)::<lambda(std::pair<std::basic_string<char>, std::basic_string<char> >&)>) (std::pair<const std::basic_string<char>, std::basic_string<char> >&)

我认为参数类型有问题在我的lambda表达式。

I think there's something wrong with the type of the argument in my lambda expression. It's probably something simple, but I can't seem to figure out what's expected.

推荐答案

你缺少第一个const的常量类型。

You are missing the const in the first type of the pair.

[](std::pair<const std::string, std::string>& p) {

但这不是你的问题:你不能使用 作为OutputIterator,因为它们不支持分配。您可以使用 std :: for_each

However this is not your problem: You cannot use a map as the OutputIterator, as they do not support assignment. You can, however mutate the second argument using std::for_each.

好旧 map_to_foobar

std::for_each(data.begin(), data.end(), 
              [](std::pair<const std::string, std::string>& p) {
                p.second = "foobar";
              });

概念:调用 transform 范围作为输入和输出是相当合法的,如果所有的函子返回值和不改变他们的参数,这很有道理。然而,改变某些东西的地方可以更快(或至少在代码看起来更快,永远不会优化编译器),并使成员函数很有意义。

Conceptual stuff: Calling transform with the same range as input and output is quite legit and makes a lot of sense if all your functors return by value and don't mutate their arguments. However, mutating something in place can be a faster (or at least look faster in code, nevermind the optimizing compiler) and makes a lot of sense with member functions.

这篇关于如何在C ++中将变换应用到STL映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆