首页
社区
课程
招聘
[分享]《探索现代化C++》泛读笔记摘要13
2022-9-22 08:40 3875

[分享]《探索现代化C++》泛读笔记摘要13

2022-9-22 08:40
3875

《探索现代化C++》泛读笔记摘要13

Chapter 4 C++库

容器

C++11

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <algorithm>
 
int main()
{
    using namespace std;
    vector<int> v = {3,4,7,9};
    auto it = find(v.begin(),v.end(),4);
    cout<<"After "<<*it<<" comes "<<*(it+1)<<'\n';
    auto it2= v.insert(it+1, 5); // insert value 5 at pos. 2
    v.erase(v.begin()); // delete entry at pos. 1
    cout ≪ "Size = " << v.size() << ", capacity = "
    << v.capacity() << '\n';
    v.shrink_to_fit(); // drop extra entries
    v.push_back(7);
    for (auto i : v)
        cout ≪ i ≪ ",";
    cout ≪ '\n';
}

C++11 emplace系列,如emplace_back,emplace_front。

1
2
3
vector<matrix> v;
v.push_back(matrix(3,7));
v.emplace_back(7,9);// 相比上面节省了拷贝或者移动构造的内存操作

常见容器vector,deque,list,forward_list,set,multiset,map,multimap,unordered_map( Hash Tables)

 

C++20 set 方法contains

1
2
3
4
set<int> s = {1,3,4,7,9};
for (int i= 0; i < 6; ++i)
    cout << i << "is" << (s.contains(i) ? "" : "n't")
    << " contained in s.\n";

算法

算法主要定义在<algorithm>中,以及用于数字计算的<numeric>。

 

非修改型序列操作

 

find

1
2
vector<int> seq = {3,4,7,9,2,5,7,8};
auto it = find(begin(seq),end(seq),7);

find_if

1
2
3
4
5
6
7
bool check(int i) { return i>4&&i<7;}
int main()
{
    list<int> seq={3,4,5,7,8,9,2,8};
    auto it = find_if(begin(seq),end(seq),check);
    cout << "The first value in range is " << *it << '\n';
}

C++11 充分利用Lambda

1
auto it = find_if(begin(seq),end(seq),[](int i){ return i>4&&i<7;}};

修改型序列操作

 

copy

1
2
3
vector<int> seq={3,4,7,9,2,5,7,8},v;
v.resize(seq.size());
copy(begin(seq),end(seq),begin(v));

unique函数用于移除序列中的重复项。

1
2
3
4
std::vector<int> seq= {3, 4, 7, 9, 2, 5, 7, 8, 3, 4, 3, 9};
sort(begin(seq), end(seq));
auto it= unique(begin(seq), end(seq));
resize(distance(begin(seq), it));

排序操作

1
2
vector<int> seq= {3, 4, 7, 9, 2, 5, 7, 8, 3, 4, 3, 9};
sort(begin(seq), end(seq), [](int x, int y){return x > y;});

数值操作

1
2
3
4
5
6
7
8
9
10
11
vector<float> v= {3.1, 4.2, 7, 9.3, 2, 5, 7, 8, 3, 4},
w(10), x(10), y(10);
iota(begin(w), end(w), 12.1);
partial_sum(begin (v), end(v), begin(x));
adjacent_difference(begin(v), end(v), begin(y));
float alpha= inner_product(begin(w), end(w), begin(v), 0.0f);
float sum_w= accumulate(begin(w), end(w), 0.0f),
product_w= accumulate(begin(w), end(w), 1.0f,
[](float x, float y){
return x*y;
});

算法复杂性总结

 

$O(1)$:swap,iter_swap

 

$O(\log(n))$: lower_bound, upper_bound, equal_range, binary_search, push_heap, pop_heap

 

$O(n\log(n))$: inplace_merge, stable_partition, 所有的排序算法

 

$O(n^2)$: find_end, find_first_of, search, search_n

 

$O(n)$: 其他算法


[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课

收藏
点赞0
打赏
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回