如何将混合数据类型(int、float、char 等)存储在数组中? [英] How can mixed data types (int, float, char, etc) be stored in an array?

查看:26
本文介绍了如何将混合数据类型(int、float、char 等)存储在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数组中存储混合数据类型.怎么能这样呢?

I want to store mixed data types in an array. How could one do that?

推荐答案

您可以使数组元素成为可区分的联合,又名 标记联合.

You can make the array elements a discriminated union, aka tagged union.

struct {
    enum { is_int, is_float, is_char } type;
    union {
        int ival;
        float fval;
        char cval;
    } val;
} my_array[10];

type 成员用于保存对每个数组元素应使用union 的哪个成员的选择.所以如果你想在第一个元素中存储一个 int,你可以这样做:

The type member is used to hold the choice of which member of the union is should be used for each array element. So if you want to store an int in the first element, you would do:

my_array[0].type = is_int;
my_array[0].val.ival = 3;

当要访问数组的某个元素时,必须先检查类型,然后使用联合的对应成员.switch 语句很有用:

When you want to access an element of the array, you must first check the type, then use the corresponding member of the union. A switch statement is useful:

switch (my_array[n].type) {
case is_int:
    // Do stuff for integer, using my_array[n].ival
    break;
case is_float:
    // Do stuff for float, using my_array[n].fval
    break;
case is_char:
    // Do stuff for char, using my_array[n].cvar
    break;
default:
    // Report an error, this shouldn't happen
}

程序员需要确保 type 成员始终对应于存储在 union 中的最后一个值.

It's left up to the programmer to ensure that the type member always corresponds to the last value stored in the union.

这篇关于如何将混合数据类型(int、float、char 等)存储在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