1.vector 的数据的存入和输出:
#include<stdio.h>
#include<vector>
#include <iostream>
using namespace std;
void main()
{
int i = 0;
vector<int> v;
for( i = 0; i < 10; i++ )
{
v.push_back( i );//把元素一个一个存入到vector中
}
for( i = 0; i < v.size(); i++ )//v.size() 表示vector存入元素的个数
{
cout << v[ i ] << " "; //把每个元素显示出来
}
cont << endl;
}
注:你也可以用v.begin()和v.end() 来得到vector开始的和结束的元素地址的指针位置。你也可以这样做:
vector<int>::iterator iter;
for( iter = v.begin(); iter != v.end(); iter++ )
{
cout << *iter << endl;
}
2. 对于二维vector的定义。
1)定义一个10个vector元素,并对每个vector符值1-10。
#include<stdio.h>
#include<vector>
#include <iostream>
using namespace std;
void main()
{
int i = 0, j = 0;
//定义一个二维的动态数组,有10行,每一行是一个用一个vector存储这一行的数据。
所以每一行的长度是可以变化的。之所以用到vector<int>(0)是对vector初始化,否则不能对vector存入元素。
vector< vector<int> > Array( 10, vector<int>(0) );
for( j = 0; j < 10; j++ )
{
for ( i = 0; i < 9; i++ )
{
Array[ j ].push_back( i );
}
}
for( j = 0; j < 10; j++ )
{
for( i = 0; i < Array[ j ].size(); i++ )
{
cout << Array[ j ][ i ] << " ";
}
cout<< endl;
}
}
2)定义一个行列都是变化的数组。
#include<stdio.h>
#include<vector>
#include <iostream>
using namespace std;
void main()
{
int i = 0, j = 0;
vector< vector<int> > Array;
vector< int > line;
for( j = 0; j < 10; j++ )
{
Array.push_back( line );//要对每一个vector初始化,否则不能存入元素。
for ( i = 0; i < 9; i++ )
{
Array[ j ].push_back( i );
}
}
for( j = 0; j < 10; j++ )
{
for( i = 0; i < Array[ j ].size(); i++ )
{
cout << Array[ j ][ i ] << " ";
}
cout<< endl;
}
}
-----zz自 http://blog.csdn.net/tjh666/archive/2007/05/11/1604119.aspx
下面是我找的一些常用vector类的成员函数~
push_back()插入一个元素
pop_back() 可以弹出最后ch一个元素
erase(iterator it)可以删除指定位置的元素
size()求vector中的已存的元素个数
clear()可以清空vector中的元素
Vector constructors |
create vectors and initialize them with some data |
Vector operators |
compare, assign, and access elements of a vector |
assign |
assign elements to a vector |
at |
returns an element at a specific location |
back |
returns a reference to last element of a vector |
begin |
returns an iterator to the beginning of the vector |
capacity |
returns the number of elements that the vector can hold |
clear |
removes all elements from the vector |
empty |
true if the vector has no elements |
end |
returns an iterator just past the last element of a vector |
erase |
removes elements from a vector |
front |
returns a reference to the first element of a vector |
insert |
inserts elements into the vector |
max_size |
returns the maximum number of elements that the vector can hold |
pop_back |
removes the last element of a vector |
push_back |
add an element to the end of the vector |
rbegin |
returns a reverse_iterator to the end of the vector |
rend |
returns a reverse_iterator to the beginning of the vector |
reserve |
sets the minimum capacity of the vector |
resize |
change the size of the vector |
size |
returns the number of items in the vector |
swap |
swap the contents of this vector with another |
posted on 2007-07-18 14:00
yoyouhappy 阅读(4504)
评论(0) 编辑 收藏 引用 所属分类:
学习笔记 、
转载