How to access and convert pair value?

Advertisements
vector<pair<int,char>>alpha;

for(int i=0;i<26;i++){
        if(letter[i] > 0)
        {
            alpha.push_back(pair<int,char>(letter[i],(i+'A')));
        }
    }

    sort(alpha.begin(),alpha.end());

    for(auto& val:alpha){
        string str = val.second;
    }

I was trying to convert map value (which was char type) into string type using auto. I need to push those char into string. How could I solve this?

>Solution :

You could do

    string str;
    for(auto& val:alpha){
        str.push_back(val.second); // Append to back of string
    }

If you want to just append chars to the string.

Or you could do

auto str = string s(1, val.second); // 1 is the length of the string,
                                    // and val.second is the character to fill it with

If you want your strings to be just a single character long.

You could use std::generate and std::transform like others suggested if you think that makes your code more readable as other commenters has suggested (I don’t think so in this case). I leave that as an exercise for the reader.

Leave a ReplyCancel reply