您的位置:首页 > 其它

14 STL中容器vector

2017-11-18 21:27 387 查看

1、概述

vector容器是容器类和算法系统的一部分,支持面向容器的操作,如排序,插入,重新排序,搜索,数据转移等。

2、容器vector的结构



注意点:vector容器是线性结构,容器的大小不是固定的,可向容器的一端扩展数据。

3、测试代码头文件

#include <stdexcept>
#include <string>
#include <cstdlib> //abort()
#include <cstdio> //_snprintf()
#include <iostream>
#include <ctime>
#include <algorithm> //sort()
#include <vector>
using namespace std;
using std::string;
namespace hh02
{
void test_vector(long& value)
{
cout << "test_vector().......... \n";
vector<string> c;
char buf[10];
clock_t timeStart = clock();
srand((unsigned)time(NULL));
for (long i = 0; i < value; ++i){
try
{
_snprintf(buf, 10, "%d", rand());
c.push_back(string(buf));
}
catch (exception* p)
{
cout << "i = " << i << " " << p->what() << endl;
abort();
}
}
cout << "milli-seconds : " << (clock() - timeStart) << endl; //耗时
cout << "vector.max_size()= " << c.max_size() << endl;	//vector最大容量
cout << "vector.size()= " << c.size() << endl; //vecter的大小
cout << "vector.front()= " << c.front() << endl; //vector的首值
cout << "vector.back()= " << c.back() << endl;	//vector的尾值
cout << "vector.data()= " << c.data() << endl; //vector的地址
cout << "vector.capacity()= " << c.capacity() << endl << endl; //vector的当前容量

string target = get_a_target_string();

timeStart = clock();
auto pItem = ::find(c.begin(), c.end(), target); //全局的循序查找方法,返回iterate
cout << "std::find(), milli-seconds : " << (clock() - timeStart) << endl;
if (pItem != c.end())
cout << "found, " << *pItem << endl << endl;
else
cout << "not found! " << endl << endl;

timeStart = clock();
::sort(c.begin(), c.end()); //全局排序的方法
cout << "sort(), milli-seconds : " << (clock() - timeStart) << endl;

timeStart = clock();
string* pItem1 = (string*)::bsearch(&target, (c.data()), //c提供的查找方法
c.size(), sizeof(string), compareStrings);
cout << "bsearch(), milli-seconds : " << (clock() - timeStart) << endl;
if (pItem1 != NULL)
cout << "found, " << *pItem1 << endl << endl;
else
cout << "not found! " << endl << endl;
}
}
解析:

a、该代码为头文件中的主要部分,要想顺利运行程序,要添加其余部分函数在13篇中的辅助函数所示;

b、声明了一个vector容器,存放的是string类型数据vector<string> c;

c、使用push_back()方法向容器尾部添加数据;

d、用cout方法打印输出容器的参数,如代码中大小size(),容量capacity(),首值front(),尾值back();

e、先使用全局循序查找方法find()搜索目标值,打印搜索时间;

f、再使用全局的排序方法sort()对vector进行排序,然后使用c的查找方法bsearch()进行查找;

4、主程序及输出

#include "vector.h" //辅助函数

int _tmain(int argc, _TCHAR* argv[])
{
long value = 250000L;
hh02::test_vector(value);
return 0;
}
/*输出:
test_vector()..........
milli-seconds : 2483
vector.max_size()= 153391689
vector.size()= 250000
vector.front()= 22680
vector.back()= 10119
vector.data()= 03981040
vector.capacity()= 311073

target (0~32767): 1200
std::find(), milli-seconds : 14
found, 1200

sort(), milli-seconds : 10284
bsearch(), milli-seconds : 0
found, 1200
*/
解析:

a、传入250000数值,vector的大小为250000;

b、从输出结果看,vector
926c
的capacity()值大于size()值,是因为当往容器vevtor中增加数值时,是先双倍的增加空间;


c、使用全局sort()的时间非常慢,但是sort()后的查找时间非常快,接近0;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: