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;
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With