Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access and convert pair value?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading