C++

c++STL容器适配器--Apple的学习笔记

2019-10-24  本文已影响0人  applecai

第三章习题1

从键盘读取任意个数的单词,然后把它们保存到deque<string>容器中,再把容器中的单词复制到List<string>容器中,并将列表中的内容排列成升序,最后输出排序结果。

我的练习代码:

#include <iostream>
#include <algorithm>
#include <string>
#include <list>
#include <deque>
#include <queue>
using namespace std;
void test3_1()
{
  std::deque<std::string> words;
  std::string word;
  std::cout << "Enter words separated by spaces, enter Ctrl+Z on a separate line to end:\n";
  while (true)
  {
    if ((std::cin >> word).eof())
    {
      std::cin.clear();
      break;
    }
    words.push_back(word);
  }
  std::cout << "The words in the list are:" << std::endl;
  priority_queue<string, vector<string>, greater<string>> listwords{begin(words), end(words)};
  while (!listwords.empty())
  {
    cout << listwords.top() << " ";
    listwords.pop();
  }
  cout << endl;
}

输出结果

Enter words separated by spaces, enter Ctrl+Z on a separate line to end:
Hello Apple How Are You?
^Z
The words in the list are:
Apple Are Hello How You?

上一篇下一篇

猜你喜欢

热点阅读