简体   繁体   中英

C++ how to pass an STL list to a function

I wrote the following code in C++. The declaration of the function "change_list" gives an error: "incomplete type is not allowed" and "identifier "list" is undefined". Do you know why? I just followed the answers in this post: 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;

}

The problem is statement mylist.push_back(4) , in which you pass an integer whereas mylist expects a Point* . If you call it like mylist.push_back(new Point()) it compiles. BTW: maybe you should write std::list or place a using std::list somewhere after #include<list> .

There are two issues in your code :

  1. You have used namespace std in main, either use std globally (bad practice) or use std::list.
  2. In function change_list, push a valid Point type pointer, you are pushing an integer.

      void change_list(std::list<Point*> &mylist){ // ERROR!!! mylist.push_back(initPoint(8, 8)); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM