【发布时间】:2014-03-18 22:15:11
【问题描述】:
我正在寻找来自 Python 编程语言的 map 或 filter 的 C++ 类似物。它们中的第一个将一些函数应用于可迭代的每个项目并返回结果列表,第二个从函数返回true的迭代元素构造一个列表。
我想在 C++ 中使用类似的功能:
- 将一些函数映射到容器,以便获得具有转换后数据的新容器(并且可能具有不同的长度);
- 对容器使用某种条件过滤;
C++ 中是否有 Python 的 map 和 filter 的良好实现?
在这个简短的示例中,我正在尝试使用boost::bind 和std::for_each 等工具来解决这个问题,但我遇到了困难。 std::vector<std::string> result 应该包含所有字符串std::vector<std::string> raw,在字典上高于标准输入的最后一个字符串。但实际上result容器在返回点还是空的。
#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>
void filter_strings(std::string& current, std::string& last, std::vector<std::string>& results)
{
if (current > last)
{
results.push_back(current);
std::cout << "Matched: " << current << std::endl;
}
}
int main()
{
std::vector<std::string> raw, result;
std::string input, last;
//Populate first container with a data
while(std::getline(std::cin, input))
raw.push_back(input);
last = raw.back();
//Put into result vector all strings which lexicographically higher than the last one
std::for_each(raw.begin(), raw.end(), boost::bind(&filter_strings, _1, last, result));
//For some reason the resulting container is empty
std::cout << "Results: " << result.size() << std::endl;
return 0;
}
输入和输出:
[vitaly@thermaltake 1]$ ./9_boost_bind
121
123
122
120 //Ctrl+D key press
Matched: 121
Matched: 123
Matched: 122
Results: 0
任何帮助将不胜感激。
【问题讨论】:
-
你需要为在 std 容器上工作的良好通用
map和filter函数编写一些非常讨厌的模板,我尝试过一次但失败了。相反,您应该按照@juanchopanza 的建议使用std::algorithm。 -
看看 boost range,它导致的代码与 linq 和 python 非常相似
标签: python c++ boost functional-programming