Accessing methods of a class on a vector of pointers

Asked

Viewed 57 times

0

All right, I have a Package class with a public method double calculate_cost().
I need to create a std::map<string, std::vector<Package*>> where I can iterate through the array and save the return of the calculate_cost() method into a variable.
(The map is std::map<std::string, std::<vector<Package*>> packagemap;)

I’ve been tempted in some ways, among them:

std::map<std::string, std::vector<Package*>>::iterator mit;
std::vector<Package*>::iterator vit;
double total{0};
for (mit = packagemap.begin(); mit != packagemap.end(); ++mit) {
  for (vit = mit->second.begin(); vit != mit->second.end(); ++vit)
    total += mit->second[*vit].calculate_cost();

But I’ve been getting this mistake most of the time:

error: invalid Conversion from ːPackage*' to ːStd::vector::size_type' {aka 'long unsigned int'} [-fpermissive] total += mit->Second[*Vit]. calculate_cost();

                             ^~~~  

This mix of map and pointer vector has confused me a lot. I appreciate help!

1 answer

0

I suggest you simplify and use the syntax of ranged for loop which makes the code even more readable.

When iterating a map with this syntax, with:

for (auto elemento : colecao)

The key is accessible through .first, in the above example would be elemento.first and the value with .second. In his example the value, the second is a pointer vector, but you can still use another ranged for loop to iterate on these.

Example:

double total = 0;
for (auto package_entry : packagemap){
    for (auto package_ptr: package_entry.second){
        total += package_ptr->calculate_cost();
    }
}

Watch it work on Ideone

It is important to mention that this syntax works in c++11 up.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.