Shubham gupta
Shubham gupta

Reputation: 21

How to use map stl within struct data structure and initialize the map and then reference to it?

Is it correct method to have map within struct and then having array of structure.

struct node    {             //struct node
    std::map<int ,int> mymap;//stl map within struct
};
struct node n[10];           //array of struct node

Then how to initialise n and refer to map within it? How to have iterator to map within struct that is mymap? any best way?

Upvotes: 2

Views: 546

Answers (3)

Humam Helfawi
Humam Helfawi

Reputation: 20264

Bad or good idea is opinion-based. However, it is not wrong.

std::map does not need to be initialized. The default constructor will do it for you.

How to access your map ?

for(size_t i=0;i<10;++i){
    n[i].mymap//.something
}

Upvotes: 1

oklas
oklas

Reputation: 8220

There is an example static initialisztion:

node n[3] = {
    {
        { {1,2}, {3,4} }
    },
    {
        { {1,2}, {3,4} }
    },
    {
        { {1,2}, {3,4} }
    }
}; 

remove "struct" before n declaration. and about accessing map elements like this:

n[1].mymap[1] // = 2
n[2].mymap[3] // = 4

need to specify modern c++ language standart, for gcc command line will be like this:

g++ -std=c++0x main.cpp

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180500

struct node n[10]; 

Creates an array of 10 nodes that are default initialized. Since std::map has a default constructor each node in n will have the map default constructed.

To access the map you just use

n[some_valid_index].mymap//.some_member_function;

Remember that arrays are 0 index based so some_valid_index needs to be in the range of [0, 9]

Upvotes: 0

Related Questions