boost::algorithm::join provides a convenient join on std::vector<std::string>.
How would you expand this functionality to use std::vector<std::tuple<std::string,bool>> to surround the results with single-quotes (for strings) if true, before doing the join.
This is not hard to do with loops, but I am looking for a solution that makes the most use of standard algorithms and C++11 features (eg lambdas).
Continue to use boost’s join, if feasible: elegance/readability/conciseness are more important.
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
}
EDIT
OK, I took kassak’s suggestion below and took a look at boost::transform_iterator() – I got put off by the verbosity of the example in boost’s own documentation, so I tried std::transform() – it’s not as short as I wanted, but it seems to work.
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;
}
If you want to use join, you could wrap collection in
boost::transform_iteratorand add quotes if needed