我在按值将 char 数组传递给 priority_queue
时遇到问题。我想给构造函数传递一个唯一的值,但是我只能把优先级队列中的类型赋值给char*
。这会导致问题,因为传递的值在算法的每次迭代中都会发生变化,然后优先级队列中的所有值都会发生变化(因为每个元素都是指向任务的指针)。这是一个代码示例:
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);
有什么方法可以为优先级队列的每个元素分配一个唯一的字符串?
最佳答案
正如对问题的评论建议您可以包装 char [100]
和 int
到新类型(因为 pair<>
给出了很差的抽象)。
另一种选择是使用 std::string
, std::vector<char>
, std::array<char, 100>
而不是 char[100]。
PS:调用atoi(&priority)
可能会下降,因为 atoi
需要以 null 结尾的 C 字符串,而不是指向单个字符的指针。
关于c++ - 按值传递 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18059428/