#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
/*
vector是数组的一种类表示方式,提供了自动内存管理,随机访问,可以动态的改变长度。
在尾部添加和删除元素的时间是固定的,在头部和中间添加和删除元素的时间的线性的。
与vector类似的还有deque,deque支持从开始端插入数据:push_front
*/
using std::vector;
using std::string;
using std::cout;
using std::endl;
void test(double d);
bool compare(double a, double b);
int main()
{
//指定长度
vector<int> vec(5);
vec[0] = 9;
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << ",";
}
cout << endl ;
//不指定长度
vector<double> scores;
//尾部添加元素
scores.push_back(11.11);
scores.push_back(22.22);
scores.push_back(33.33);
scores.push_back(0.33);
//迭代器循环
vector<double>::iterator iter = scores.begin();
for (;iter != scores.end();iter++)
{
cout << *iter << ",";
}
cout << endl ;
//删除尾部元素
scores.pop_back();
//简单循环方式1
for_each(scores.begin(), scores.end(),test); //algorithm头文件中
//排序
sort(scores.begin(), scores.end(), compare); //algorithm头文件中
cout << endl;
//简单循环方式2
for (double d : scores) {
cout << d << ",";
}
cout << endl;
//是否空
cout << "scores.empty():" << scores.empty() << endl;
//插入元素
scores.insert(scores.end(), 5, 44.4);//在尾部添加5个44.4
for_each(scores.begin(), scores.end(), test);
cout << endl;
return 0;
}
void test(double d) {
cout << d << ",";
}
bool compare(double a, double b) {
if (a > b)
{
return true;
}
return false;
}
输出结果:
9,0,0,0,0,
11.11,22.22,33.33,0.33,
11.11,22.22,33.33,
33.33,22.22,11.11,
scores.empty():0
33.33,22.22,11.11,44.4,44.4,44.4,44.4,44.4,