//vector的使用
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v;
cout<<"enter a list of positive numbers./n"
<<"place a negative number at the end./n";
int next;
cin>>next;
while(next>0)
{
v.push_back(next);
//在向量的一个索引位置首次添加一个元素是,
//通常使用成员函数push_back;
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()返回unsigned int类型
cout<<v[i]<<" ";
//可以使用v[i]来更改编号为i的元素的值,但是不能使用v[i]来初始化编号为i的元素
//只能用它更改一个已经赋值的元素。
cout<<endl;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> INTVECTOR;
const ARRAY_SIZE = 8;
void main()
{
// Dynamically allocated vector begins with 0 elements.
INTVECTOR theVector;
// Intialize the array to contain the members [100, 200, 300, 400]
for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
theVector.push_back((cEachItem + 1) * 100);
cout << "First element: " << theVector.front() << endl;
cout << "Last element: " << theVector.back() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
for (unsigned int i=0;i<theVector.size();i++)
cout<<theVector[i]<<endl;
// Delete the last element of the vector. Remember that the vector
// is 0-based, so theVector.end() actually points 1 element beyond
// the end.
theVector.erase(theVector.end() -1);
cout << endl << "After erasing last element, new last element is: "
<< theVector.back() << endl;
// Delete the first element of the vector.
theVector.erase(theVector.begin());
cout << "After erasing first element, new first element is: "
<< theVector.front() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
for (i=0;i<theVector.size();i++)
cout<<theVector[i]<<endl;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v(10);
int i;
for(i=0;i<v.size();i++)
v[i]=i;
vector<int> copy;
copy = v;//向量赋值具有良好的行为,生成一个独立的副本
//这取决于向量的基类型(这里是int)
v[0]=42;
for(i=0;i<copy.size();i++)
cout<<copy[i]<<endl;
cout<<endl;
return 0;
}