> For example, let say my Team class has a member matches_won & I want to
> update that whenever they win a match, so in that case I want to update only
> that particular team and not other teams.
map/set gives you fast searching O(lg n) based on a `less than' operation
which you've defined it like this
1 2 3
|
bool Team :: operator <(const Team& t) const{
return (this->nameOfTeam > t.nameOfTeam);
}
|
that is, you sorted them based on `nameOfTeam'
doing
auto it = Hurricanes.find( Team("Hurry", "this string is not relevant and may have any value, even empty") );
you'll get an iterator to the Hurry team stored in your Hurricanes collection
(it->first is the Team)
if you modify the object, then you may screw up the internals of the map (the order may change) so you get a const_iterator which doesn't allow you to modify the object.
you have some alternatives:
- remove/insert:
1 2 3 4
|
auto value = *it; //make a copy
Hurricanes.erase(it); //remove the element
value.first.update(); //update whatever you want
Hurricanes.insert(value); //"reinsert" it on the collection
|
- cast away:
1 2
|
auto &team = const_cast<Team&>(it->first);
team.update(); //don't modify `nameOfTeam' or you'll screw up the collection
|
- change your collection type:
set/map gives you fast insert/erase/search of elements O(lg n)
a sorted vector gives you fast search O(lg n) but slow insert/erase O(n)
¿do you expect to be removing/adding a lot? ¿do you add everything once and then operate? ¿is n quite big (say, in the thousands)?
perhaps you may use vector instead
- change your key:
map< string, Team >
where the key is the name of the team.
so then you'll say
Hurricanes["Hurry"].update();
> let say my Team class has a member matches_won
>
std::map<Team,std::string> Hurricanes;
use meaningful names for your variables