【发布时间】:2019-03-07 15:15:42
【问题描述】:
我有一个由元组组成的常量向量,其中每个元组都包含一个键、名称、数量、值。这就是我的定义-
// 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),
};
在主函数内部,我需要每个元组的索引和所有值来处理。为简单起见,我使用以下方式打印它们-
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 中是否有更简洁的方法来定义元组的常量向量?
【问题讨论】:
-
只需将最后一个代码块中的
()更改为{}。
标签: c++ c++11 vector tuples stdtuple