Problem using set<>

Hello, i want to create a set to control my objects of type Habitante, but i just want save one reference of each object, so my difficult is how can i write function compare and build the struct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//.h Habitante
class Habitante{
  int idHab;
}
//.h City
class City{
set<Habitante*&> conjHabitante;//array of references

}


//.cpp City
 
bool City::operator()(const int idOb1, const int idOb2){
	return (idOb1 > idOb2)?true:false;
}

Habitante& City::findHab(const int idHab){
	set<Habitante>::reference it = conjHabitante.find(idHab);
	return it;
}

My question is how i can use set to find Habitante, and conjHabitante its correct, really is array of references?
set<Habitante*&>
That looks like a set of references to pointers to Habitante objects.
And from what I know, C++ won't allow you to use uninitialized references.

Also...
1
2
3
4
Habitante& City::findHab(const int idHab){
	set<Habitante>::reference it = conjHabitante.find(idHab);
	return it;
}

This is nasty because the reference will become invalid as soon as the it object is destroyed, being a local variable.

This said, I'm sorry but I cannot understand what you need to achieve.
hmm, ok! Actually i try using set<Habitante**>, cause i had a question about c++ and references, and so i just not want duplicate my objects when i work with them. So if i've set<Habitante**> to find some habitante using find from set , how can i implement this method? Because for that, I need some function where Template of stl can compare my objects, isn't it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Habitante{
public: // access specifier, "private" is default
  int idHab;
}

// somewhere:
// set<Habitante *> conjHabitante;

Habitante * City::findHab(int idHab){ // no purpose using const when passing by value

  // must manually search, because our set only holds pointer values (memory addresses)
  // and we can't tell which memory address is "right"
  for (set<Habitante *>::iterator i = conjHabitante.begin(); i != conjHabitante.end(); ++i)
      if ((*i)->idHab == idHab) // should use another ID name for less confusion
          return *i;

  return NULL; // special value for "nothing found"
}


I hope this helps, didn't test it.

Edit: small corrections.
Last edited on
Topic archived. No new replies allowed.