65.9K
CodeProject 正在变化。 阅读更多。
Home

新的动态数组,使用整数和字符串索引动态创建数组

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.14/5 (7投票s)

2007年5月11日

2分钟阅读

viewsIcon

38198

downloadIcon

282

介绍如何使用整数和字符串索引动态创建任何类型的数组的文章。

引言

本文档展示了如何使用整数和字符串索引动态创建数组。

背景

本文档假定您熟悉 C++ 中的链表和运算符重载,因为它是完全基于这些知识构建的。下标运算符被重载,因此我们可以动态创建数组,并且为了知道下标运算符是在左侧还是右侧,我们创建了另一个名为 ArrayItem 的类,该类维护链表,并且我们重载了 int、char* 和 double 类型等,以便识别这是右侧值。带有 const 关键字的下标运算符版本对于右侧值不起作用,所以我使用了上述不同的风格。我创建了不同的函数,以便这个类对其他人更有用,其他人也可以向这个类添加函数,并让我知道以更新这篇文章。

使用代码

 NewDynamicArray<int> NDA ;
  NDA["asd"]=1;   //will create new index
  int i=NDA["asd"]; //rhs value
  NDA[1]=3;       //will create new index
  printf("%d",(int)NDA["murtza"]); //rhs value
  NDA[1]=2; //will overwrite existing index
  i=NDA[1];  //rhs value
  
  while(NDA.MoveNext()) //will print all value 
      printf("%s",(int)NDA.Ite->value);
  NDA.ReSetIterator(); //will movbe iterator to point to first value
   
  NewDynamicArray<char*> NDa;
  NDa["age"]="twenty one"; //will create new index
  NDa["dob"]="07-aug-1985"; // will create new index
  NDa["age"]="08-aug-1985";  // overwrites existing one
  printf("%s",(char*)NDa["dob"]);
  
  
以下是 NewDynamicArray 类的函数。
 void Insert(const int index,const Type& T); // 

此函数将值插入数组。如果索引已存在,则覆盖现有值。此插入函数接受 int 类型的索引。

 void Insert(char* index,const Type& T); 

此函数将值插入数组。如果索引已存在,则覆盖现有值。此插入函数接受 string (char*) 类型的索引。

 bool IsIndexExist(int index); 

此函数检查给定的索引是否已存在。此函数接受 int 类型的索引。

 bool IsIndexExist(char* index); 

此函数检查给定的索引是否已存在。此函数接受 int 类型的索引。

 Type& Get(const int index); 

此函数获取给定索引的值。此函数适用于 int 类型的索引。

 Type& Get(const char* index); 

此函数获取给定索引的值。此函数适用于 string 类型的索引。

 bool IsValueExist(Type value); 

此函数检查给定的值是否已存在。

 void RemoveByIndex(char* index);  

此函数通过字符串类型的索引删除值。

 void RemoveByIndex(int index); 

此函数通过 int 类型的索引删除值。

 void RemoveByValue(Type value); 

此函数通过输入值删除值。

 bool MoveNext(); 

此函数用于迭代链表,以便我们可以访问值。

void ReSetIterator();

此函数用于重置迭代器,以便迭代器可以指向第一个值。

这个类在很多方面都非常有用。

1) 可以创建任何类型的字符串或 int 索引。

2) 可以轻松灵活地检索值。

3) 用户还可以包含他们自己的函数。

4) 这是一个模板类,可以使用任何数据类型。


.

© . All rights reserved.