0

Okay I have a little assignment I need to sort a vector of strings using std::sort but it does not sort any "numbers" above two digest correctly. It is critical I use this API for the assignment.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector<string> Nums = { "1", "5", "34", "3", "6", "12", "21" };
    sort(Nums.begin(), Nums.end());
    for (int i = 0; i < Nums.size(); i++)
    {
        cout << Nums[i] << endl;
    }
    system("PAUSE");
}

Result:

1
12
21
3
34
5
6
Press any key to continue . . .

Want:

1
3
5
6
12
21
34
3
  • Do you want to sort the strings numerically, or lexicographically? i.e. should the list start("1", "3", ... ) or ("1", "12", ...)? Commented Dec 1, 2015 at 2:00
  • 1
    This is using string sort. If you want to sort them by numeric value, use a custom comparator in the call to sort. More info here: en.cppreference.com/w/cpp/algorithm/sort Commented Dec 1, 2015 at 2:01
  • Numerically, should have been more clear. Commented Dec 1, 2015 at 2:02

2 Answers 2

2

std::sort is doing exactly what you're asking it to: it's sorting a list of strings in lexicographical order. To sort numerically, you're going to need to pass a custom comparator to sort which compares the strings as if they were numbers. For example:

std::sort(std::begin(Nums), std::end(Nums)
          [] (const std::string& lhs, const std::string& rhs) {
              return std::stoi(lhs) < std::stoi(rhs);
          });

This uses the function stoi from the standard library to convert the strings to ints for comparison.

Sign up to request clarification or add additional context in comments.

Comments

0

I have provided the same thing in a more simple manner. You have to use custom comparison in order to achieve this.

bool cmp(string a,string b)
{
     int p=convertToNum(a); //can use custom function or std::stoi
     int q=convertToNum(b); // converting string to integer
     return p<q;
}
sort(Nums.begin(), Nums.end(),cmp);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.