Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have these classes:

C++
class Restaurant {
    public:
    std::string name;
    std::set<std::string> food;
};

class Owner {
    public:
    Restaurant *res;
    int position;
}


And then I have this vector

std::vector<Owner> vec;


I need to group the owners having the same name together. how can I do so?

What I have tried:

I know I can loop through it like this to print:

C++
for (auto v : vec ){
     cout << v.res->name << "- " << v.position << endl;

}

giving me:

C++
branch1- 4
branch2- 10
branch3- 3
branch1- 2


However, what I want is:
branch1- 6
branch2- 10
branch3- 3
Posted
Updated 21-Nov-20 17:30pm

1 solution

Use a map:
C++
std::map<std::string, int> groups;

//Build the map from the vector;
for(auto v : vec) {
    groups[v.res->name] += v.position; 
}


// print it out
for(auto totals : groups) {
     std::cout << totals.first << "- " << totals.second << std::endl;
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900