形成元组数组C++

Forming a Tuple Array C++

本文关键字:C++ 数组 元组      更新时间:2023-10-16

我正在尝试制作一个"自动售货机",在那里我可以吃一系列零食,每个零食都是一个带有名称、价格和数量的元组。这是可能的还是我最好只使用结构?这是我到目前为止所拥有的:

#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);
}

演示