您的位置:首页 > 其它

使用STL的vector容器类

2016-04-02 15:03 316 查看
范例程序:

#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
const int Size = 5;
int i, SizeF, SizeC;
float A[Size] = { 1.5, 2.9, 3.8, 4.2, 5.7 };
char B[Size] = { 'b', 'a', 'i', 'r', 'w' };

//定义vector对象
vector<float> Vf(A, A + Size);
vector<char> Vc(B, B + Size);
SizeF = Vf.size();
SizeC = Vc.size();
//定义ostream对象
ostream_iterator<float> IntOut(cout, " ");
ostream_iterator<char> CharOut(cout, " ");
cout << showpoint << setprecision(4);
cout << "\n---------------测试vector<float>---------------" << endl;
cout << "\nVf为:" << endl;
//vector对象输出
for (i = 0; i < SizeF;i++)
{
cout << Vf[i] << "";
}
//设置特定元素
Vf.at(2) = 9.9;
cout << endl;
cout << "在执行设置1之后,Vf变为:" << endl;
//vector对象输出
copy(Vf.begin(), Vf.end(), IntOut);
cout << endl;
Vf[3] = 2.8;
cout << "在执行设置2之后,Vf变为:" << endl;
copy(Vf.begin(), Vf.end(), IntOut);
cout << endl;
//插入额外的元素
Vf.insert(Vf.begin() + 3, 1.2);
cout << "在执行完插入元素后,Vf变为:" << endl;
copy(Vf.begin(), Vf.end(), IntOut);
cout << endl;
//将对象中的元素依大小顺序排序
sort(Vf.begin(), Vf.end());
cout << "排序后Vf变为:" << endl;
copy(Vf.begin(), Vf.end(), IntOut);
cout << endl;
//重排
random_shuffle(Vf.begin(), Vf.end());
cout << "重排后Vf变为:" << endl;
//对象输出
copy(Vf.begin(), Vf.end(),IntOut);
cout << endl;
cout << "\n---------------测试vector<char>---------------" << endl;
cout << "\nVc为:" << endl;
//Vector对象的输出
for (i = 0; i < SizeC;i++)
{
cout << Vc[i] << " ";
}
cout << endl;
//改变特定元素的值
Vc.at(2) = 'h';
cout << "在执行设置1之后,Vc变为:" << endl;
copy(Vc.begin(), Vc.end(), CharOut);
cout << endl;
Vc[3] = 'G';
cout << "在执行设置2之后,Vc变为:" << endl;
copy(Vc.begin(), Vc.end(), CharOut);
cout << endl;
//插入元素
Vc.insert(Vc.begin() + 3, 'p');
cout << "在执行完插入元素后,Vc变为:" << endl;
copy(Vc.begin(), Vc.end(), CharOut);
cout << endl;
//输出
sort(Vc.begin(), Vc.end());
cout << "排序后Vf变为:" << endl;
copy(Vc.begin(), Vc.end(), CharOut);
cout << endl;
//重排
random_shuffle(Vc.begin(), Vc.end());
cout << "重排后Vc变为:" << endl;
copy(Vc.begin(), Vc.end(), CharOut);
cout << endl;
return 0;
}

程序执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: