C++中的vector

来源:互联网 发布:nginx 修改80端口 编辑:程序博客网 时间:2024/06/08 04:32
在使用string时,我们可以向string对象中输入数据而不关心需要多少存储空间。但如果把某一行读入到一个string对象,由于整个文件事先不知道有多少行。   解决这个问题需要某种自动扩展的存放设施。于是可以采用vector,参考代码如下:
#include <cstdlib> //include "system()"#include <iostream>#include <fstream>#include <direct.h>#include <string>#include <vector>using namespace std;int main(int argc, char *argv[]){    vector<string> v;    ifstream in("Scopy.cpp");    ofstream out("Scopy2.cpp");    cout<<"\n将一个程序打印到屏幕上"<<endl;    cout<<"/*****************************************/"<<endl;    //system("Hello");    string line;    while(getline(in,line)){           v.push_back(line);         }     //打印部分        for(int i=0;i<v.size();i++)      cout<<i<<": "<<v[i]<<endl;         system("PAUSE");    return EXIT_SUCCESS;}

在c++中,vector是一个十分有用的容器,下面对这个容器做一下总结。

1 基本操作

(1)头文件vector.

(2)创建vector对象,”vector vec”;

(3)尾部插入数字:vec.push_back(a);

(4)使用下标访问元素,cout<

#include<stdio.h>#include<algorithm>#include<vector>#include<iostream>using namespace std;typedef struct rect{    int id;    int length;    int width;  //对于向量元素是结构体的,可在结构体内部定义比较函数,下面按照id,length,width升序排序。  bool operator< (const rect &a)  const    {        if(id!=a.id)            return id<a.id;        else        {            if(length!=a.length)                return length<a.length;            else                return width<a.width;        }    }}Rect;int main(){    vector<Rect> vec;    Rect rect;    rect.id=1;    rect.length=2;    rect.width=3;    vec.push_back(rect);    vector<Rect>::iterator it=vec.begin();    cout<<(*it).id<<' '<<(*it).length<<' '<<(*it).width<<endl;    return 0;}

3 算法

(1) 使用reverse将元素翻转:需要头文件#include

reverse(vec.begin(),vec.end());将元素翻转(在vector中,如果一个函数中需要两个迭代器,

一般后一个都不包含.)

(2)使用sort排序:需要头文件#include,

sort(vec.begin(),vec.end());(默认是按升序排列,即从小到大).

可以通过重写排序比较函数按照降序比较,如下:

定义排序比较函数:

bool Comp(const int &a,const int &b)
{
return a>b;
}
调用时:sort(vec.begin(),vec.end(),Comp),这样就降序排序。

0 0