Reputation: 505
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?
Upvotes: 1
Views: 1008
Reputation: 567
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.
Upvotes: 2
Reputation: 67743
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?
Upvotes: 0