3

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?

ravi
  • 6,140
  • 18
  • 77
  • 154

1 Answers1

9

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},
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Perhaps adding that `std::make_tuple` can get you out of a tight spot if some deduction or references spoil the fun. – rubenvb Mar 07 '19 at 15:24
  • It works like a charm. See here for the [demo](https://repl.it/repls/ScrawnyScrawnyExabyte). I was unnecessary thinking too much! – ravi Mar 07 '19 at 15:26