leon
leon

Reputation: 181

C++ map questions about syntax

I am trying to learning more about maps in general: i have never seen syntax like this before: charMap[c]++; i assume it is adding a char into as key? and incrementing the count as value? Would someone be able to provide where i can see this notation? I cant seem to find any information of this.

int firstUniqChar(string s) {
    unordered_map<char, int> charMap;
    for (char c : s)
        charMap[c]++;            
}

Also I was wondering, how come i receive an error when I try to insert into map but it works when i do map?

int firstUniqChar(string s) {
    map<string,int> myMap;

    for( int i=0; i<s.length(); i++){
       auto it = myMap.insert({s[i],1});
        if(!it.second){
            it.first->second+=1;      
        }

    }
    auto itr = myMap.begin();
    while(itr!=myMap.end()){

        cout<<it->first;
        it++;
    }

}

Upvotes: 0

Views: 78

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117178

unordered_map<char, int> charMap;
charMap[c]++;

std::map::operator[]:

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

So charMap[c] returns a reference to the mapped int that is increased with ++.

auto it = myMap.insert({s[i], 1});

There's no matching insert overload. Try using emplace:

auto it = myMap.emplace(s[i], 1);

Edit: I just noticed that you changed to a map with a string as key in your second part of the code and that you probably try to create a string from the char s[i] with length 1 when you do {s[i],1}, but that's the wrong way around. The count comes first, then the char - it also lacks the value part.

Using insert it could look like below. I'm using structured bindings to make it easier to see what's what.

map<string,int> myMap;

for(size_t i=0; i<s.length(); i++){
   // create a string of length 1 mapped to the value 1
   auto [it, inserted] = myMap.insert({{1, s[i]}, 1});
   auto& [key, value] = *it;
   if(inserted == false) {
       ++value;
   }
}

Upvotes: 2

Related Questions