只是一个简短的问题:
是否有与 Haskell 的 inits 等效的 C++11 ?
The inits function returns all initial segments of the argument, shortest first.
我想做某事。喜欢
reverse $ inits [1..10]
C++11 支持 std::reverse ,但我找不到某物。就像std::inits。
列表将在 C++ 中表示为 std::vector。
最佳答案
我认为我让它纯粹功能性地工作:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(void) {
vector<int> nums = { 1,5,5,9,8,7,6 };
auto inits = accumulate(nums.begin()+1, nums.end(), // Iterate between second and last element
vector< vector<int> >{ vector<int>{nums.front()}}, // Initialize accumulator
[] (vector< vector<int> > &acc, int j) { // Lambda constructing further elements
auto tmp = acc.back();
tmp.push_back(j);
acc.push_back( tmp );
});
return 0;
}
Inits 将是 int 向量的向量。
一切都没有(可见的)循环:-)
关于haskell - C++11 相当于 Haskell 的 "inits",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22965640/