如何创建一个可以存储两种类型数据的数组 [英] How to create an array which can store two types of data

查看:99
本文介绍了如何创建一个可以存储两种类型数据的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,研究员:


我在创建一个可以存储两种不同数据类型的数组时遇到困难,例如:C ++中的string和int。有些网站告诉我这是不可能的。或者使用类来完成它。任何人都可以帮我解决这个问题。非常感谢你!

Hello, fellows:

I having difficulties on creating an array which can store two different data types, for example: string and int, in C++. Some of the websites told me it is impossible. Or use class to do it. Could anyone give me a hand on this. Thank you every much!

推荐答案

一个类或结构是要走的路,你可以从阅读本文
A class or structure is the way to go, you could start by reading this.


您对课程模板了解吗?


模板< class T>

类数据

{

T theValue

//为简洁省略了类方法

};


数据< int> ARR [100]; //包含整数的100个数据对象的数组

数据< string> ARR1 [100]; //包含字符串的100个数据对象的数组
Do you know about class templates yet?

template<class T>
class Data
{
T theValue
//class methods omitted for brevity
};

Data<int> arr[100]; //array of 100 Data objects containing ints
Data<string> arr1[100]; //array of 100 Data objects containing strings



你好,伙计:


我有创建一个可以存储两种不同数据类型的数组的困难,例如:C ++中的string和int。有些网站告诉我这是不可能的。或者使用类来完成它。任何人都可以帮我解决这个问题。非常感谢你!
Hello, fellows:

I having difficulties on creating an array which can store two different data types, for example: string and int, in C++. Some of the websites told me it is impossible. Or use class to do it. Could anyone give me a hand on this. Thank you every much!



这样做的间接方法是创建一个struct数组,它本身是两个或多个数据类型的联合,例如


union u

{

int i;

char j; //用于存储字符串你可以保留字符*

};


struct s

{

int eletype; //说int = 0,char = 1等等

union u data;

};


struct s array [10];

array [0] .eletype = 0; // store int

array [0] .data = 12;


array [1] .eletype = 1;

array [1] .data =''g'';

An indirect way to do this is to create an array of struct which itself is union of two or more data types eg

union u
{
int i;
char j; //for storing string u can keep char *
} ;

struct s
{
int eletype; //say int =0, char =1 and so on
union u data;
};

struct s array[10];
array[0].eletype = 0; //store int
array[0].data = 12;

array[1].eletype = 1;
array[1].data = ''g'';


这篇关于如何创建一个可以存储两种类型数据的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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