[英]I am trying to come up with a program to store user input (strings) in a vector and output them in descending order by length
An example would be.一个例子是。
Input:输入:
Hey this is fantastic!
Output: Output:
fantastic! this Hey is
sorry if I haven't asked the question properly.抱歉,如果我没有正确提出问题。 This is all I have to go by.这就是我对 go 所拥有的全部了。
Check out the std::sort
function from <algorithm>
and std::vector<std::string>
.从<algorithm>
和std::vector<std::string>
查看std::sort
function 。 There are plenty of examples on the internet on how to write a function that orders the strings by descending order (pass the function to std::sort
).互联网上有很多关于如何编写按降序排列字符串的 function 的示例(将 function 传递给std::sort
)。
Use the std::sort()
standard algorithm, giving it a predicate that sorts in descending order, eg:使用std::sort()
标准算法,给它一个按降序排序的谓词,例如:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::vector<std::string> v;
std::string s;
std::getline(std::cin, s);
std::istringstream iss(s);
while (iss >> s) {
v.push_back(s);
}
std::sort(v.begin(), v.end(),
[](const std::string &a, const std::string &b){ return a.size() >= b.size(); }
);
for(auto &word: v) {
std::cout << word << std::endl;
}
return 0;
}
Check out the method reverse from std Library, this is an example I just found on Internet, it will reverse the order on the string vector you pass on it.查看 std 库中的 reverse 方法,这是我刚刚在 Internet 上找到的一个示例,它将反转您传递给它的字符串向量的顺序。 http://www.cplusplus.com/reference/algorithm/reverse/ http://www.cplusplus.com/reference/algorithm/reverse/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.