c++ - 按值传递 char 数组

标签 c++ c++11

我在按值将 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/

相关文章:

c++ - 检查二维数组中的对象是否为 Null

c++ - 加载共享库时出错 : libgsl. so.0:无法打开共享对象文件:没有这样的文件或目录

c++ - 创建一个带有任何签名的 "do-nothing" `std::function`?

c++ - 可变模板函数 : argument number for each argument

c++ - 为什么 clang 和 gcc 以不同的方式处理具有类内初始化的结构的支撑初始化?

c++ - XCode 的简单 C++ 项目问题

c++ - 指向抽象模板基类的指针?

c++ - 哈夫曼解码函数重复解压一个字符

c++ - 成员函数声明的参数列表后的单个&符号是什么意思?

C++ std::线程 "Attempt to use a deleted function"