使用向量
// String.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include<iostream>#include<vector>int main(int argc, char* argv[]){using namespace std;vector<int> v;cout<<"Enter a list of positive number.\n"<<"Place a negitive number at the end.\n";int next;cin>>next;while(next > 0){v.push_back(next);cout<<next<<" added. ";cout<<"v.size() = "<<v.size ()<<endl;cin>>next;}cout<<"You entered :\n";for(unsigned int i = 0; i < v.size () ; i ++) ///v.size()成员函数获取向量的长度{cout<<v[i]<<" ";}cout<<endl;return 0;}
一些说明:向量的用法类似于数组,但向量的长度不是固定的。
使用向量需要包含以下语句:
#include<vector>
using namespace std;
声明向量的两种方式:
(1) vector<int> v;
(2)向量的一个构造函数可获取一个整数参数,并初始化由参数指定的位置数目。
如:vector<int > v(10);
那么前10个元素会初始化为0,而v.size()会返回10!然后可以让i从0变化到9,
for(unsigned int i = 0; i < 10 ; i++)
v[i] = i ;
在i大于等于10的情况下,要想设置编号为i的元素,需要使用Push_back()。