c++ - 将单词字符串解析为单词集

标签 c++ parsing set stringstream

这是我正在编写的将一串单词解析为一组单词的函数。

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/

相关文章:

java - 如何在 Java 中实现谓词,用于根据任意数量的规则交叉检查字符串?

javascript - 什么是 JavaScript 中好的数学集实现?

c - 获取和设置路径

c++ - 使用求解器 SparseLU 并出现错误 C2664

python - 使用机器学习或 NLP 处理格式错误的文本数据

c++ - 返回更专业对象的最佳方法

php - 从 SimpleXMLElement 对象获取值

algorithm - 对于具有 N 个成员的集合,每个子集的大小为 1 或 2 的集合分区的数量是多少?

c++ - 在 Microsoft Visual Studio 2008 上安装 OpenCV 2.4.10

c++ - Qt Creator/qmake - 从源目录加载 Assets 文件夹,而不是构建目录