我正在尝试制造“自动售货机”,在这里我可以吃各种各样的小吃,每种小吃都是一个具有名称,价格和数量的元组。这可能吗?还是我最好只使用结构?这是我到目前为止的内容:
#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;
}
答案 0 :(得分:0)
语法为:
tuple<string, float, int> snacks[3] = {
{"food 1", 1.2, 20},
{"food 2", 1.2, 20},
{"food 3", 1.2, 30}
};
但是对于人类来说,使用struct更容易,因此您可能有个好名字:
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);
}
答案 1 :(得分: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