I need to have a key with multiple values. What datastructure would you recommend?

前端 未结 7 1134
悲哀的现实
悲哀的现实 2021-02-07 10:53

I have an string array filled with words from a sentence.

words[0] = \"the\"
words[1] = \"dog\"
words[2] = \"jumped\"
words[3] = \"over\"
words[4] = \"the\"
word         


        
相关标签:
7条回答
  • 2021-02-07 11:28

    I've found that a struct may work well for this situation. This approach (basically akin to a class) allows a cleaner access to your parameters named as you see fit.

    struct car_parts {
    
        string wheelType;
        string engine;
        int number_of_cylinders;
    
        car_parts(string _wheelType, string _engine, int _number_of_cylinders)
        {
            wheelType = _wheelType;
            engine = _engine;
            number_of_cylinders = _number_of_cylinders;
        }
    };
    
    int main()
    {
        // Populate the dictionary
        map<char, car_parts> vehicles =
        {
            { 'I', car_parts("All terrain", "X2", 6) },
            { 'C', car_parts("Summer only", "BB", 8) },
            { 'U', car_parts("All terrain", "X3", 4) }
        };
    
        map<char, car_parts>::iterator it;
    
        it = vehicles.find('I');
    
        if (it != vehicles.end())
        {
            cout << "The vehicle with key of I has " << it->second.number_of_cylinders << " cylinders\n";
        }
    }
    
    0 讨论(0)
提交回复
热议问题