C++之vector用法

1.插入配对

std::vector<pair<int,int> > w;

w.push_back(make_pair<int,int>(f,s) );

cout <<w[i].first << " " << w[i].second <<endl;

2.元素去重

std::vector<int> all;

sort(all.begin(), all.end());
std::vector<int>::iterator nown = unique(all.begin(), all.end());
all.erase(nown,all.end());

3.排序

升序排序

sort(all.begin(), all.end());

自定义排序

bool compare(pair<string,int> a,pair<string,int> b)
{
if ( a.second>b.second){
return true;
}
if (a.second==b.second && strcmp(a.first.c_str(),b.first.c_str())<0){
return true;
}
return false;
}

sort(v.begin(),v.end(),compare);

4.内存释放

vector<your_type>().swap(your_vector);

vector< vector<int> >的样子也可以上面一句话进行内存释放。

5.元素翻转:

std::reverse(v.begin(), v.end());  

原文地址:https://www.cnblogs.com/huangshiyu13/p/5876351.html