C++提供了使用抽象进行高效率编程的方式。标准库就是一个很好的例子:
标准库定义了许多容器类以及一系列泛型算法,是程序员可以更加简洁、抽象和有效地编写程序。
容器容纳特定类型对象的集合,
顺序容器:
它是将单一类型元素聚集起来成为容器,然后根据位置来存储和访问这些元素,这就是顺序容器,顺序容器的元素排列次序与元素值无关,而是由元素添加到容器里的次序决定。
标准库中定义了三种顺序容器类型:
vector;
list;
deque
标准库还提供了三种容器适配器(adaptor)如下:
stack;
queue;
priority_queue.
vector例子一:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
vector<int> vec1(10, -1);
vector<int> vecMyHouse(10); //define a known length vector.
vec = vec1;
int i;
cout << "Please input a integer:";
cin >> i;
vecMyHouse.resize(i);
for(i = 0; i < vecMyHouse.size(); i++)
{
vecMyHouse[i] = i;
}
for(i = 0; i < vecMyHouse.size(); i++)
{
cout << vecMyHouse[i] << endl;
}
// vec.clear();
vec.push_back(100);
for(i = 0; i < vec.size(); i++)
{
cout << vec[i] << endl;
}
cout << vecMyHouse.size() << endl;
system("pause");
return 0;
}
vector示例二:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int num;
string word;
vector<string> text;
cout << "Please input the number of element that we want to insert:";
cin >> num;
cout << "Please input the element that we should insert:" << endl;
while((cin >> word) && (--num))
{
text.push_back(word);
}
cout <<"First Method:\n";
cout << "Words read are:\n";
for(int i = 0; i < text.size(); i++)
{
cout << text[i] << endl;
}
cout << "Second Method" << endl;
cout << "Words read are:\n";
for(vector<string>::iterator it = text.begin(); it != text.end(); ++it)
{
cout << *it << endl;
}
system("pause");
return 0;
}