I would go for a slightly different approach, using std::stringstream
s:
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
bool myfunc(std::string p1, std::string p2) {
bool result;
char ch;
int p1int, p2int;
stringstream comparator(p1 + " " + p2); //initialize stringstream
while(comparator >> ch && !(isdigit(ch))); //read until the first digit
comparator.putback(ch); //put it back
comparator >> p1int; //read the int
while (comparator >> ch && !(isdigit(ch))); //read until first digit
comparator.putback(ch); //put it back
comparator >> p2int; //read the whole int
result = p1int < p2int; //get the result
return result; //return it
}
int main() {
std::vector<std::string> v1 { "John - 204","Jack - 143","Alex - 504" };
sort(v1.begin(), v1.end(), myfunc); // sorts the players based on their position
for (unsigned int i = 0; i < v1.size(); i++) {
cout << v1[i] << endl;
}
}
Output:
Jack - 143
John - 204
Alex - 504
More on std::stringstreams: https://www.cplusplus.com/reference/sstream/stringstream/.
Also, read Why is "using namespace std;" considered bad practice?.
When you passed your string to std::stoi, it had something that wasn't digits, so it failed, which is why your code did not work.