我有一个恒定的元组向量,其中每个元组都包含一个键,名称,数量和值。这就是我的定义方式-
// 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),
};
在main函数中,我需要每个元组的索引和所有值进行处理。为简单起见,我使用以下方式打印它们-
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;
}
很明显,定义向量的方法不是那么干净。 我希望有很多更清洁的东西,例如以下-
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),
};
在C ++ 11中是否有一种更清晰的方法来定义元组的常数向量?
答案 0 :(得分:8)
您可以使用{}
:
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},
};