c++ - 如何在 C++ 中将转换应用于 STL 映射

标签 c++ stl map lambda transform

在 C++ 中,我使用转换将映射的所有值更改为大写。

  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 表达式中的参数类型有问题。这可能很简单,但我似乎无法弄清楚预期的结果。

最佳答案

您在该对的第一种类型中缺少 const。

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

但这不是你的问题:你不能使用 map 作为 OutputIterator,因为它们不支持赋值。但是,您可以使用 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 是非常合法的,如果您的所有仿函数都按值返回并且不改变它们的参数,那么这很有意义。然而,在原地改变某些东西可能会更快(或者至少在代码中看起来更快,更不用说优化编译器了)并且对成员函数很有意义。

关于c++ - 如何在 C++ 中将转换应用于 STL 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7879326/

相关文章:

c++ - "Invalid initialization of non-const reference of type ' std::vector& ' from an rvalue of type ' std::vector"错误

c++ - Windows 与 Linux 上 std::string 的可移植性和长度

java - 我可以使用变量类型在 Java 中声明另一个变量吗?

java - Set.removeAll() 在 : equals or compareTo? 下面使用了哪个方法

javascript - 使用 JVector 随机着色美国 map

php - HBitmap字节数组到php

c++ - 检查迭代器属于哪个 vector

c++ - 是否可以根据构造函数中作为参数传入的 bool 将数据成员初始化为 const?

C++,创建 vector 的 vector ?

c++ - 除了 boost::pool 之外,C++ 中的自定义池分配器