Link to home
Start Free TrialLog in
Avatar of turn123
turn123Flag for United States of America

asked on

Map and accessing?

#include <map>
#include <iostream>
#include <string>

class sizer {
     public:
          sizer(){
            std::map <std::string, std::string> price;
            std::map <std::string, std::string> size;
            std::string part1 = "1450A";
            std::string price1 = "40.65";
            std::string dim1 = "7,34 1/2,3 1/2,";

            price[part1]=price1;
            size[part1]=dim1;
            };
          void accessPrice(std::string part){
            std::cout << price[part]; // I want this to print out the price for the part passed to it but it doesn't work.
            // What do I need to do to make this work?
               return
          }
};
Avatar of AlexFM
AlexFM

std::cout << price[part1];
Avatar of jkr
Use

std::cout << price[part].second;
Oh, BTW, you should better use 'find()' in order to be able to handle the case that the key you want to look up does not exist in the map, e.g.

void accessPrice(std::string part){

 std::map <std::string, std::string>::iterator i = price.find(part);
 if ( i != price.end()) std::cout << i->second << std::endl;
   else
    std::cout << part << " could not be found" << std::endl;
}
Hi turn123,
> >std::cout << price[part]; // I want this to print out the price for the
> >part passed to it but it doesn't work.

Where is accessPrice getting price variable from.
In the code you posted, price is not declared within the scope that can be accessed by accessPrice function.

From looking at your class, you should either have price be a member variable, or you should modifiy the input arguments to  accessPrice, so that it includes price variable.

David Maisonave :-)
Cheers!
Avatar of turn123

ASKER

David,

Thats the problem is I'm unsure how to declare it so accessPrice can see it.  Can you post code on how to do that?

Thanks,
Turn123
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of turn123

ASKER

Thanks for the tip jkr.  I'll use it that way.
Avatar of turn123

ASKER

Thank you jkr!
turn123,
????
Didn't I give that as the answer?
Avatar of turn123

ASKER

Axter,

What I needed was to know how to make it work not what was wrong.  I understood that price was not in scope for accessPrice but I didn't know how to make it so it would be in scope.  jkr provided the answer I needed for this question.

Looking back knowing how to do it I see that you gave me the correct answer first but I didn't understand what you were saying :-(.

Thank you for helping me though.  I really appreciate it.

Turn123