根据C++聊天室里那些了不起的家伙们的要求,将一个文件(我的情况是包含大约100行字符串,每行大约有10个单词)拆分并将所有这些单词插入到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;
}
ostringstream
就是为了这个目的而设计的。它可以生成一个像 ostream
一样的 string
。 - Mooing Duck<algorithm>
头文件后,这段代码比您的代码容易理解得多。 - Mooing Duck#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;
}
#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';
}
<algorithm>
来处理更少的开销? - Drise