codeguru文章翻译(1)

来源:互联网 发布:全球云计算市场份额 编辑:程序博客网 时间:2024/06/05 07:31
 

原文

http://www.codeguru.com/Cpp/Cpp/cpp_mfc/arrays/article.php/c4071/

什么是std:vector数组?
    向量数组是标准命名空间的一部分(std:);它可以很容易的创建任何类型的动态数组。向量类是STL(标准模板库)中的一个模板类;也就是说我们可以用他创建任何数据类型和对象的数组在我们的程序中,这是个为你引导最大内存处理的类句柄。向量类为你处理大部分的内存管理。
在什么情况下可以应用向量数组?
   向量数组在动态存储数据的情况下应用最好。例如,一个数组在程序执行过程中会改变数组的长度。
你如何应用向量数组?
   在应用向量数组前,你要先引进<vector>这个头文件。在老版本的Microsoft Visual C++ (2002和以前的),你既可以用<vector>也可以用<vector.h>;在 Microsoft Visual C++7.1 (2003)中就没有了<vector.h>这个头文件了。
   接着,你就可以实际的来创建一个数组了。这里有一个声明整型数组的例子。
// VectorTest.cpp
//

// files to include
#include <stdio.h>      // standard input/output
#include <vector>       // stl vector header

using namespace std;    // saves us typing std:: before vector

void main()
{
  // create an array of integers
  vector<int> arNumbers;
}


注意,在声明整型数组的时候,先要指定任何我们要使用的类"vector",指出那是我们想要创建的数据类型。我们在尖括号内写进"int"指出这个是我们要创建的整型类型数组。当要创建模板类的时候,最重要的因素是为了添加附加消息在类里边;这个信息被写到尖括号内。接下来,我们就要简单的指定一个我们想要的数组名字(arNumbers)并且用分号作为结束语句。
 接下来,给这个数组加入元素,调用"push_bac"这个成员函数;这个主要是在数组的最后加上一个新的原来定义好的类型的元素(在这是"int")。这里有一个给数组加入四个元素的例子:
// same as in previous code sample above

void main()
{
  // create an array of integers
  vector<int> arNumbers;

  // add four elements to our array
  arNumbers.push_back(12);
  arNumbers.push_back(24);
  arNumbers.push_back(36);
  arNumbers.push_back(48);
}

然后就可以使用熟悉的简单的方法重新得到这些信息。下面这些代码写在上面的代码"arNumbers.push_back(48);"的下面。
  // get the total amount of elements within the array
  int nArraySize = (int)arNumbers.size();

  // display the total amount of elements on the screen
  printf("Total Elements: %d/n/n", nArraySize);

  // display the array's contents on the screen
  for(int i = 0; i < nArraySize; i++)
    printf("Value at position %d is %d/n", i, arNumbers[i]);
}
首先,我要找出向量数组中元素的总个数;只要调用 size()这个函数就可以了。这里我们要强制转换成整型;这是为了防止编译器给我们警告。接着添加了一行显示数组个数的代码。接着用一个循环来得到数组的各个元素。作为标准的动的数组,可以用'[' 和 ']'操作符来存取特定位置的元素。
使用向量数组迭代器

   向量类有它特定的迭代器可以用来存取数组中的信息;很多向量类成员函数都要求输出这些迭代器,有个使用迭代器的erase()函数。erase()函数用来删除数组中的一个或多个成员的。
  声明一个和向量数组一致的迭代器,你需要做下面这些事情:
   vector<int>::iterator NumIt
  迭代器基本上就是一个指针指向数组中所存储的数据的内存地址。为了存取引用的值你要使用*号。这里有个例子是在向量使数组中使用迭代器的。
  // VectorTest.cpp
//

// files to include
#include <stdio.h>      // standard input/output
#include <vector>       // stl vector header

using namespace std;    // saves us typing std:: before vector

void main()
{
  // create an array of integers
  vector<int> arNumbers;

  // add four elements to our array
  arNumbers.push_back(12);
  arNumbers.push_back(24);
  arNumbers.push_back(36);
  arNumbers.push_back(48);

  // get the total amount of elements within the array
  int nArraySize = (int)arNumbers.size();

  // display the total amount of elements on the screen
  printf("Total Elements: %d/n/n", nArraySize);

  // create a vector<int>::iterator and set the position to which
  // it points to the beginning of the vector array in memory
  vector<int>::iterator itNum = arNumbers.begin();

  // Now, we iterate through the array until the iterator exceeds
  // the end of the array. You will notice that in this for loop
  // I have left out the initialisation section; this is
  // because it has been done separatly before.
  for(; itNum < arNumbers.end(); itNum++)
    printf("Value at position %d is %d/n",
      (int)(itNum - arNumbers.begin()), *itNum);
}
   在这个环节,通过数组的起始与current iterator位置,计算每个元素的位置。因此基本上,array的起始点与当前的iterator间的距离,正好等于array的index值, 就像上面的例子。
   接着,我们可以通过删除数组的第二的扩展我们的知识(作完后我们就可以显示数组的内容以至我们可以看到数组的变化).

