【问题标题】:Sort words by string length按字符串长度排序单词
【发布时间】:2015-07-04 15:52:15
【问题描述】:

我有一个 .txt 文件中的单词列表:

list
of
a
thousand
words

我希望单词按长度排序,ofstream 将结果保存到 .txt 文件中。

输出的话会是这样的:

a
of
list
words
thousand

任何答案将不胜感激。

【问题讨论】:

  • 所以你必须 1) 从文件中读取单词,2) 将它们存储在某种容器中,3) 测量单词的长度,4) 按长度对单词进行排序,5)将它们写入另一个文件。您可以做哪些部分,您遇到了哪些问题?
  • 。这不是家庭作业外包服务。
  • 好的,我知道如何处理ifstreamofstream,用string.size()衡量,我不知道如何使用<vector>来存储它们并按顺序排序
  • 你知道怎么用吗?

标签: c++ fstream words


【解决方案1】:

我不想用勺子喂你,但同时你可以通过查看代码学到很多东西。下面的例子使用vector作为主容器,sort函数配合lambda从低到高排序。

std::vector<std::string> myList;

myList.push_back("why");
myList.push_back("am i");
myList.push_back("helping you with");
myList.push_back("your");
myList.push_back("homework");

std::sort(myList.begin(),myList.end(),[](const std::string& val1, const std::string& val2){
    return val1.size() < val2.size();
});

for (auto& itm : myList)
{
    std::cout << itm << std::endl;
}

【讨论】:

  • 所以包括 &lt;iostream&gt; &lt;fstream&gt; &lt;vector&gt; &lt;algorithm&gt; 以及我错过的其他任何内容?
猜你喜欢
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 2017-07-08
  • 2015-03-15
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
相关资源
最近更新 更多