有没有办法实现Python的'separator'.join()在C ++的模拟? [英] Is there a way to implement analog of Python's 'separator'.join() in C++?
问题描述
所有我找到的是 boost :: algorithm :: string :: join
。然而,似乎过度使用Boost只为加入。那么也许有一些经过时间考验的食谱?
All I've found is boost::algorithm::string::join
. However, it seems like overkill to use Boost only for join. So maybe there are some time-tested recipes?
UPDATE :
对不起,问题标题不好。
我正在寻找方法来连接字符串与分隔符,而不只是逐个连接。
UPDATE:
Sorry, the question caption were bad.
I'm looking for method to concatenate strings with separator, not just to concatenate one-by-one.
推荐答案
由于您正在寻找食谱,请继续使用Boost的。一旦你超越了所有的一般性,它不是太复杂:
Since you're looking for a recipe, go ahead and use the one from Boost. Once you get past all the genericity, it's not too complicated:
- 分配一个地方来存储结果。
- 将序列的第一个元素添加到结果中。
- 当有其他元素时,将分隔符和下一个元素追加到结果中。
- 返回结果。
- Allocate a place to store the result.
- Add the first element of the sequence to the result.
- While there are additional elements, append the separator and the next element to the result.
- Return the result.
这里有一个版本可以在两个迭代器上工作
Here's a version that works on two iterators (as opposed to the Boost version, which operates on a range.
template <typename Iter>
std::string join(Iter begin, Iter end, std::string const& separator)
{
std::ostringstream result;
if (begin != end)
result << *begin++;
while (begin != end)
result << separator << *begin++;
return result.str();
}
这篇关于有没有办法实现Python的'separator'.join()在C ++的模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!