在结构体中使用列表

Using a list inside a struct c++

本文关键字:列表 结构体      更新时间:2023-10-16

我从编程开始,我的英语不好,很抱歉。

我喜欢在结构体内部使用列表而不是数组,就像这样:

#include <iostream>
#include <list>
using namespace std;
struct Market {
        string b;
        list <int> prices;
    };
int main()
{   list <int> precios;
    Market m1 = {"a",NULL};
    return 0;
} 

但是我得到这个错误转换从int' to non-scalar type std::list<int, std::allocator<int> >请求|

这可能吗?也许用malloc或free?

应该定义一个构造函数

struct Market {
    Market(string val){b=val;}
    // or like this:
    // Market(string val):b(val){}
    string b;
    list <int> prices;
};

然后你就可以创建这样的对象:

Market a("A");

由于list的默认构造函数创建的是空列表,所以你不需要给它传递任何参数。

关于类基础知识的好读物:http://www.cplusplus.com/doc/tutorial/classes/

NULL不是std::list<int>类型,这就是为什么你得到这个错误。

你正在使用c++ 11编译器吗?

如果是,则尝试:

Market m1 = {"a", { NULL } }; 
否则

:

list<int> prices;
Market m1;
m1.b = "a";
m1.prices = prices;

您正在尝试用空指针值(实际上是int类型)初始化list。如果您需要按值存储列表,您可以初始化'm1',如下所示

Market m1 = {"a", std::list<int>()};