gpt4 book ai didi

C++ 如何将 STL 列表传递给函数

转载 作者:行者123 更新时间:2023-11-27 23:55:28 25 4
gpt4 key购买 nike

我用 C++ 编写了以下代码。函数“change_list”的声明给出了一个错误:“不允许不完整的类型”和“标识符“列表”未定义”。你知道为什么吗?我只是遵循了这篇文章中的答案:C++ pass list as a parameter to a function

#include <iostream>
#include <list>

typedef struct Point {
int x;
int y;
} Point;

Point* initPoint(int x, int y) {
Point* pt = (Point*)malloc(sizeof(Point));
pt->x = x;
pt->y = y;
return pt;
}

void change_list(list<Point*> &mylist){ // ERROR!!!
mylist.push_back(4);
}

int main()
{
using namespace std;
list<Point*> c1; // initiating a list
c1.push_back(initPoint(1, 1));
c1.push_back(initPoint(2, 2));
c1.push_back(initPoint(3, 3));

change_list(c1);

for (Point* c : c1)
cout << " " << c->x;
cout << "\n";

return 0;

}

最佳答案

问题是语句mylist.push_back(4) ,其中您传递一个整数,而 mylist期望一个 Point* .如果你这样调用它 mylist.push_back(new Point())它编译。顺便说一句:也许你应该写 std::list或放置 using std::list #include<list> 之后的某处.

关于C++ 如何将 STL 列表传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com