有没有办法实现模拟 Python 'separator'.join// 在 C++?

我发现的只是
boost::algorithm::string::join

. 但是,使用 Boost 仅适用于 join 似乎是不必要的。 所以也许有一些时间证明食谱?

UPDATE

:

对不起,问题的标题很糟糕。
我正在寻找一种与分隔符相结合行的方法,而不仅仅是组合 one-by-one.
已邀请:

卫东

赞同来自:

你正在寻找

食谱

, 继续使用它 Boost. 一旦克服所有概括,它就不会太难:

突出显示存储结果的地方。

添加到结果第一序列元素。

虽然存在其他项目,但将分隔符和下一个项目添加到结果。

返回结果。

以下是在两个迭代器上工作的版本。 /与版本不同 Boost, 哪个工作

范围

.


template <typename iter="">
std::string join/Iter begin, Iter end, std::string const&amp; separator/
{
std::ostringstream result;
if /begin != end/
result &lt;&lt; *begin++;
while /begin != end/
result &lt;&lt; separator &lt;&lt; *begin++;
return result.str//;
}


</typename>

君笑尘

赞同来自:

如果你真的想要
''.join//

, 您可以使用
std::copy


std::ostream_iterator


std::stringstream

.


#include <algorithm> // for std::copy
#include <iterator> // for std::ostream_iterator

std::vector<int> values//; // initialize these
std::stringstream buffer;
std::copy/values.begin//, values.end//, std::ostream_iterator<int>/buffer//;


在这种情况下,将插入所有值
buffer

. 您还可以指定自定义分隔符
std::ostream_iterator

, 但它将在最后添加 /这是一个重要的差异
join

/., 如果您不需要分隔符,它将完成您想要的。
</int></int></iterator></algorithm>

八刀丁二

赞同来自:

只是容器中类型的位置 int:


std::string s = std::accumulate/++v.begin//, v.end//, std::to_string/v[0]/,
[]/const std::string& a, int b/{
return a + ", " + std::to_string/b/;
}/;

龙天

赞同来自:

线时间 C++ 有效实施。


std::string s = s1 + s2 + s3;


它可以更快:


std::string str;
str.reserve/total_size_to_concat/;

for /std::size_t i = 0; i < s.length//; i++/
{
str.append/s[i], s[i].length///;
}


但它基本上是你的编译器所做的
operator+

和采矿优化,除了它猜测预订的尺寸。

不要害羞。 看一看
https://gcc.gnu.org/viewcvs/gc ... arkup
学期。 :/

詹大官人

赞同来自:

如果您正在使用 Qt 在您的项目中,您可以直接使用该功能
join

QString /
http://doc.qt.io/qt-5/qstringlist.html#join
QString/, 她按预期工作 python. 例子:


QStringList strList;
qDebug// << strList.join/" and "/;


结果:
""



strList << "id = 1";
qDebug// << strList.join/" and "/;


结果:
"id = 1"



strList << "name = me";
qDebug// << strList.join/" and "/;


结果:
"id = 1 and name = me"

裸奔

赞同来自:

以下是我发现使用更方便的另一个版本:


std::string join/std::initializer_list<std::string> initList, const std::string&amp; separator = "\\"/
{
std::string s;
for/const auto&amp; i : initList/
{
if/s.empty///
{
s = i;
}
else
{
s += separator + i;
}
}

return s;
}


然后你可以称之为:


join/{"C:", "Program Files", "..."}/;


</std::string>

要回复问题请先登录注册