Hardcore Games
Hardcore Games

Reputation: 1

sorting std::vector<std::string> with numeric data

I have a vector<string> container but the strings are all numbers

EDIT: I tried this:

so now the logic seems to be borked

cleaned this up but experimenting with various attempts to cast std::string to an int is tough lamba was useless and I have run out of ideas for casting std::string without some bug surfacing

template<typename Iterator>void bubbleSort(Iterator first, Iterator last){
    Iterator i, j;
    for (i = first; i != last; i++)
        for (j = first; j < i; j++)
            if (*i < *j)
                std::iter_swap(i, j); // or std::swap(*i, *j);
}

My code to read the source data is

void loadgames(void) { // read the game app id's
ifstream inFile;
ofstream outFile;
string s;
inFile.open("game-list.txt");
if (inFile.is_open()) {
    while (std::getline(inFile, s)) {
        if(s.length() > 0)
            gamelist.push_back(s); 
    };
    inFile.close();
}
//  bubbleSort(gamelist.begin(),gamelist.end());
outFile.open("game-list.txt");
if (outFile.is_open()) {
    for (i = gamelist.begin(); i != gamelist.end(); i++) {
        outFile << *i << endl;
    }
}
outFile.close();

}

The call to is the problem of sorting my vector

bubbleSort(gamelist.begin(),gamelist.end());

Upvotes: 0

Views: 337

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596833

As you already know, you can use std::sort() with a custom comparator. The problem is your compare is setup wrong. Its parameters need to be the container's value_type, not the container type. And you have an erroneous . in it.

Try this instead:

std::vector<std::string> gamelist;
// fill gamelist as needed...

auto compare = [](const std::string &a, const std::string &b){
    return std::stoi(a) < std::stoi(b);
};

std::sort(gamelist.begin(), gamelist.end(), compare);

Online Demo

However, I would suggest using std::vector<int> instead (or appropriate integer type, depending on your string contents), and simply parse the std::strings into integers with std::stoi() (or equivalent) before inserting them into the std::vector, eg:

std::vector<int> gamelist;
// fill gamelist as needed...
gamelist.push_back(std::stoi(someString));
...
std::sort(gamelist.begin(), gamelist.end());

Online Demo

This will consume less memory and sort much faster, and it will reduce the complexity of the sort since you will be incurring the overhead of converting strings to integers only one time up front, not on every iteration of the sort algorithm (potentially parsing the same strings over and over).

Upvotes: 6

Related Questions