简体   繁体   中英

sort a string array using string length with std::vector in cpp

I have a function in cpp that i want to use to sort an array of strings according to the individual length of each string, i tried to compare the length of an element at a particular index with the length of the element residing in the next index. If the length of the next index is lower than the length of the string in the first index then i push the shorter length string to the index of the string with higher length. The code i tried is shown below, i have a problem using it in my main, there is an error generated by the compiler that states :[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;
}

Here you go.

#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;
}

Note: Works on for c++11 or greater.

As an alternative to sorting, you can move your strings into a sorted container:

#include <iostream>
#include <set>
#include <string>
#include <vector>

struct StringLengthComparer
{
    bool operator ()(std::string left, std::string right) const 
    {
        return left.length() < right.length();
    }
};

using StringMultiset = std::multiset<std::string, StringLengthComparer>;

using std::cout;

StringMultiset sortByLength(std::vector<std::string> arr) 
{
    return StringMultiset{arr.begin(), arr.end()};
}

int main()
{
    auto myset = sortByLength({"Mario", "Bowser", "Link"});

    for(auto item : myset)
    {
        cout << item<< '\n';
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM