我有一个大小为10的字符串向量。我想将它连接到索引3到6的字符串,空格作为分隔符。我知道boost::algorithm::join
可以使用整个向量来完成它,但是我希望能够在特定范围内完成它,只需要最少的副本和最佳的效率。我知道很多基于stringstream的解决方案,但我想要一些没有stringstream开销的东西。
答案 0 :(得分:2)
您可以使用完整容器以外的其他内容创建范围,并使用boost::algorithm::join
,就像在原始示例中一样。
#include <boost/algorithm/string/join.hpp>
#include <vector>
#include <iostream>
int main(int, char **)
{
std::vector<std::string> list;
list.push_back("Something");
list.push_back("that's");
list.push_back("not");
list.push_back("Hello");
list.push_back("World!");
list.push_back("really");
list.push_back("it's");
list.push_back("not");
boost::iterator_range<std::vector<std::string>::const_iterator>
rng (list.begin() + 3, list.begin() + 5);
std::string joined = boost::algorithm::join(rng, ", ");
std::cout << joined << std::endl;
}
仍打印“Hello,World!”
答案 1 :(得分:1)
由于您需要减少开销,我建议为std::back_insert_iterator
实施std::string
的自定义版本。
所以你可以这样做:
class my_back_insert_iterator :
public std::iterator<std::output_iterator_tag,void,void,void,void>
{
protected:
std::string* container;
public:
typedef std::string container_type;
explicit my_back_insert_iterator(std::string& x) : container(std::addressof(x)) {}
my_back_insert_iterator& operator=(const std::string& value)
{ container->append(value + " "); return *this; }
my_back_insert_iterator& operator=(std::string&& value)
{ container->append(std::move(value + " ")); return *this; }
my_back_insert_iterator& operator*()
{ return *this; }
my_back_insert_iterator& operator++()
{ return *this; }
my_back_insert_iterator& operator++(int)
{ return *this; }
};
之后您可以轻松执行以下操作:
std::vector<std::string> strings = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9"};
std::ptrdiff_t from = 3ULL;
std::ptrdiff_t to = 6ULL;
std::string joinedStrings;
std::move(strings.begin()+from, strings.begin()+to,
my_back_insert_iterator(joinedStrings));
joinedStrings += *(strings.begin()+to);
也请尝试这个online!
您可以执行以下操作:
std::vector<std::string> strings = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9"};
std::ptrdiff_t from = 3ULL;
std::ptrdiff_t to = 6ULL;
std::stringstream ss;
std::copy(strings.begin()+from, strings.begin()+to,
std::ostream_iterator<std::string>(ss, " "));
ss << *(strings.begin()+to);
std::string joinedStrings = ss.str();
看到它正常工作online!