Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

std::map declared in header is null?

Status
Not open for further replies.

BlueGhost79

Programmer
Feb 6, 2008
11
US
Hi,
I declare a std::map in my header file, but when I go to add an item to it in the class it crashes as it is null.


header file

class x
{
public:
void DoStuff();
private:
std::map<int, int> sample_data;

};


source file

void DoStuff()
{
//crashes here as sample_data is null
sample_data[4] = 5;
}


why would the sample_data variable be null?

void DoStuff()
{
//crashes here as sample_data is null
std::map<int, int> sample_data;
sample_data[4] = 5;
}

will work, if sample_data is a local variable.
 
Just a thought as I haven't looked too closely. If it works for a local variable, shouldn't you call the class x's sample_data, something like x.sample_data[4] = 5? Also have you looked at using insert instead instead of assigning?


James P. Cottingham
-----------------------------------------
[sup]I'm number 1,229!
I'm number 1,229![/sup]
 
You have an empty map. No pair <int,int> with key 4 in the map! You assign a value to unexistent object.
You must insert element before access it. For example:
Code:
std::map<int,int> sample_data;
typedef std::pair<int,int> V;
...
sample_data.insert(V(4,4));
// Now you can access map element with key 4...
m[4] = 5; // or what else...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top