Sergio
Sergio

Reputation: 77

Using a list inside a struct c++

I´m starting with the programming and i speak bad english sorry for that.

I like to use a list instead of an array, inside of a struct, something like this:

#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;
} 

but i get this error conversion from int' to non-scalar type std::list<int, std::allocator<int> > requested|

Is this possible? maybe with malloc or free?

Upvotes: 1

Views: 2371

Answers (3)

A. K.
A. K.

Reputation: 38146

NULL is not of the type std::list<int>, that's why you are getting this error.

Are you using a C++11 compiler?

If yes then try:

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

Otherwise:

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

Upvotes: 0

UldisK
UldisK

Reputation: 1639

You should define a constructor

struct Market {

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

Then you will be able to create objects like:

Market a("A");

As lists default constructor creates empty list, you dont need to pass it any parametrs.

A good read about basics of classes: http://www.cplusplus.com/doc/tutorial/classes/

Upvotes: 3

Captain Obvlious
Captain Obvlious

Reputation: 20063

You are attemping to initialize the list with a null pointer value (actually an int type). If you need to store the list by value you can initialize 'm1' like so

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

Upvotes: 0

Related Questions