0

I'm using a multiset object to sort a group of strings that I'm passing into it(using the default alphabetical ordering that it provides). My issue is that it is not sorting the strings like it is supposed to. I know it should work because I was using one in another part of my code to do the same thing, and I had no issues. Args is a string with a bunch of words in it, and I'm stripping out the words individually to be sorted by the multiset. Here is the function in which I'm using it in:

void
SimpleCommand::sortAndInsertArgument(char * args){
//cout << args;
    char * word;
    multiset<string> sortedArgs;
    word = strtok (args," \t\n");
    while(word!=NULL){
      sortedArgs.insert(strdup(word));
      word = strtok (NULL," \t\n");
    }
    multiset<string>::iterator it;
    for(it=sortedArgs.begin();it!=sortedArgs.end();it++){
      string str = *it;
      const char * charStr = str.c_str();
      Command::_currentSimpleCommand->insertArgument(strdup(charStr));
    }
}
Otto45
  • 555
  • 2
  • 6
  • 20
  • Your code has a memory leaks. Why are you calling strdup()? Each call to strdup() allocates memory. Remove the call to strdup() and you may not solve your issue, but at least you will get rid of the leaks. – PaulMcKenzie Feb 27 '14 at 23:21
  • Why do you think the multiset is not sorted? Can you show us your testcase in an SSCCE? – Mooing Duck Feb 27 '14 at 23:23
  • If I were to give the above code the string "command.o lex.yy.o cat_grep.cc" it would output it in that order, instead of sorting it alphabetically. – Otto45 Feb 28 '14 at 00:45
  • [Works for me](http://ideone.com/C7cQw5) – Igor Tandetnik Feb 28 '14 at 02:16
  • That's weird, because I'm doing the same thing and it won't sort it. – Otto45 Feb 28 '14 at 02:29
  • What's even more strange is that if I give it a string just like you did, it puts several copies of the string into the multiset. Even if I create a string inside the function itself and feed that to the while loop with strtok, the while loop for some reason runs several times past when it should and continues to restart at the beginning of the string. – Otto45 Feb 28 '14 at 02:55

0 Answers0