vector动态创建数组

来源:互联网 发布:薪酬数据分析报告 编辑:程序博客网 时间:2024/06/02 16:20

相应的头文件: #include <vector>

vector定义向量对象:

vector<int> ivec;                //定义向量对象 ivecvector<int> ivec1(ivec);    // 定义向量对象ivec1,并用ivec初始化vector<int> ivec2(n,1);      //定义向量ivec2,包含了n个值为1的元素vector<int> ivec3(n);         // 定义向量对象ivec3,包含了n个值为0的元素

示例程序:

#include <iostream>#include <vector>using namespace std;int main(){    vector<int>::iterator it;    vector<int> ivec(4,6); // 使用4个整形数值6初始化    for (int i = 0; i < ivec.size(); ++i)        cout<<ivec[i];    cout<<endl;    ivec.push_back(7); //尾部添加元素7    ivec.insert(ivec.begin(),5); // ivec头部添加元素5,注意该操作复杂度为O(n)    for (it = ivec.begin(); it != ivec.end(); ++it)//!!!!        cout<<*it;   //使用迭代器访问每个元素  这里避免了直接操作越界的情况    cout<<endl;    return 0;}

运行结果:

6666566667

定义迭代器的方法:

vector<int>::iterator it;it = ivec.begin();      //迭代器指向ivec的第一个元素it = ivec.end();         //迭代器指向ivec的最后一个元素

利用vector定义一个二维数组

vector<vector<int> > ivv;//注意:vector<int后两个">"之间要有空格!否则会被认为是重载">>"

利用vector动态创建二维数组

#include <vector>#include <iomanip>using namespace std;int main(){ int i,j,x,y; cout << "input value for x,y:"; cin>>x>>y; //vector<int后两个">"之间要有空格!否则会被认为是重载">>"。 vector<vector<int> > vecInt(x, vector<int>(y));//定义一个二维vector for (i = 0; i < x; i++)  for (j = 0; j < y; j++)   vecInt[i][j] = i+j; for (i = 0; i < x; i++) {  for (j = 0; j < y; j++)    //打印数组值和地址    cout<<setw(5)<<vecInt[i][j]<<":"<<setw(9)<<&vecInt[i][j];  cout<<endl; } return 0;}

运行结果:

input value for x,y:4 2    0: 0x330fc8    1: 0x330fcc    1: 0x330fd8    2: 0x330fdc    2: 0x330fe8    3: 0x330fec    3: 0x330ff8    4: 0x330ffc
0 0
原创粉丝点击