Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 形成元组数组C++;_C++_Arrays_Struct_Tuples - Fatal编程技术网

C++ 形成元组数组C++;

C++ 形成元组数组C++;,c++,arrays,struct,tuples,C++,Arrays,Struct,Tuples,我正在尝试制作一个“自动售货机”,在那里我可以有一系列的零食,每个零食都是一个元组,上面有名称、价格和数量。这是可能的还是我最好只使用structs?以下是我到目前为止的情况: #include <iostream> #include <tuple> #include <string> using namespace std; tuple<string, float, int> snacks[3] = {("food 1",1.2,20),("

我正在尝试制作一个“自动售货机”,在那里我可以有一系列的零食,每个零食都是一个元组,上面有名称、价格和数量。这是可能的还是我最好只使用structs?以下是我到目前为止的情况:

#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;
}
#包括
#包括
#包括
使用名称空间std;
元组零食[3]={(“食物1”,1.2,20),(“食物2”,1.2,20),(“食物3”,1.2,30)};
int main(){
返回0;
}
语法应该是:

tuple<string, float, int> 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);
}
auto-as_-tuple(const-Snack&s){return std::tie(s.name,s.price,s.quantity);}
自动组件(快餐和小吃){return std::tie(s.name,s.price,s.quantity);}

bool操作符可以这样做:

//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
//声明和初始化元组
元组土豆(“薯片”,1.25,20),饼干(“饼干”,0.85,20),糖果(“糖果”,0.95,20);
//设置阵列
常数int s=3//数组的大小。
数组零食={土豆、饼干、糖果}//排列

{“食品1”,1.2,20},{“食品2”,1.2,20},{“食品3”,1.2,30}它编译吗?你最好使用结构-给那些属性命名,
get(o)
的可读性比
o.price
要差得多。如果它编译,这是可能的。否则,您正在寻找意见,因此这不是一个问题。我得到了一个错误:2.1.cpp | 8 |错误:请求将“int”转换为非标量类型“std::tuple”|我使用您的方法得到了一个错误。但是,我确实通过设置先声明元组,然后创建数组来解决了这个问题。@amirt01:添加了演示链接。
//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