I have the following structure:
struct User
{
string name;
bool flag;
int score;
bool operator==(const User& user) const
{
return name == user.name;
}
}
namespace std {
template<>
struct hash<User>
{
size_t operator()(const User& user) const
{
return hash<string>{}(user.m_nickname);
}
};
}
After that I want to use User with unordered_set container, but after reading another portion of data I want to modify user score\\flag etc, therefore it wont affect the hash value, because I know that all users will have unique names beforehand.
In my program I use something like that:
unordered_set<User> set;
while(true)
{
User user = *set.find({name});
user.score++;
}
But after my user object goes out of scope and I find it one more time values remain the same as they were before modifying. How I can solve this problem and maybe I should use other container? I have chosen this one because of O(1) complexity.
使用Map, unordered_map
,其中键是名称,值是User。
In an unordered_set<>
each object's value is its key. Hence, the objects can't change.
One way you can get around this is by making the non-key members mutable.
That is, change
bool flag;
int score;
to
mutable bool flag;
mutable int score;
Also, you're modifying a copy.
Change
User user = *set.find({name});
to
auto &user = *set.find({name});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.