Last active
November 2, 2015 01:13
-
-
Save LincolnBurrows/522d25a4a43913e1a48a to your computer and use it in GitHub Desktop.
C++ STL vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
vector<数据类型> name; | |
example: | |
vector<int> vec; | |
尾部插入数字:vec.push_back(int a); | |
使用下标访问元素 std::cout<<vec[0]<<std::endl; 下标从0开始 | |
使用迭代器访问元素 | |
vector <int> ::iterator it; | |
for(it=vec.begin();it!=vec.end();++it) | |
{ | |
std::cout<<*it<<std::endl; | |
} | |
插入元素:vec.insert(vec.begin()+i, a);在i+1个元素前面插入a | |
删除元素:vec.erase(vec.begin()+2);删除第三个元素 | |
vec.erase(vec.begin()+i,vec.begin()+j);删除区间[i,j-1] | |
向量大小:vec.size() | |
清空:vec.clear() | |
example: | |
#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; | |
} | |
算法: | |
头文件:#include<algorithm> | |
使用reverse将元素翻转: | |
reverse(vec.begin(),vec.end()); | |
使用sort排序: | |
sort(vec.begin(),vec.end()); //默认按升序排列,从小到大 | |
可以通过重写排序比较函数按照降序排列: | |
bool comp (const int &a,const int &b) | |
{ | |
return a>b; | |
} | |
调用:sort(vec.begin(),vec.end(),comp);降序排列 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment