是否有用于执行反向字符串拆分器的开箱即用功能?

Is there an out of the box function for performing the reverse a string splitter?

本文关键字:功能 拆分 用于 执行 字符串 是否      更新时间:2023-10-16

为了将字符串拆分为我使用的向量

std::vector<std::string> v;
boost::split(v, input, boost::is_any_of("|"));

Boost 或 STL 中是否有一个函数可以执行此操作的相反操作,即形式的连接函数

join(v, output, "|")

boost::join

std::vector<std::string> v = {"Hello", "world"};
const std::string separator = " ";
std::string s = boost::join(v, separator);

演示

是的,有这样一个函数,它被称为std::accumulate

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
std::vector<std::string> v { "a", "b" };
std::string r = std::accumulate( v.begin(), v.end(), std::string(""),[](std::string a,std::string b){ return a + " | " + b; });
std::cout << r;
}

输出:

| a | b

正确处理边界(开始时没有|(,代码变得更加冗长:相应地传递v.begin() + 1和初始字符串,但要注意空v的边缘情况。

然而,并不是说这种天真的std::accumulate应用远非高效(有关详细信息,请参阅此处(。