Accessing methods of a class in a vector of pointers

0

Right, I have a Package class with a public method double calculate_cost ().
I need to create a std::map<string, std::vector<Package*>> in which I can iterate through the vector and save the return of the calculate_cost () method on a variable. Home (The map is std::map<std::string, std::<vector<Package*>> packagemap; )

I've been tempted in some ways, including:

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 get this error in most attempts:

  

error: invalid conversion from 'Package *' to 'std :: vector :: size_type' {aka 'long unsigned int'} [-fpermissive] total + = mit- > second [* vit] .calculate_cost () ;

                             ^~~~  

This blend of map and vector pointers has got me pretty confused. Thanks for your help!

    
asked by anonymous 05.10.2018 / 23:37

1 answer

0

I suggest simplifying and using the syntax of the ranged for loop > that still brings more readability to the code.

When iterates a map with this syntax, with:

for (auto elemento : colecao)

The key is accessible through .first , in the example above it would be elemento.first and the value with .second . In its example the value, second is a vector of pointers, but can use another ranged for loop to iterate over them.

Example:

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

See it working on Ideone

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

    
06.10.2018 / 00:49