[英]Duplicates when inserting into std::set<std::tuple<std::string, …>>
[英]Splitting std::string and inserting into a std::set
根據C ++聊天室的精彩故事要求,有什么方法可以分解文件(在我的情況下包含一個大約有100行的字符串,每行約10個單詞)並插入所有這些單詞進入std :: set?
從包含一系列元素的源構造任何容器的最簡單方法是使用帶有一對迭代器的構造函數。 使用istream_iterator
迭代流。
#include <set>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
//I create an iterator that retrieves `string` objects from `cin`
auto begin = istream_iterator<string>(cin);
//I create an iterator that represents the end of a stream
auto end = istream_iterator<string>();
//and iterate over the file, and copy those elements into my `set`
set<string> myset(begin, end);
//this line copies the elements in the set to `cout`
//I have this to verify that I did it all right
copy(myset.begin(), myset.end(), ostream_iterator<string>(cout, "\n"));
return 0;
}
假設您已將文件讀入字符串,boost :: split將起到作用:
#include <set>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
std::string astring = "abc 123 abc 123\ndef 456 def 456"; // your string
std::set<std::string> tokens; // this will receive the words
boost::split(tokens, astring, boost::is_any_of("\n ")); // split on space & newline
// Print the individual words
BOOST_FOREACH(std::string token, tokens){
std::cout << "\n" << token << std::endl;
}
如有必要,可以使用列表或向量代替集合。
還要注意這幾乎是一個騙局: 在C ++中拆分一個字符串?
#include <set>
#include <iostream>
#include <string>
int main()
{
std::string temp, mystring;
std::set<std::string> myset;
while(std::getline(std::cin, temp))
mystring += temp + ' ';
temp = "";
for (size_t i = 0; i < mystring.length(); i++)
{
if (mystring.at(i) == ' ' || mystring.at(i) == '\n' || mystring.at(i) == '\t')
{
myset.insert(temp);
temp = "";
}
else
{
temp.push_back(mystring.at(i));
}
}
if (temp != " " || temp != "\n" || temp != "\t")
myset.insert(temp);
for (std::set<std::string>::iterator i = myset.begin(); i != myset.end(); i++)
{
std::cout << *i << std::endl;
}
return 0;
}
讓我們從頂部開始吧。 首先,您需要使用一些變量。 從您要解析的字符串中的每個字符構建它時, temp
只是字符串的占位符。 mystring
是你想要拆分的字符串,而myset
是你將分裂字符串的地方。
然后我們讀取文件(通過<
piping輸入)並將內容插入mystring
。
現在我們想要迭代字符串的長度,搜索空格,換行符或制表符以分割字符串。 如果我們找到其中一個字符,那么我們需要insert
字符串插入到集合中,並清空我們的占位符字符串,否則,我們將字符添加到占位符,這將構建字符串。 完成后,我們需要將最后一個字符串添加到集合中。
最后,我們迭代集合,並打印每個字符串,這只是為了驗證,但在其他方面可能是有用的。
編輯: Loki Astari在評論中對我的代碼進行了重大改進,我認為該評論應該整合到答案中:
#include <set>
#include <iostream>
#include <string>
int main()
{
std::set<std::string> myset;
std::string word;
while(std::cin >> word)
{
myset.insert(std::move(word));
}
for(std::set<std::string>::const_iterator it=myset.begin(); it!=myset.end(); ++it)
std::cout << *it << '\n';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.