std常用类型

std::getline

文档

std::reverse

文档

注意事项

  1. reverse()返回值为void,是对原序列进行修改

std::vector

文档

emplace 和 emplace_back

两者的区别仅为前者可以指定插入元素的位置,后者是直接插入到容器末尾

当调用push_backinsert成员函数时,是把元素类型的对象传递给它们,这些对象被拷贝到容器中(即需要调用一次拷贝构造函数)
但调用一个emplace系列函数时,则是将相应参数传递给元素类型的构造函数,直接构造出对象并插入到容器中,不需要调用拷贝构造函数
演示程序如下

#include <iostream>
#include <vector>

using namespace std;

class A {
    public:
    int x;

    A() {
        x = 0;
        cout << "默认构造执行" << endl;
    }
    A(int x) {
        this->x = x;
        cout << "带参构造执行" << endl;
    }
    A(const A &a) {
        this->x = a.x;
        cout << "拷贝构造执行" << endl;
    }
};

int main() {
    vector<A> vec;

    A a = A(1);
    vec.push_back(a);

    for (A &i : vec) cout << i.x << ' ';

    return 0;
}

执行结果:

#include <iostream>
#include <vector>

using namespace std;

class A {
    public:
    int x;

    A() {
        x = 0;
        cout << "默认构造执行" << endl;
    }
    A(int x) {
        this->x = x;
        cout << "带参构造执行" << endl;
    }
    A(const A &a) {
        this->x = a.x;
        cout << "拷贝构造执行" << endl;
    }
};

int main() {
    vector<A> vec;

    vec.emplace_back(2);

    for (A &i : vec) cout << i.x << ' ';

    return 0;
}

执行结果

emplace系列函数的核心在于调用插入元素的构造函数,因此传入的值要符合构造函数的要求

std::next_permutation

文档

注意事项

  1. 是按照字典序递增的顺序进行排列的,需要关注初始序列

std::function

文档

用法

类似C语言中的函数指针
目前使用过的用法

  1. vector中存放lambda表达式指明元素类型
auto op1 = [](int a, int b) -> int {return a + b;};
auto op2 = [](int a, int b) -> int {return a - b;};
auto op3 = [](int a, int b) -> int {return a ^ b;};
vector<function<int(int, int)>> ops = {op1, op2, op3};

一道例题,不使用lambdavector相结合,就需要写三段重复度很高的代码

std::nth_element

官方文档

第二个参数的nth是指下标,例如带入0表示寻找下标为0,第1小的数值

示例程序

#include <iostream>
#include <algorithm>

using namespace std;

int k; // 第k+1小的元素,下标为k
int a[5] = {6, 1, 5, 2, 7};

int main()
{
    cin >> k;

    for (int i = 0; i < 5; ++ i) cout << a[i] << ' '; cout << endl;

    nth_element(a, a + k, a + 5);

    for (int i = 0; i < 5; ++ i) cout << a[i] << ' '; cout << endl;

    printf("第%d小的数为%d,下标为%d\n", k + 1, a[k], k);

    return 0;
}

输出结果

posted @ 2021-01-11 10:21  0x7F  阅读(140)  评论(0编辑  收藏  举报