zoukankan      html  css  js  c++  java
  • C++实现元组

         一般我们使用struct时需要在头文件中定义,例如

    struct Example

    {

      int a;

      char b;

      ...

    };

    这样将数据打包好必须在程序运行之前将其定义好,如果有需求在程序运行时添加数据,就无法达到目的。

    例如我需要向Example通过读取文件的方法来定义它所包含的变量。在python中。有一个结构叫做元组,如{“abcd”,1,1.23}。它可以存放各种类型的数据,并且可以动态添加或者删除。我需要用C++实现元组的形式。

    思路很简单,我们写一个类CAnyType,此类可以存放各种类型的数据并且只能存放一个数据。如CAnyType a,b,c...

    a="hello world"

    b='a'

    c=1

    ...

    class CAnyType //: public CObject
    {
    public:
        CAnyType();
        //DECLARE_SERIAL(CAnyType)
        virtual ~CAnyType();
    
    protected:
        
        CString DataType;
        union{
            int myint;
            double mydouble;
            float myfloat;
            wchar_t mychar;
            CString mystring;
          };
    
    public:
        CAnyType operator=(const int &in){myint=in;DataType=L"int";return *this;}
        CAnyType operator=(const wchar_t &in){mychar=in;DataType=L"char";return *this;}
        CAnyType operator=(const float &in){myfloat=in,DataType=L"float";return *this;}
        CAnyType operator=(const double &in){mydouble=in;DataType=L"double";return *this;}
        CAnyType operator=(const LPCTSTR lpctstring){mystring=lpctstring;DataType=L"string";return *this;}
    }

    我们首先将基础数据类型或可能用到的数据类型放入类中做成员变量,为了节省内存,可放入联合中。

    然后我们为每种数据类型重载操作符=,这个类现在就可以接受预定的任意数据类型了。如果需要其他操作(大于,小于等),可自己重载操作符。

    最后我们需要制成一个元组只需new一个数组就完成了。

    CAnyType *a=new CAnyType[size]

    为元组赋值

     a[0]=1.1

    a[1]=2

    ...

    a[size-1]="end"

  • 相关阅读:
    Redis 常用配制参数
    CentOS 7 环境下配制 Redis 服务
    Mysql ERROR 1032 (HY000): Can't find record in TABLE
    Linux下利用Shell使PHP并发采集淘宝产品
    Linux C连接Mysql
    PHP采集淘宝商品
    关于Certificate、Provisioning Profile、App ID的介绍及其之间的关系
    mac下svn无法上传.a文件的问题
    armv6, armv7, armv7s的区别
    【转】图片处理:颜色矩阵和坐标变换矩阵
  • 原文地址:https://www.cnblogs.com/jshan/p/3454240.html
Copyright © 2011-2022 走看看