正如@jalf说,地图和折叠已经在标准中,隐藏不同的名字后面:
- 地图 - >
std::transform
,在标头中找到<algorithm>
- 倍 - >
std::accumulate
,在报头<numeric>
发现
许多更多功能的东西可以在Boost.Range,这是一个非常棒的图书馆。尤其是range adaptors给人一种真实的功能感,因为他们在其他范围内创建了视图。通过C++ 11,可以通过lambdas轻松创建可能的谓词。
Boost.Optional可能是您的“选项类型”,具体取决于您的意思。
C++中的不变性可以通过简单地声明对象const
来实现。您可以避免使用通过参考参数传递的副本。真相被告知,这当然不等于真正的功能不可变性,因为函数式语言中的不可变容器可以被复制,但是你想要的并且通常只是共享内部表示。毕竟,如果你从不写,写入时拷贝是非常棒的。
在你的托管指针上,我不知道你是什么意思。在C++中,通常根本不需要指针或动态分配的对象。只需创建它们“堆叠”:Foo obj;
。
如果您的意思是共享所有权,那么有std::shared_ptr
。甚至有一个很好的范围适配器,如果你存储这种指针的容器:
#include <boost/range/adaptor/indirected.hpp>
#include <boost/range/algorithm/generate.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <vector>
#include <memory>
#include <algorithm>
#include <iterator>
#include <iostream>
int main(){
std::vector<std::shared_ptr<int>> v(5);
int i = 0;
boost::generate(v, [&i]{ return std::make_shared<int>(i++); });
boost::copy(v | boost::adaptors::indirected,
std::ostream_iterator<int>(std::cout));
}
你的具体例子
my_list.map(f).filter(p).head_opt.get_or_else("not found")
可能是这样的(注实现即std::vector
是C++中的默认容器):
// Warning, C++11 only!
// Boost.Range doesn't like lambdas without this:
#define BOOST_RESULT_OF_USE_DECLTYPE
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <boost/optional.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/generate.hpp> // only needed for filling the vector
#include <boost/range/algorithm/copy.hpp> // only needed for printing
// we need a little helper for the optional stuff
struct head_opt_gen{} head_opt; // just a tag type
template<class Range>
auto operator|(Range const& r, head_opt_gen)
-> boost::optional<decltype(r.front())>
{
if(r.empty())
return boost::none;
return r.front();
}
int main(){
using namespace boost::adaptors;
std::vector<int> v(5);
int i = 0;
boost::generate(v, [&]()->int{ ++i; return i*i; });
// first, without the optional stuff
boost::copy(v | transformed([](int x){ return std::to_string(x); })
| filtered([](std::string const& s){ return s.size() > 1; }),
std::ostream_iterator<std::string>(std::cout, "\n"));
std::cout << "=====================\n";
// now with
std::cout << boost::get_optional_value_or(
v | transformed([](int x){ return std::to_string(x); })
| filtered([](std::string const& s){ return s.size() > 2; }) // note: > 2
| head_opt, "none");
}
与锵3.1中继线编译,这导致下面的输出:
16
25
=====================
none
来源
2012-02-25 00:22:00
Xeo
顺便说一下,C++有一个垃圾收集器。不过,不是标准的一部分。 – 2012-02-24 23:49:24
C++标准库具有基本上是地图和折叠的功能。他们只是被称为'std :: transform'和'std :: accumulate'。 Boost有一个选项类型。我不确定你的意思是“托管指针”虽然 – jalf 2012-02-24 23:51:58
@jalf我正在寻找像'my_list.map(f).filter(p).head_opt.get_or_else(“not found”)',其中my_list是一个int的可迭代容器,f是一个从int到std :: string的函数,p是一个用于选择字符串子集的谓词,head_opt返回表示列表中第一个的选项,最后get_or_else是典型的函数on一个Option类型,它返回一个Some的内容,或一个None的给定值 – 2012-02-25 00:10:11