我有一组由#分隔的字符串。我想拆分它们并插入unordered_set。
例如。
ABC DEF##GHI XYZ#MNO#PQR
我通过传递无序集来使用boost split。但每次我得到新的结果集。我想将下一个结果附加到同一组中。
std::string str1 = "abc#def#ghi";
std::string str2 = "xyz#mno#pqr";
std::unordered_set<std::string> result
boost::split(result, str1, boost::is_any_of("#"));
boost::split(result, str2, boost::is_any_of("#"));
如果我检查结果集,我只得到xyz,mno,pqr。我希望它附加“abc def and ghi”。如何实现它。
注意:我不想使用任何其他容器。
答案 0 :(得分:1)
我会这样做:(见 Live On Coliru )
#include <sstream>
#include <unordered_set>
#include <iostream>
int main()
{
std::unordered_set<std::string> result;
std::istringstream iss("abc#def#ghi");
std::string tok;
while (std::getline(iss, tok, '#'))
result.insert(tok);
iss.str("xyz#mno#pqr");
iss.clear();
while (std::getline(iss, tok, '#'))
result.insert(tok);
for (auto& s : result)
std::cout << s << "\n";
}
答案 1 :(得分:1)
这是因为boost::split
在写入之前清理目标容器。
我会根据您的需要使用boost::tokenizer
。
#include<boost/tokenizer>
// ....
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep("#");
std::string str1 = "abc#def#ghi";
std::string str2 = "xyz#mno#pqr";
std::unordered_set<std::string> result;
tokenizer t1(str1, sep), t2(str2, sep);
std::copy(t1.begin(), t1.end(), std::inserter(result, result.end()) );
std::copy(t2.begin(), t2.end(), std::inserter(result, result.end()) );