How to add valid key without specifying value to a std::map?

后端 未结 5 1172
不知归路
不知归路 2021-02-20 05:10

I have a std::map, and I would like to add a valid key to iterate over it later, but without giving any value (it will be given later on in the course of the iterations).

相关标签:
5条回答
  • 2021-02-20 05:17

    /* I don't want to do that because in fact I don't use a float type */

    Then instead of std::map use the std::set.

    0 讨论(0)
  • 2021-02-20 05:18

    you can try by just making a temporary float or any data type and initialize the value of the map with it.

    #include <iostream>
    #include <map>
    #include <string>
    #include <vector>
    using namespace std;
    
     int main()
     {
     map <string,map<int,vector<int>>> hen;
    map<int ,vector<int>> m;
    
    string s="egg";
    hen[s]=m;
    hen[s][1].push_back(5);
    
    
    
    
    return 0;}
    

    as you can see in this example I have made temporary map m to initialize it to hen[s] similarly, you can create a temp float to initialize it to your map.

    0 讨论(0)
  • 2021-02-20 05:24

    I suppose something that could help you out is Boost.Optional.

    #include <boost/optional.hpp>
    #include <map>
    
    class CantConstructMe
    {
        CantConstructMe() {}
    };
    
    int main()
    {
        std::map<int, boost::optional<CantConstructMe> > m;
        m[0];
    }
    

    The lack of available default constructor is not an issue, by default optional will be empty.

    0 讨论(0)
  • 2021-02-20 05:27

    I'm not entirely sure what you mean by "without giving any value" but if you mean without explicitly assigning a value then just do

    map[valid_keys[i]];
    

    This still works i.e. it creates a new entry in the map if there was not previously one with that key. The operator[] just returns a refernce to the value so that you can assign a new value to it but remember it's already been default constructed.

    If, on the other hand, you mean you want to express that there is no meaningful value and it may or may not subsequently receive a valid value then see @UncleBens` answer.

    0 讨论(0)
  • 2021-02-20 05:32

    It seems like you really want a std::set or std::list of keys, and then iterate over that set later to create your map.

    If for some reason this isn't acceptable, you could wrap your float with some type of object that implements operator float(), and various conversion functions for float, but also has a "good()" flag or somesuch.

    If your final values are actually floats, you could initialize the values to +/- NaN as a simple placeholder.

    I would say boost::optional is a better option for production code, but it depends on your requirements.

    0 讨论(0)
提交回复
热议问题