2

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?

1
  • mymap is default construct so is empty (it is valid). Commented Feb 9, 2016 at 13:05

3 Answers 3

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

how to have iterator to the mymap
0
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]

4 Comments

How to use iterator to map within struct?
@Shubhamgupta I Don't understand what you are asking.
how to use map<int ,int >:: iterator it to mymap
@Shubhamgupta auto it = n[some_valid_index].mymap.begin();
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.