Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 501
Jason Perching Bird Avatar asked Jul 02 '21 13:07

Jason Perching Bird


People also ask

How do you sort a string vector in C++?

Approach: The sort() function in C++ STL is able to sort vector of strings if and only if it contains single numeric character for example, { '1', ' '} but to sort numeric vector of string with multiple character for example, {'12', '56', '14' } one should write own comparator inside sort() function.

How do you sort an array of strings?

To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.

How do you sort an array of vectors?

Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintains the relative order of equal elements.

How to sort an array by length in Python?

A simple solution is to write our own sort function that compares string lengths to decide which string should come first. Below is the implementation that uses Insertion Sort to sort the array.

How to sort a vector in C++?

Prerequisites : std::sort in C++, vector in C++, initialize a vector in C++. How to sort in descending order? sort () takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass “greater ()” function to sort in descending order. This function does comparison in a way that puts greater element before.

How to sort a list in Python using C++ STL sort?

A better solution is to use sort function provided by programming languages like C++, Java. These functions also allow us to write our own custom comparator. Below is C++ implementation that uses C++ STL Sort function . Take string as list. Use the sorted function in python by providing key as len.

How to sort string array in JavaScript?

We can sort () function to sort string array. At first determine the size string array. Show activity on this post. My solution is slightly different to any of those above and works as I just ran it.So for interest:


2 Answers

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.

like image 109
Manthan Tilva Avatar answered Oct 11 '22 10:10

Manthan Tilva


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;
}
like image 20
Daniel Dearlove Avatar answered Oct 11 '22 11:10

Daniel Dearlove