vector2.cpp

C++向量类使用示例
本文通过一个C++程序示例展示了如何使用STL中的向量类(vector)进行动态内存分配、添加元素、获取向量大小及容量等基本操作,并演示了如何预留存储空间(reserve)和调整向量大小(resize)。

  #ifdef __BCPLUSPLUS__
#include <iostream.h>
#include <vector.h>
#else
#include <iostream>
#include <vector>
#endif

using namespace std;
typedef vector<int> INTVECTOR;

void main(void)
 {
   // Dynamically allocated vector begins with 0 elements.
   INTVECTOR theVector;

   // Add one element to the end of the vector, an int with the value 42.
   theVector.push_back(42);

   // Show statistics about vector.
   cout << "theVector's size is: " << theVector.size() << endl;
   cout << "theVector's maximum size is: " << theVector.max_size()<< endl;
   cout << "theVector's capacity is: " << theVector.capacity() << endl;

   // Ensure there's room for at least 1000 elements.
   theVector.reserve(1000);
   cout << endl << "After reserving storage for 1000 elements:" << endl;
   cout << "theVector's size is: " << theVector.size() << endl;
   cout << "theVector's maximum size is: " << theVector.max_size()<< endl;
   cout << "theVector's capacity is: " << theVector.capacity() << endl;

   // Ensure there's room for at least 2000 elements.
   theVector.resize(2000);
   cout << endl << "After resizing storage to 2000 elements:" << endl;
   cout << "theVector's size is: " << theVector.size() << endl;
   cout << "theVector's maximum size is: " << theVector.max_size()<< endl;
   cout << "theVector's capacity is: " << theVector.capacity() << endl;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值