背景知识
- vector<int>还是vector<int*>
在使用STL容器(比如map、list、vector等)的时候,是用放一个对象还是放一个对象指针,即是用vector<int>>还是vector<int*>,这里的vector可以换成其他的容器,int可以换成其他基本类型,也可以自定义的数据结构或类。 备注:若push进去错误的类型,编译时会报错,详见4
1、定义vector
int类型指针
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
void main()
{
vector <int*> mVector;
}
struct类型指针(object对象类型与此相同)
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
typedef struct
{
int number;
bool sex;
char name[220];
}student;
void main()
{
vector <student*> mVector;
}
2、下标索引遍历vector,释放内存
以int指针类型为例
#include <vector>
using namespace std;
typedef struct
{
int number;
bool sex;
char name[220];
}student;
void main()
{
vector <int*> mVector;
for(int i=0;i<5;i++)
{
int *p = new int(i);
mVector.push_back(p);
}
int *oa;
for (int i=0;i<mVector.size();i++)
{
oa = mVector[i];
int *temp=mVector[i];
cout<<temp<<endl<<*temp<<endl;
delete temp;
temp = NULL;
}
cout<<endl<<oa<<endl<<*oa<<endl;
return;
}
输出
019F4F40
0
019F4FC0
1
019F4F80
2
019F5008
3
019F5050
4
019F5050
-17891602
3、使用迭代器遍历vector,释放内存
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
typedef struct
{
int number;
bool sex;
char name[220];
}student;
void main()
{
vector <int*> mVector;
for(int i=0;i<5;i++)
{
int *p = new int(i);
mVector.push_back(p);
}
std::vector<int*>::iterator iter;
for (iter=mVector.begin();iter!=mVector.end();iter++)
{
cout<<*iter<<endl<<*(*iter)<<endl;
delete *iter;
*iter = NULL;
}
return;
}
输出
01394F40
0
01394FC0
1
01394F80
2
01395008
3
01395050
4
4、把错误的类型放入vector时会报错
比如,我们定义的mVector存放的是int指针,
vector <int*> mVector;
当我们把指针指向的数据(int类型数据)放入mVector,则会报错;
mVector.push_back(*p);
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
void main()
{
vector <int*> mVector;
for(int i=0;i<5;i++)
{
int *p = new int(i);
mVector.push_back(*p);
}
return;
}
报错如下
Error 1 error C2664: ‘std::vector<_Ty>::push_back’ : cannot convert parameter 1 from ‘int’ to 'int *const &
参考:
1.c++中vector<int>和vector<int*>的用法区别 2.C++中new int()与new int[]区别 3.C++ new和delete(C++动态分配和释放内存)
|