【问题标题】:Forming a Tuple Array C++形成元组数组 C++
【发布时间】:2019-10-21 05:44:38
【问题描述】:

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

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

【问题讨论】:

  • {{"food 1",1.2,20},{"food 2",1.2,20},{"food 3",1.2,30}};
  • 可以编译吗?
  • 你最好使用结构体 - 为这些属性命名,get&lt;1&gt;(o) 的可读性远低于o.price
  • 如果它编译,它是可能的。否则,您正在寻找意见,所以这不是问题
  • 我收到错误:2.1.cpp|8|错误:从 'int' 转换为非标量类型 'std::tuple<:__cxx11::basic_string std: :char_traits>, std::allocator >, float, int>' 请求|

标签: c++ arrays struct tuples


【解决方案1】:

可以这样做:

//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

【讨论】:

    【解决方案2】:

    语法是:

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

    Demo

    【讨论】:

    • 使用您的方法时出现错误。但是,我确实通过设置先声明元组然后创建数组来解决此问题。
    • @amirt01:添加了演示链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多