// VectorTest.cpp
//

// files to include
#include <stdio.h>      // standard input/output
#include <vector>       // stl vector header

using namespace std;    // saves us typing std:: before vector

void main()
{
  // create an array of integers
  vector<int> arNumbers;

  // add four elements to our array
  arNumbers.push_back(12);
  arNumbers.push_back(24);
  arNumbers.push_back(36);
  arNumbers.push_back(48);

  // remove the second element from the array, what we say
  // looks like element 1, but because we start counting from
  // 0 it is actually element 2 because 0 represents element 1
  vector<int>::iterator itRemove = arNumbers.begin() + 1;
  // now, actually remove this element from the array
  arNumbers.erase(itRemove);

  // get the total amount of elements within the array
  int nArraySize = (int)arNumbers.size();
  // display the total amount of elements on the screen
  printf("Total Elements: %d/n/n", nArraySize);

  // get an iterator to the start of the numbers array
  vector<int>::iterator itNum = arNumbers.begin();

  // display the arrays' contents
  for(; itNum < arNumbers.end(); itNum++)
    printf("Value at position %d is %d/n",
      (int)(itNum - arNumbers.begin()), *itNum);
}

/* Program's Output:
   ================

   Total Elements: 3

   Value at position 0 is 12
   Value at position 1 is 36
   Value at position 2 is 48
   Press any key to continue

*/

   也可以删除掉简单的通过开始迭代和结束迭代来删除所有范围的
值,例如下面:
arNumbers.erase(itStart, itEnd);
   清除掉所有的向量数组
  应用clear()成员函数可以清除掉所有的数组成员。知道的,数组是不是有包含指向动态创建的内存的点。例如,新的操作被使用,而没有释放掉,因此引起内存泄漏。所以,你必须要确定在调用clear()成员函数之前已经为每个元素调用了delete 操作。这里是一个例子:
// same as before

class CMyClass
{
public:
  CMyClass() {}
  CMyClass(int def_x, int def_y) : x(def_x), y(def_y) {}
  virtual ~CMyClass() {}

  // this classes member functions
  // ...

  // some data (i.e. x and y)...
  int x, y;
};

void main()
{
  // create an array of CMyClass object pointers
  vector<CMyClass*> arMyClass;

  // dynamically add some elements (use new operator)
  arMyClass.push_back(new CMyClass(2, 40));
  arMyClass.push_back(new CMyClass(4, 60));
  arMyClass.push_back(new CMyClass(6, 80));
  arMyClass.push_back(new CMyClass(8, 100));

  // remove the second element from the array
  vector<CMyClass*>::iterator itSecond = arMyClass.begin() + 1;
  delete *itSecond;             // free the memory
  arMyClass.erase(itSecond);    // remove from
                                // the array

  // retrieve the value stored within the first x and y variables
  vector<CMyClass*>::iterator itFirst = arMyClass.begin()/* + 0 */;
  printf("First Coordinate: (%d, %d)/n", (*itFirst)->x,
                                         (*itFirst)->y);

  // start from the beginning of the array
  vector<CMyClass*>::iterator itPos = arMyClass.begin();
  // clear all elements from the array
  for(; itPos < arMyClass.end(); itPos++)
    delete *itPos;    // free the element from memory
   // finally, clear all elements from the array
  arMyClass.clear();
}

有争论说(用新的操作符)动态的创建元素更加有效,因为迭代向量数组时,电脑只能迭代指针的大小(通常在两位到四位之间)并且不支持迭代大的对象。这对需要快速运行的软件是十分必要的,比如实时软件或者游戏。如果你没有动态的分配内存(比如使用NEW操作符),那么记住你不必释放内存(例如使用DELETE操作符)。 如果你仅仅简单的将数组向量的指针静态的存储到内存或者接下来将它清除,那么动态的释放内存将对你来说不成问题。

 

如果你需要用向量数组完成更大的任务,在向量数组中创建类的句柄是很好的方法,只是你想要在数组上完成的过程句柄。
  结论
  这片文章只是开始使用std::vector arrays的大概的介绍,在以后你将会发现所有的你使用的不同种类和技术。也有很多不同的有用的数组STL 函数等等。