user1939168
user1939168

Reputation: 557

Segmentation fault which accessing a map c++

In continuation to this question I am trying to access a map. But i am getting a segmentation fault. Below is my code:

typedef multimap<string, vector<string> > mos_map;
typedef multimap<string, vector<string> >::iterator mos_map_it;

int main()
{

mos_map mos;
mos_map_it it;

vector<string> v1;

v1.push_back("a");
v1.push_back("b");
v1.push_back("c");
v1.push_back("mo1");

mos.insert(mos_map::value_type(*(v1.end()-1),v1));

for(it=mos.begin();it!=mos.end();it++);
{
cout<<(*it).first<<endl;//seg fault occurs here
}

Upvotes: 0

Views: 1511

Answers (1)

awesoon
awesoon

Reputation: 33661

for(it=mos.begin();it!=mos.end();it++);
//                                    ^

Your loop has empty body.

Some tips:

  • Enable warnings:

    warning: for loop has empty body [-Wempty-body]

  • Declare variables only when they are needed:

    for(auto it = mos.begin(); it != mos.end(); it++);
    {
        cout << (*it).first << endl;
    }
    

    This code will cause a compile time error:

    error: use of undeclared identifier 'it'

Upvotes: 4

Related Questions