vector

//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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值