您的位置:首页 > 其它

vector使用

2010-02-26 14:08 120 查看
// vectorTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class TestEle
{
public:
TestEle(int nCnt, const char* szName) : m_nCnt(nCnt)
{
strncpy(m_szName, szName, 64);
}
/*
如果禁掉拷贝构造函数,添加元素将导致编译器错误
private:
TestEle(const TestEle& oth)
{
}
*/
/*
private:
TestEle& operator=(const TestEle& oth)
{
}
*/
private:
int m_nCnt;
char m_szName[64];
};
/*
对元素的要求:
1.对于用户自定义类型,必须拷贝构造函数(在分配的原始内存中构建对象::new(ptr)(obj),可查看allocator的内部实现)
2.支持赋值运算
3.最好不要放auto_ptr
一个编译器可以检查出某些违背标准库规则的情况,但另一些则检查不出来,它们或许会导致无法预期的行为
*/
int _tmain(int argc, _TCHAR* argv[])
{
vector<TestEle> vecTestEle;
vecTestEle.reserve(1000);	//预分配1000个元素的原始内存空间

cout << vecTestEle.size() << endl;	//0
cout << vecTestEle.capacity() << endl;	//1000
for (int i = 0; i < 1000; i++)
{
vecTestEle.push_back(TestEle(i, "liyong"));
}

cout << vecTestEle.size() << endl;	//1000
cout << vecTestEle.capacity() << endl;	//1000
vecTestEle.push_back(TestEle(1000, "liyong"));	//空间用完,再分配500
cout << vecTestEle.size() << endl;	//1001
cout << vecTestEle.capacity() << endl;	//1500
vector<TestEle> vecTestEle2;
vecTestEle2.reserve(500);
for (int j = 0; j < 500; j++)
{
vecTestEle2.push_back(TestEle(j, "cc"));
}
//容器之间元素复制
vector<TestEle> vecTestEle3(vecTestEle2.begin(), vecTestEle2.end());
vector<TestEle> vecTestEle4(vecTestEle3);
//容器一开始就构造n个对象
//vector<TestEle> vecTestEle5(1000);	//这里需要元素有默认构造函数, TestEle类不具备
vector<TestEle> vecTestEle6(1000, TestEle(101, "bb"));
//容器之间的赋值
vector<TestEle> vecTestEle7 = vecTestEle6;	//After a call to this member function, both the vector object and vector x will have the same size and compare equal to each other.

//几个重要成员函数的使用
vecTestEle6.resize(500, TestEle(102, "dd"));	//小于实际元素数量,删除多余的元素
vecTestEle6.resize(1000, TestEle(103, "ee"));	//大于实际元素数量,增加到指定的个数,以第二个参数为对象蓝本
vecTestEle6.assign(100, TestEle(104, "ff"));	//先删除所有原有的元素,然后加入100个TestEle(104, “ff”)
vecTestEle6.assign(vecTestEle2.begin(), vecTestEle2.end());	//同上,只不过输入变为迭代器对

vecTestEle6.insert(vecTestEle6.begin(), TestEle(1011, "gg"));	//在迭代器指定的位置插入一个元素
vecTestEle6.insert(vecTestEle6.begin(), vecTestEle3.begin(), vecTestEle3.end());	//插入迭代器对范围的元素
vecTestEle6.insert(vecTestEle6.begin(), 20, TestEle(1020, "ii"));	//插入n个相同的元素
vecTestEle6.erase(vecTestEle6.begin());	//删除迭代器指定位置的元素
vecTestEle6.erase(vecTestEle6.begin(), vecTestEle6.end() - 10);//删除迭代器指定范围的元素
//上述操作会导致迭代器失效,对于元素删除,添加操作时刻注意迭代器失效问题
//返回被最后删除元素的下一个位置,如果是最后一个元素,则是同end()

//交换两个容器的元素
vector<TestEle> vec1(10, TestEle(111, "abc"));
vector<TestEle> vec2(20, TestEle(222, "def"));
vec1.swap(vec2);

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