Ok, so basically I have a text file that contains the following:

Resource3 "Actuator"
Resource10 "Insert Exhaust Valve"
Resource1 "6, 10, 18, 1"
Resource21 "Emergency Stop"
Resource2 "Cool Down in Progress"

etc. etc.

I want to read the file line by line and store it in a vector (this is no problem). Next, I want to sort each line in the vector so that the lines are in order of resource number (i.e. Resource1 "6, 10, 18, 1", Resource2 "Cool Down in Progress", Resource3 ...., Resource 10...., Resource21....).

So, what I want to know is if there is a way of splitting each of the strings in the vector so that the resource number is separate from the command, from which i can sort the resource numbers by using sort and again by sorting by length (so 10 comes later than 2 and 3) and then putting the command back together with its original resource number?

Basically I want to ensure that the commands are always mapped to their specific resource number so i can manipulate the resource number as much as i want and still have the same command attached to it at the end.. I can't get my head round it, but would be thankful of any input from you guys.

Thanks

You can sort the vector without splitting it. call std::sort to do the sorting. All you have to do is to expand the resource number from 1 to 2 digits, such as "resource1" to "resource01" when you read them from the file. That way std::sort (or any other sort algorithm) will sort the vector correctly.

Edited 5 Years Ago by Ancient Dragon: n/a

Thanks Ancient Dragon, that makes sense and is far easier than the way I was trying to do it!

There's only one small snag... the number attached to the resource is generated by a windows form numeric up-and-down control. Is there a way to get these numbers to have zeros prefixed to them?

Hmm.. Ok then, I'm pretty sure your first reply will help solve my problem anyway.
I think I could probably add leading zeros in the code by measuring the size of each resource ID first and inserting them if required, then use your idea :)

Thanks!

Another option is to supply your comparison method to std::sort:

int getDigitFromLine(const std::string& line){
  const string digits = "0123456789";
  size_t beg = line.find_first_of(digits);
  size_t end = line.find_first_of(digits);
  string digitString = line.substr(beg, end-beg + 1);
  return atoi( digitString.c_str() ); 
}
bool mycomp(const std::string& lhs, const std::string& rhs){
  int lhsNumber = getDigitFromLine(lhs);
  int rhsNumber = getDigitFromLine(rhs);
 return lhsNumber < rhsNumber;
}
int main(){
 //populate vector
 std::sort( vec.begin(), vec.end(), mycomp);
}

That was my original thought too, but I dismissed it because it would be horribly sloooow.

But adding leading 0's infront assumes you know the maximum number of resource

This question has already been answered. Start a new discussion instead.