Hatted Rooster
Hatted Rooster

Reputation: 36463

C++ map with a struct

So, I got this:

struct People_Info {
  bool isWorking;
  std::string name;
  int age;
  float height;
};
int counter = 0;
int random = urand(1, 4);
std::map<uin64, People_Info> PeopleMap;

Now, a function will get called that will create an entry in the map with this struct that will set some default values:

PeopleMap[counter].isWorking = false;
PeopleMap[counter].name = "Mr";
PeopleMap[counter].age = 1;
PeopleMap[counter].height = 1.60f;
counter++;

Now, that is the function that should make an entry for someone new, but, throughout the script I will remove some entries, so if I got 5 elements, and I remove e.g. the second one, then, I want to edit some variables of everyone in the map:

for(int i = 0; i < 5 ; i++) {
  if(PeopleMap[i] == PeopleMap.end())  // Don't edit map entries that are erased
    continue;

  PeopleMap[i].isWorking = true;
}

Now, for some reason it is still editing all the entries, do I need to use new to make a struct for every entry?

Upvotes: 5

Views: 25220

Answers (3)

dmayola
dmayola

Reputation: 512

PeopleMap.end() doesn't return a valid argument, it's like a ghost node.

For example, a way to iterate in map could be:

for(std::map<uin64, People_Info>::iterator it = PeopleMap.begin();it != PeopleMap.end() ;it++)

See, PeobleMap is like a ghost node in the end denotes that you have reach the end. In the previous for, if you like to access to map values you could do:

it->first // uint64
it->second.isWorking

So, if you use iterators you don't have to check erased values and you would be able to edit a parameter in each pair in the map (less key)

Upvotes: 3

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

When using the subscript operator to access a key in the map that doesn't exist, yet, a corresponding element is inserted. It is immaterial that the object was erased before: it will still be inserted if it doesn't exist.

To access all elements in a map you don't use the keys but rather you 'd use iterators over the map. This way no new elements get inserted.

Upvotes: 2

NPE
NPE

Reputation: 500167

The following is incorrect:

if(PeopleMap[i] == PeopleMap.end())

You probably meant to say

if(PeopleMap.find(i) == PeopleMap.end())

Upvotes: 0

Related Questions