我搜索一些
std::
算法但失败了。我想处理从输入迭代器到最后一个迭代器的项目并将输出写入输出迭代器。注意输出可以少于或多于输入流。所以我写了一个例子来展示我到底需要什么:
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <string_view>
void some_algorithm_name(auto it_beg, auto it_end, auto it_out, auto func)
{
for (; it_beg != it_end; it_beg++)
{
func(*it_beg, it_out);
}
}
int main(int argc, char** argv)
{
using namespace std;
string_view in = "abcdefaa";
string out;
some_algorithm_name(begin(in),
end(in),
back_inserter(out),
[](char ch, auto& out_it)
{
switch (ch)
{
case 'a': // duplicate
{
*out_it++ = 'a';
*out_it++ = 'a';
break;
}
case 'b': // skip
{
break;
}
case 'c': // change/transform
{
*out_it++ = 'd';
break;
}
case 'd': // change/transform
{
*out_it++ = 'c';
break;
}
default: // copy
{
*out_it++ = ch;
}
}
});
string expected = "aadcefaaaa";
cout << "input: " << quoted(in) << endl;
cout << "output: " << quoted(expected) << (expected == out ? "==" : "!=")
<< quoted(out) << endl;
return 0;
}
有什么库或框架可以找到这样的算法吗?或者你可以给它起个名字吗?
其中一种方法是使用标头
std::accumulate
中声明的标准算法<numeric>
。例如
#include <iostream>
#include <string>
#include <string_view>
#include <iterator>
#include <numeric>
int main()
{
std::string_view in = "abcdefaa";
std::string out;
auto lambda = []( auto result, const auto ch )
{
switch (ch)
{
case 'a': // duplicate
result.append( 2, 'a' );
break;
case 'b': // skip
break;
case 'c': // change/transform
result += 'd';
break;
case 'd': // change/transform
result += 'c';
break;
default: // copy
result += ch;
break;
}
return result;
};
out = std::accumulate( std::begin( in ), std::end( in ), std::string(), lambda );
std::cout << "in = " << in << '\n';
std::cout << "out = " << out << '\n';
}
程序输出为
in = abcdefaa
out = aadcefaaaa