1mpl3m3nt 向量堆栈并输出存储和计数的项目

1mpl3m3nt vector stack & output a stored&counted item

这是我的代码:

我目前将用户输入的所有内容都转储到堆栈中并进行了排序,但我how/where不会从这里开始。我尝试用计数变量解决它,但我的解决方案不合适(如果用户输入狗两次,它应该只输出一次“2 dog”)。如果有人可以帮助或知道解决这个问题的方法,请举个例子。

如评论所述使用std::map:

std::map<std::string, unsigned int> countMap;

while(enter!=endString){
    getline(cin,enter);
    countMap[enter]++;   // Operator `[]` enters a new key if not present and 
    // default initializes the value. 
    //, else fetches and increases the corresponding value
}

// coutMap[str] gives the number of times `str` entered.

你应该使用地图。但如果您正在寻找另一个答案,请使用对所有元素的搜索。 从输入中读取所有元素后,开始循环向量。获取第一个元素,存储它的值并将其删除,然后检查其他 size-1 元素以查看它们是否等于这个元素。如果是,添加计数器并从向量中删除该项目。 请注意,大小已减小。现在再次做同样的事情,直到大小变为 0.

有多种方法可以做到这一点。最简单的是 std::map:

的简单使用
#include <iostream>
#include <string>
#include <map>

int main()
{
    std::map<std::string, unsigned int> mymap;
    std::string s;

    while (std::getline(std::cin, s) && !s.empty() && s != "END")
        ++mymap[s];

    for (auto const& pr : mymap)
        std::cout << pr.second << ':' << pr.first << '\n';
}

工作原理

  • 读取每一行,如果成功(不是eof,不为空,不等于"END")用于更新映射中的条目。
  • 根据 documentation for std::map::operator [],如果映射中尚未存在必需的键,则添加它,并且 mapped-to 值为 value-initialized.对于 unsigned int 这意味着初始值为 0.
  • 从那里开始,增量应用于返回的 unsigned int 引用,对于新元素,它会产生值 1,对于现有元素,它只是增加先前的值。
  • 这一直持续到循环终止。

循环终止后,结果按字典顺序报告,前面是它们的计数。

输入

one
two
three
four
three
one
one
one
two
END

输出

1:four
4:one
2:three
2:two

如果你想根据计数对输出进行排序,需要做更多的工作,但这并不难。地图中的一组对,倒置,因此计数在前,字符串在后,简化了这一点:

#include <iostream>
#include <string>
#include <map>
#include <set>

int main()
{
    std::map<std::string, unsigned int> mymap;
    std::string s;

    while (std::getline(std::cin, s) && !s.empty() && s != "END")
        ++mymap[s];

    std::set<std::pair<unsigned int, std::string>> ms;
    for (auto const& pr : mymap)
        ms.insert(std::make_pair(pr.second, pr.first));

    for (auto const& pr : ms)
        std::cout << pr.first << ':' << pr.second << '\n';
}

下面出现了一个例子运行:

输入

one
two
three
four
three
one
one
one
two
END

输出

1:four
2:three
2:two
4:one