ravi
ravi

Reputation: 6328

Cleaner way of defining a constant vector of tuples in C++11

I have a constant vector of tuples, in which each tuple contains a key, name, quantity, value. This is how I am defining it-

// tuple of key, name, quantity, value
const std::vector<std::tuple<unsigned char, std::string, unsigned char, float> > myTable{
    std::tuple<unsigned char, std::string, unsigned char, float>(0, "mango", 12, 1.01f),
    std::tuple<unsigned char, std::string, unsigned char, float>(4, "apple", 101, 22.02f),
    std::tuple<unsigned char, std::string, unsigned char, float>(21, "orange", 179, 39.03f),
};

Inside the main function, I need the index of each tuple and all values to process. For simplicity, I am printing them using the following way-

for (int index = 0; index < myTable.size(); index++) {
    auto key = std::get<0>(myTable[index]);
    auto name = std::get<1>(myTable[index]);
    auto quantity = std::get<2>(myTable[index]);
    auto value = std::get<3>(myTable[index]);
    std::cout << " index: " << index
              << " key:" << (int)key
              << " name:" << name
              << " quantity:" << (int)quantity
              << " value:" << value
              << std::endl;
}

It is clearly visible that the way of defining the vector is not so clean. I would prefer to have a lot of cleaner something like following-

const std::vector<std::tuple<unsigned char, std::string, unsigned char, float> > myTable{
    (0, "mango", 12, 1.01f),
    (4, "apple", 101, 22.02f),
    (21, "orange", 179, 39.03f),
};

Is there a cleaner way of defining a constant vector of tuples in C++11?

Upvotes: 3

Views: 364

Answers (1)

Jarod42
Jarod42

Reputation: 217145

You might use {}:

const std::vector<std::tuple<unsigned char, std::string, unsigned char, float> > myTable{
    {0, "mango", 12, 1.01f},
    {4, "apple", 101, 22.02f},
    {21, "orange", 179, 39.03f},
};

Upvotes: 9

Related Questions