在 cpp 中使用带有 std::vector 的字符串长度对字符串数组进行排序

Jas*_*ird 5 c++ arrays sorting std

我在 cpp 中有一个函数,我想用它根据每个字符串的单独长度对字符串数组进行排序,我尝试将特定索引处元素的长度与下一个索引中元素的长度进行比较. 如果下一个索引的长度小于第一个索引中字符串的长度,那么我将较短长度的字符串推送到具有较高长度的字符串的索引。我尝试的代码如下所示,我在主程序中使用它时遇到问题,编译器生成了一个错误,指出 :[Error] could not convert '{"Mario", "Bowser", "Link"}' from '<brace-enclosed initializer list>' to 'std::vector<std::basic_string<char> >'.

#include <iostream>
#include <ctype.h>
#include <vector>

//below is my sort according to length function
using namespace std;
std::vector<std::string> sortByLength(std::vector<std::string> arr) {

    for(int k=0;k<arr.size();k++){
        if(arr[k+1].size()<arr[k].size()){
            //push the shorter string to the lower index
            arr[k]=arr[k+1];
        }
    }
    return arr;
}
//below is the main function
int main(){
//this line below generates compile error
std::vector<string> myarr=sortByLength({"Mario", "Bowser", "Link"})<<endl;
cout<<myarr<<endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Man*_*lva 4

干得好。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
void printVec(std::vector<std::string>& vec) {
    for(auto&& v:vec) {
        std::cout<<v<<std::endl;
    }
}
int main() {
    std::vector<std::string> vec {"abc","ab","a","abcd"};
    printVec(vec);
    std::sort(vec.begin(), vec.end(), [](std::string& a, std::string& b) {
        return a.length() > b.length();
    });
    printVec(vec);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

注意:适用于 c++11 或更高版本。