您的位置:首页 > 其它

STL的一些技巧函数使用

2018-01-10 18:55 281 查看

1.emplace() 函数和 emplace_back() 函数

C++11的STL中新增加了emplace() 函数和 emplace_back() 函数,用来实现insert() 函数和 push_back() 函数的功能。

如果容器中的元素是对象:

emplace() 函数的功能是可以直接将参数传给对象的构造函数,在容器中构造出一个对象,从而实现 0 拷贝。(底层机制是调用placement new即布局new运算符来实现的)。

假设类MyClass 有构造函数 MyClass(T1 val1,T2 val2);

那么container.emplace(container.end() ,val1, val2) 可以直接在容器的末尾构造出一个对象,如果用container.insert(container.end() ,MyClass(val1,val2)) 会先构造一个对象,然后拷贝到容器的末尾。

同样的,emplace_back() 和 push_back() 的差别类似。

如果是一个已有的对象 MyClass obj;container.emplace(..., obj) 和 container.emplace_back(obj)的效率差不多。

2.stable_sort()方法 与 sort()方法;partition()方法和 stable_partition()方法

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

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

int main()
{
vector<int> v;
for(int i = 0; i < 10; i++)
v.push_back(i);

cout<<"The original elements in the vector are: "<<endl;
vector<int>::iterator it, bound;

for(it = v.begin(); it != v.end(); it++)
cout<<*it<<" ";
cout<<endl;

cout<<"First use the function partition() to separate all elements into 2 groups without ordering: "<<endl;
//use partition to separate the vector into 2 parts...
bound = partition(v.begin(), v.end(), IsOdd);

cout << "All odd elements in the vector are:" <<endl;
for(it = v.begin(); it != bound; it++)
cout<<*it<<" ";
cout<<endl;

cout<< "All even elements in the vector are:" <<endl;
for(it = bound; it != v.end(); it++)
cout<<*it<<" ";
cout<<endl;

v.clear();
for(int i = 0; i < 10; i++)
v.push_back(i);

cout<<"Secondly use the function stable_partition() to separate all elements into 2 groups with ordering: "<<endl;
//use stable_partition to separate the vector into 2 parts...
bound = stable_partition(v.begin(), v.end(), IsOdd);

cout << "All odd elements in the vector are:" <<endl;
for(it = v.begin(); it != bound; it++)
cout<<*it<<" ";
cout<<endl;

cout<< "All even elements in the vector are:" <<endl;
for(it = bound; it != v.end(); it++)
cout<<*it<<" ";
cout<<endl;

return 0;
}


The original elements in the vector are:
0 1 2 3 4 5 6 7 8 9
First use the function partition() to separate all elements into 2 groups without ordering:
All odd elements in the vector are:
9 1 7 3 5
All even elements in the vector are:
4 6 2 8 0
Secondly use the function stable_partition() to separate all elements into 2 groups with ordering:
All odd elements in the vector are:
1 3 5 7 9
All even elements in the vector are:
0 2 4 6 8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: