I am writing a parser, and I decided to save type information in a std::map. When I use the [] operator to access it, I always get the 0 value for the enum. The map is declared as such:

enum type {Bool, Bool_a, Int_4, Inta_4, Int_8, Inta_8, Float_s, Floata_s, Float_d, Floata_d, Ch_s, Ch_a, Str, Invalid};  

class  kparse_ret{
...  
    std::map<std::string, type  
...  
} ret_data;

And is then set using something like

ret_data.type_list[itemname] = Int_4;  

(Where itemname is a std::string)
The problem I'm having is that when I use

ret_data.type_list[data_name]  

I always get Bool, or 0. (again, data_name is a std::string). I know that itemname and data_name have exactly the same contents when their respective contexts are reached. Furthermore, if I use itemname again to access it, I get the value I just set it to.

有帮助吗?

解决方案

When comparing string as key for a map, not only the content of the string are compared but also the size of the the string for example.

The following will help you identify the problem :

std::map<std::string, std::string>

std::string key = "KEY";
std::string key2 = "KEY";

key2.resize(100);

now if you mapped something on "KEY" and use key2 to access it, you won't obtain the value yous expected.

jav

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top