-1

我正在从用户那里读取内容,并在向量数组中获取每个单词的出现值。

每次程序运行向量都会从用户那里获取新内容以进行处理。在下面的示例中,我静态地采用了字符串。

我想

  1. 添加到向量中的单词集是持久的。我的意思是在第二次迭代中,当用户输入新内容时;具有计数值的新单词应与先前的向量值合并。而且每次它都会继续增长。显然,由于向量的范围是主要功能,因此每次程序运行时都会刷新。有人可以建议我的想法,以便我可以在矢量中动态添加内容并使其持久化吗?

  2. 先前的向量内容包含单词“mobile”,计数值为 5。用户内容也包含单词“mobile”,计数为 3。那么最终向量应该包含单词“mobile”,计数为 8。

  3. 是否有任何 c++ 类或方法按字母顺序对向量的内容进行排序?

l

int main()
{
    typedef std::unordered_map < std::string, int >occurrences;
    occurrences s1;
    std::string s = "one two two three one one two";
    std::string input = "one,two; three";
    std::istringstream iss(std::move(s));
    std::vector < std::string > most;
    int max_count = 0;
    while (iss >> s) {
    int tmp = ++s1[s];
    if (tmp == max_count) {
        most.push_back(s);
    } else if (tmp > max_count) {
        max_count = tmp;
        most.clear();
        most.push_back(s);
    }
    }

    //Print each word with it's occurance

    //I want vector most to be declared and used in such a way that below coming value should remain persistent each time user perform action
    for (occurrences::const_iterator it = s1.cbegin(); it != s1.cend(); ++it)
    std::cout << it->first << " : " << it->second << std::endl;

    //Print the words with max occurance
    std::cout << std::endl << "Maximum Occurrences" << std::endl;
    for (std::vector < std::string >::const_iterator it = most.cbegin(); it != most.cend(); ++it)
    std::cout << *it << std::endl;
    return 0;
}
4

1 回答 1

1

您的第一个问题基本上是serialization的用法。在这种情况下,最简单的选择可能是将向量中的内容保存到文件中,并在下次运行程序时重新读取该文件。

对于问题 2 和 3,使用 astd::map而不是向量。这将使所有内容保持排序(基于排序标准,对于字符串,默认情况下是按字典顺序排列的)。它也不允许重复的键。例如,以下代码基本上可以满足您的需求:

std::map<std::string, unsigned> words;
...
// Initialize mobile to have a count of 5
words["mobile"] = 5;
...
// Increment count when another "mobile" is seen.
++words["mobile"];
于 2013-08-30T04:36:34.693 回答