STL常用函数(转自TiWalker)

1.map中查找指定键值
   map.find()


2.set中查找指定键值
    set<int>s;
    s.find()
    s.count()
  注:count()函数统计某一键值出现的次数,因此可以查看set中是否出现某一键值。


3.sort()函数
sort(vect.begin(), vect.end());//此时相当于调用
sort(vect.begin(), vect.end(), less<int>() );

sort 中的其他比较函数
equal_to 相等
not_equal_to 不相等
less 小于
greater 大于
less_equal 小于等于
greater_equal 大于等于
       上述例子中系统 自己为sort提供了less仿函数。在STL中还提供了其他仿函 数,以下是仿函数列表: 不能直接写入仿函数的名字,而是要写其重载的()函数: less<int>();

       当你的容器中元 素时一些标准类型(int float char)或者string时,你可以直 接使用这些函数模板。但如果你时自己定义的类型或者你需要按照其他方式排序,你可以有两种方法来达到效果:一种是自己写比较函数。另一种是重载类型的'<'操作赋。


       局部排序其实是为了减少不必要的操作而提供的排序方式。
其函数原型为:
void partial_sort(RandomAccessIterator first, RandomAccessIterator middle,RandomAccessIterator last);
void partial_sort(RandomAccessIterator first,RandomAccessIterator middle,RandomAccessIterator last, StrictWeakOrdering comp);


例如:班上有1000个学生,我想知道分数最低的5名是哪些人。
partial_sort(vect.begin(),vect.begin()+5,vect.end(),less<student>());

Effective STL对排序函数的总结:
若需对vector, string, deque, 或array容器进行全排序,你可选择sort或stable_sort;

若只需对vector, string, deque, 或array容器中取得top n的元素,部分排序partial_sort是首选.

若对于vector, string, deque, 或array容器,你需要找到第n个位置的元素或者你需要得到top n且不关系top n中的内部 顺序,nth_element是最 理想的;

若你需要从标准序列容器或者array中把满足某个条件 或者不满足某个条件的元素分开,你最好使用partition或stable_partition;

若使用的list容器,你可以直接使用partition和stable_partition算法,你可以使用list::sort代替sort和stable_sort排序。


4.find()函数
find( v1.begin(), v1.end(), num_to_find );
       利用返回布尔值的谓词判断pred,检查迭代器区间[first,last)(闭开区间)上的每一个元素,如果迭代器i满足pred(*i)=true,表示找到元素并返回迭代值i(找到的第一个符合条件的元素);未找到元素,返回末位置last。函数原型:find_if(v.begin(),v.end(),divby5);

bool IsOdd (int i) {
  return ((i%2)==1);
}

std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);


5.count()函数
list<int> l;
count(l.begin(),l.end(),value)
count_if(l.begin(),l.end(),pred)。谓词pred含义同find_if中的谓词。


6.search()函数
       search算法函数在一个序列中搜索与另一序列匹配的子序列。参数分别为一个序列的开始位置,结束位置和另一个序列的开始,结束位置。

vector<int>::iterator ilocation;
ilocation=search(v1.begin(),v1.end(),v2.begin(),v2.end());

search_n算法函数搜索序列中是否有一系列元素值均为某个给定值的子序列。函数原型:search_n(v.begin(),v.end(),3,8),在v中找到3个连续的元素8。


最后一个子序列搜索find_end
函数原型find_end(v1.begin(),v1.end(),v2.begin(),v2.end());在V1中要求的位置查找V2中要求的序列。


7.copy()函数
copy(v.begin(),v.end(),l.begin());将v中的元素复制到l中。

transform(v.begin(),v.end(),l.begin(),square);也是复制,但是要按某种方案复制。

int square(int x)
{
     return x*x;
}


8.replace()
replace算法将指定元素值替换为新值。

replace(v.begin(),v.end(),25,100);将元素范围中的25替换为100

函数原型:replace_if(v.begin(),v.end(),odd,100);

bool odd(int x)
{
    return x%2;
}


9.fill_n()函数
函数原型fill_n(v.begin(),5,-1);向从v.begin开始的后面5个位置跳入-1
generate_n(v.begin(),5,rand);向从v.begin开始的后面5个位置随机填写数据。


10.remove_if()
返回值相当于移除满足条件的元素后形成的新向量的end()值。
函数原型:remove_if(v.begin(),v.end(),even);


11.unique
剔除连续重复元素unique
unique(v.begin(),v.end());

猜你喜欢

转载自blog.csdn.net/C20191904/article/details/72582043