1

I have problem with passing a char array by value to a priority_queue. I want to pass a unique value to the constructor, but I can only assign the type in the priority queue to char*. This causes a problem since the value passed changes through each iteration in the algorithm and then all the values in the priority queue (since every element is a pointer to task). Here is a code sample:

 char task[100];
 char priority;
 pair<int, char*> temp;
 priority_queue< int, vector<pair<int, char*>>, compare> queue;
 printf("Define a priority and a task to be done (exit by pressing CTRL-D):\n\n");
 do {
    priority=getchar();
    if(isdigit(priority)){
      scanf("%s", task);
      temp=make_pair(atoi(&priority), task); //I want to pass by value here not by reference, is there any solution to this?
      queue.push(temp);
      printf("%i %s\n", temp.first, temp.second);
    }
 } while(priority != EOF);

Is there any way that I can assign a unique string to every element of the priority queue?

3
  • 3
    The C++ solution: pass a string or vector<char> by value. The C solution: struct foo { char task[100]; }; and pass that struct by value. Commented Aug 5, 2013 at 13:31
  • 3
    Just use make_pair(..., std::string(task)) and change the related types accordingly. Commented Aug 5, 2013 at 13:33
  • Ok. I get it, this is a solution to the problem. Using char[] only is not a option at all in this case? Commented Aug 5, 2013 at 13:39

2 Answers 2

2

As comment to question suggests you can wrap char [100] and int to new type (since pair<> gives poor abstraction). Another option is to use std::string, std::vector<char>, std::array<char, 100> instead of char[100].

PS: call to atoi(&priority) might fall because atoi expects null-terminated C-string, not a pointer to single character.

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

Comments

0

You could use something like std::array<char,100> I guess, but your current vector type requires a dynamically allocated string.

Do you want to force every element of your vector to be more than 100 bytes, however long the string?

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.