Are multiple conditional operators in this situation a good idea?

前端 未结 21 2922
名媛妹妹
名媛妹妹 2020-12-15 06:23

I just saw this block of code on the Wikipedia article on conditional operators:

Vehicle new_vehicle = arg == \'B\' ? bus      :
                      arg ==         


        
21条回答
  •  长情又很酷
    2020-12-15 07:19

    A few people have already mentioned the possibility of using an std::map or other associative array type to do the job. As long as you're only doing this is one place (or a few places), you might consider just using a normal array or vector instead:

    Vehicle vehicles[CHAR_MAX];
    
    // Initialization    
    std::fill_n(vehicles, CHAR_MAX, feet);
    vehicles['A'] = airplane;
    vehicles['B'] = bus;
    vehicles['C'] = car;
    vehicles['H'] = horse;
    vehicles['T'] = train;
    
    // Use
    Vehicle new_vehicle = vehicles[arg];
    

    Depending on how may tables you need/use (that store the same type of object), and the size of the contained objects (Vehicle in this case), this can be a perfectly reasonable alternative to an std::map. If you're creating a lot of tables, or each object is really big, std::map becomes a more reasonable alternative.

    When you use an std::map (or unordered_map, etc.) you're using more code to save on data storage. This does the reverse -- but as long as Vehicle is small (say, 4 bytes), one table like the above will typically occupy something like half a kilobyte. It's hard to guess exactly how large the code for std::map is going to be for a specific compiler, but it seems likely that it'll usually be larger than half a kilobyte, so if you're only creating one table like this, std::map may be a net loss.

    Of course, if you know that you're only dealing with letters as input, you could reduce the table size quite a bit:

    template 
    class letter_table { 
        static const int range = 'Z' - 'A';
    
        T table[range];
    public:
        // ...
        T operator[](int index) {
            index -= 'A';
            assert(index

    In the example case, this would give a table around 100 bytes -- you can create a pretty fair number of 100-byte tables in the space std::map will normally occupy.

提交回复
热议问题