Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ program crashes when trying to sort a vector of strings

I'm trying to sort an array of strings in C++, but I am getting the following error message:

terminate called after throwing an instance of 'std::logic_error'  
  what():  basic_string::_M_construct null not valid

The following program causes the previous error. I got the error when v has 17 elements, but everything works fine when v has less elements.

Could someone point me out what is the problem? I'm using gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)

#include <vector>
#include <string>
#include <algorithm>

using namespace std;

bool comp (string s1, string s2) {
    if (s1.size() < s2.size())
        return false;
    else
        return true;
}

int main () {   
    vector<string> v = { "a", "a", "a", "a",
                         "a", "a", "a", "a",
                         "a", "a", "a", "a",
                         "a", "a", "a", "a",
                         "a" };
    
    sort(v.begin(), v.end(), comp);
    return 0;
}
like image 883
Sérgio Q Medeiros Avatar asked Sep 22 '20 17:09

Sérgio Q Medeiros


People also ask

Can we sort vector of strings?

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 I sort a vector directly?

A vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file. The sort() function sorts a given data structure and does not return anything.

Can you use std::sort on a vector?

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 do you sort an object in vector?

You can sort a vector of custom objects using the C++ STL function std::sort. The sort function has an overloaded form that takes as arguments first, last, comparator. The first and last are iterators to first and last elements of the container.


1 Answers

The comparator you pass to sort must satisfy the named requirement Compare:

Establishes strict weak ordering relation with the following properties

For all a, comp(a,a)==false
If comp(a,b)==true then comp(b,a)==false
if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true

With your comparator: comp(a,a) == true. As you do not fullfill the preconditions of std::sort your code has undefined behavior.

like image 97
463035818_is_not_a_number Avatar answered Sep 21 '22 03:09

463035818_is_not_a_number