在cpp中使用带有std::vector的字符串长度对字符串数组进行排序
我在 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;
}