Search code examples
c++stdvectorstdmap

How to compare std::vector items with key elements of std::map


I am trying to change items in a vector if they match key values of a map so that e.g. a "2" in the vector is replaced by "two", which is the value of the key "2" of the map.

I cannot figure out how to compare these two elements because I cannot do something like: vector[i| == map_iterator->first

I know there are other ways to do this (switch statements etc.) but I still want to know if it is possible to compare std::vector and std::map in this way.

Code:

#include <iostream>
#include <string>
#include <map>
#include <vector>

    int main()
{
    std::map<int, std::string> numbers;
    numbers.insert(std::pair<int, std::string>(0, "zero"));
    numbers.insert(std::pair<int, std::string>(1, "one"));
    numbers.insert(std::pair<int, std::string>(2, "two"));
    numbers.insert(std::pair<int, std::string>(3, "three"));
    numbers.insert(std::pair<int, std::string>(4, "four"));
    numbers.insert(std::pair<int, std::string>(5, "five"));
    numbers.insert(std::pair<int, std::string>(6, "six"));
    numbers.insert(std::pair<int, std::string>(7, "seven"));
    numbers.insert(std::pair<int, std::string>(8, "eight"));
    numbers.insert(std::pair<int, std::string>(9, "nine"));
    numbers.insert(std::pair<int, std::string>(10, "ten"));

    std::map<int, std::string>::iterator itr = numbers.begin();
    
    std::vector<std::string> str_v ={"What", "The", "2", "4", "12"};
    
 
            for( int i = 0; i < str_v.size(); i++)
            {
                for(numbers.begin(); itr != numbers.end(); itr++)
                {
                    if(str_v[i] == itr->first) //this is the problem!
                    {
                        str_v[i] = numbers[i];
                       
                    }
                   
                }
                std::cout << "Element of vector: " << str_v[i] << std::endl;
            }
         

    return 0;
}
`````````

Solution

  • Iterate the vector and if the item is numeric, look it up in the map. If found then replace the item with the map value. Repeat until done.

    for (auto &item : str_v)
    {
        int key;
        std::stringstream ss(item);
        if (ss >> key)
        {
            auto itr = numbers.find(key);
            if (itr != numbers.end())
                item = itr->second;
        }
    }
    

    produces for your example input:

    What The two four 12