Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

c++ - std::unordered_map iterator deference problem

I have a code as below:

#include <iostream>
#include <unordered_map>
#include <string> 

void foo(const std::unordered_map<char, std::string>& uom){

    auto it2=uom.find('S');

    if(it2!=uom.end())  //NEVER FORGET THIS
        std::cout<< *it2 <<std::endl;
}

In this function I get error for *it2. The error is "invalid operands to binary expression." I couldn't find to solve this error. Can anyone help me? Thank you.

question from:https://stackoverflow.com/questions/65932359/stdunordered-map-iterator-deference-problem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The iterator returned by find is an iterator over keys and values, in the form of a std::pair<KeyT, ValT> (in your case std::pair<char, std::string>). So in order to access the value associated with the key you've looked up, you need to use it2->second (i.e. the second item in the pair). See the example code in the docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...