这是我正在编写的将一串单词解析为一组单词的函数。
std::set<std::string> parseStringToWords(string rawWord)
{
getline(cin,rawWord);
std::set<std::string> myset;
istringstream iss(rawWord);
string word;
while(iss >> word) {
myset.insert(word);
}
}
我很确定到目前为止我所做的是正确的,但我不确定在 while 循环中要做什么。有什么提示吗?
最佳答案
下面是一些代码,希望能引导您朝着正确的方向前进:
#include <iostream>
#include <string> // std::string
#include <set> // std::set
#include <sstream> // std::istringstream
namespace my {
using std::cin;
using std::cout;
using std::istringstream;
using std::set;
using std::string;
auto set_of_words( const string& s )
-> set<string>
{
set<string> result;
istringstream iss( s );
string word;
while( iss >> word )
{
result.insert( word );
}
return result;
}
auto getline( const string& prompt )
-> string
{
string result;
cout << prompt;
getline( cin, result );
return result;
}
} // namespace my
auto main() -> int
{
using namespace my;
using namespace std;
const set<string> words = set_of_words( getline( "A line of words, please: ") );
cout << "You entered these unique_words:" << endl;
for( const string word : words )
{
cout << "* " << word << endl;
}
}
此代码的主要问题是它不检查或处理故障。在专业工作中,许多代码通常与故障检查和处理有关。特别是 my::getline
函数不应该在输入失败时静默返回结果。
另一个问题是缺乏可重用性,因为缺乏抽象。正如我在对该问题的评论中已经提到的,对于经验丰富的程序员来说,一种自然的方法是让 split-into-words 函数将单词传递给输出迭代器。然后,这有助于直接用于各种目的,例如在一行中输出一个单词,或将它们添加到一个集合中,或将它们放在 vector 的末尾,......;并且它有助于为此类目的编写便利包装器的代码。更重要的是,这是一个一般原则,即不要不必要地将自己限制在给定的数据表示形式上。但另一方面,不要将工作浪费在有希望的泛化上,因为最终人们可能会发现它没有被使用。
关于c++ - 将单词字符串解析为单词集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29294083/