形成元组数组C++
Forming a Tuple Array C++
我正在尝试制作一个"自动售货机",在那里我可以吃一系列零食,每个零食都是一个带有名称、价格和数量的元组。这是可能的还是我最好只使用结构?这是我到目前为止所拥有的:
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
tuple<string, float, int> snacks[3] = {("food 1",1.2,20),("food 2",1.2,20),("food 3",1.2,30)};
int main() {
return 0;
}
这可以像这样完成:
//declare and initialize tuples
tuple<string, float, int> potato("Potato Chips", 1.25, 20), cookie("Cookies", 0.85, 20), candy("Candy", 0.95, 20);
//set up array
const int s = 3; //size of array.
array<tuple<string, float, int>, s> snacks = {potato, cookie, candy}; //array
语法为:
tuple<string, float, int> snacks[3] = {
{"food 1", 1.2, 20},
{"food 2", 1.2, 20},
{"food 3", 1.2, 30}
};
但是人类更容易使用结构,所以你可能有一个很好的名字:
struct Snack
{
std::string name;
float price = 0;
int quantity = 0;
};
Snack snacks[3] = {
{"food 1", 1.2, 20},
{"food 2", 1.2, 20},
{"food 3", 1.2, 30}
};
您可能仍然具有将结构转换为std::tuple
作为比较的功能,或者对每个成员进行通用迭代:
auto as_tuple(const Snack& s) { return std::tie(s.name, s.price, s.quantity); }
auto as_tuple(Snack& s) { return std::tie(s.name, s.price, s.quantity); }
bool operator <(const Snack& lhs, const Snack& rhs) {
return as_tuple(lhs) < as_tuple(rhs);
}
演示
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '