boost::algorithm::join
提供了一个方便的加入std::vector<std::string>
。如何在元组上使用boost :: algorithm :: join?
在执行连接之前,如何扩展此功能以使用std::vector<std::tuple<std::string,bool>>
以单引号(对于字符串)包围结果(如果为true)。
这并不难与循环,但我正在寻找一种解决方案,使使用最多的标准算法和C + + 11功能(如lambda)。
如果可行,继续使用boost的加入:优雅/可读性/简洁性更重要。
CODE
#include <string>
#include <vector>
#include <tuple>
#include <boost/algorithm/string/join.hpp>
int main(int argc, char* argv[])
{
std::vector<std::string> fields = { "foo", "bar", "baz" };
auto simple_case = boost::algorithm::join(fields, "|");
// TODO join surrounded by single-quotes if std::get<1>()==true
std::vector<std::tuple< std::string, bool >> tuples =
{ { "42", false }, { "foo", true }, { "3.14159", false } };
// 42|'foo'|3.14159 is our goal
}
编辑
OK,我把kassak的建议之下,并在boost::transform_iterator()
接过来一看 - 我被推迟由示例的详细程度提升自己的文档里,所以我尝试了std::transform()
- 这不是我想要的那么短,但它似乎工作。
ANSWER
#include <string>
#include <vector>
#include <tuple>
#include <iostream>
#include <algorithm>
#include <boost/algorithm/string/join.hpp>
static std::string
quoted_join(
const std::vector<std::tuple< std::string, bool >>& tuples,
const std::string& join
)
{
std::vector<std::string> quoted;
quoted.resize(tuples.size());
std::transform(tuples.begin(), tuples.end(), quoted.begin(),
[](std::tuple< std::string, bool > const& t)
{
return std::get<1>(t) ?
"'" + std::get<0>(t) + "'" :
std::get<0>(t);
}
);
return boost::algorithm::join(quoted, join);
}
int main(int argc, char* argv[])
{
std::vector<std::tuple< std::string, bool >> tuples =
{
std::make_tuple("42", false),
std::make_tuple("foo", true),
std::make_tuple("3.14159", false)
};
std::cerr << quoted_join(tuples, "|") << std::endl;
}
您的版本的缺点是它是两个步骤:完成向量文件的副本。 – Yakk
@Yakk如果你能提出一个更好的版本(在代码中)作为答案,我会+1你的帖子(这将是一个很好的做法) – kfmfe04