C++ STL笔记_stl 笔记-程序员宅基地

技术标签: 算法  c++  笔记  

https://blog.csdn.net/weixin_49486457/article/details/123439229?spm=1001.2014.3001.5506

#include<bits/stdc++.h>
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);

#define INF  0x3f3f3f3f; //无穷大 10^9
INT_MAX

1. 结构体

https://www.cnblogs.com/banluxinshou/p/11823158.html

  • C++的关键字struct是从C语言中的struct继承过来的,但是与C语言中要求struct只能包含成员变量不一样。C++中,struct类似于class,既可以包含成员变量,又可以包含成员函数。
  • 声明:
struct Student{
    
    char *name; //姓名
    int age; //年龄
    int school_id; //学号
};

Student xiaoming, jim; //C++允许省略struct,在Student前面可以不加struct。定义结构体Student类型的变量xiaoming,jim。
struct Student xiaoming, jim; //C风格的变量定义,在C++里面也没有问题,兼容。

  • 初始化:
    Student stu1 = {"James", 15, 20190101};
    这就定义了一个Student类型的变量stu1,并且以列表的形式为其中的变量提供了初始值。

  • 构造函数:

// 链表
struct ListNode
{
    
    double value;
    ListNode *next;
    //构造函数
    ListNode(double valuel, ListNode *nextl = nullptr)
    {
    
        value = value1;
        next = next1;
    }
};

ListNode *secondPtr = new ListNode(13.5);
ListNode *head = new ListNode(12.5, secondPtr);

C++中还可以使用构造函数来初始化结构体成员变量,这和初始化类class成员变量是相同的。
与类class的构造函数一样,结构体的构造函数必须是与结构体名称相同的公共成员函数,并且没有返回类型。因为默认情况下,所有结构体成员都是公开的,所以不需要使用关键字 public。
虽然结构体可以包含成员函数,但尽量不要这样做。尽量只把结构体当作数据类型,而在类class里面使用成员函数。

使用 class 时,类中的成员默认都是 private 属性的;而使用 struct 时,结构体中的成员默认都是 public 属性的。
class 继承默认是 private 继承,而 struct 继承默认是 public 继承(《C++继承与派生》一章会讲解继承)。
class 可以使用模板,而 struct 不能(《模板、字符串和异常》一章会讲解模板)。

2. auto 关键字

https://zhuanlan.zhihu.com/p/101432602

  • 早在C++98标准中就存在了auto关键字,那时的auto用于声明变量为自动变量,拥有自动的生命周期;但是该作用是多余的,变量默认拥有自动的生命周期。
int a = 10;      // 自动生命周期
auto int b = 20; // 自动生命周期
  • c++11 auto:
    auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型:
auto i =100;  // i 是 int 
auto p = new A();  // p 是 A* 
auto k = 34343LL;  // k 是 long long

auto的自动类型推断发生在编译期,所以使用auto并不会造成程序运行时效率的降低。

  • auto 变量必须在定义时初始化,这类似于const关键字

3. 万能头文件

#include<bits/stdc++.h>
// C++ includes used for precompiling -*- C++ -*-

// Copyright (C) 2003-2021 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

/** @file stdc++.h
 *  This is an implementation file for a precompiled header.
 */

// 17.4.1.2 Headers

// C
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cwchar>
#include <cwctype>

#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdalign>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cuchar>
#endif

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <codecvt>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif

#if __cplusplus >= 201402L
#include <shared_mutex>
#endif

#if __cplusplus >= 201703L
#include <any>
#include <charconv>
// #include <execution>
#include <filesystem>
#include <optional>
#include <memory_resource>
#include <string_view>
#include <variant>
#endif

#if __cplusplus > 201703L
#include <barrier>
#include <bit>
#include <compare>
#include <concepts>
#if __cpp_impl_coroutine
# include <coroutine>
#endif
#include <latch>
#include <numbers>
#include <ranges>
#include <span>
#include <stop_token>
#include <semaphore>
#include <source_location>
#include <syncstream>
#include <version>
#endif

4. 容器

vector

二维向量初始化为 n*n 的数组且所有值为0:

vector<vector<int>> vec(n, vector<int>(n,0));
vi.push_back(i)
vi.pop_back(i)
vi.size()
vi.clear()
vi.insert(vi.begin() + 2, -1); //将-1插入vi[2]的位置
vi.erase(vi.begin() + 3); //删除vi[3]
// 删除一个区间内的所有元素,erase(first, last), 即删除[first, last)内的所有元素,注意哦,不包括last

set

set翻译为集合,是一个内部自动有序且不含重复元素的容器,加入set之后可以实现自动排序。

#include<set>
set<typename> name;
set<int> a[100]; // a[0] ~ a[99] 中的每一个都是一个set容器。
s.insert(x) // 将x插入set容器中,并自动递增排序和去重
s.find(v) // 返回set中对应值为value的迭代器
s.erase(it) //it为所需要删除元素的迭代器
s.erase(value) //value为所需要删除元素的值
s.erase(first, last) //可以删除一个区间内的所有元素,其中first为所需要删除区间的起始迭代器,而last则为所需要删除区间的末尾迭代器的下一个地址,即为删除[first, last),
s.size()
s.clear()
int main()
{
    
  set<int> st;
  st.insert(3);//insert(x)将x插入set中
  st.insert(5);
  st.insert(2);
  st.insert(3);
 
  //注意,不支持it < st.end()的写法
  for (set<int>::iterator it = st.begin(); it != st.end(); it++)
  {
    
    printf("%d ", *it);//输出2 3 5
  }
  return 0;
}

queue

push()
pop()
front() // 访问队首
back()  // 访问队尾
empty() // true为空
size()

stack

push()
pop()
top()
empty()
size()

string

operator+= // 拼接
compare operator // 比较大小
length() / size()
insert()
erase()
clear()
substr()
find() // 失配返回-1
str.find(str2) // 当str2 是str 的子串时,返回其在str 中第一次出现的位置,如果str2 不是str 的子串,那么返回string::npos
replace()
str.replace(pos,len,str2) // 把str 从pos 号位开始、长度为len 的子串替换为上str2
str.replace(it1,it2,str2) // 把str 的迭代器[it1, it2)范围的子串替换为str2

pair

#include<utility>
//俩种方法初始化
pair<string,int> p("hello",1);
p = make_pair("hello",1);
p.first; //第一个元素 =hello
p.second; //第二个元素 = 1

// 嵌套(套娃)
vector< vector<pair<int, int> > >//与vector结合【再写个vector结合即可】
//套娃操作 用pair存储3个数据
 pair<int, pair<int, int>> p(1,{
    2,3});

当pair 结合 sort()函数使用的时候, pair 默认对first升序,当first相同时对second升序(从小到大)。

map

#include <map>
map<string,int> m = {
     "A", 10 };

insert(); //插入一个数,插入的数是一个pair
erase(); 
    //(1)输入是pair
    //(2)输入一个迭代器,删除这个迭代器
find(); //查找一个数
lower_bound(x); //返回大于等于x的最小的数的迭代器
upper_bound(x); //返回大于x的最小的数的迭代器

int main()
{
    
  	map<string,int>a;
  	a["abc"] = 1;//把字符串"abc" 映射为1
  	cout << a["abc"] << endl; //查找abc  程序输出 1
    return 0;
}

mp.insert(make_pair("heihei",5));

bitset

#include<bitset>
bitset<4> bs;  //无参构造,长度为4,默认每一位为0

bitset<8> b(12);  //长度为8,二进制保存,前面用0补充

string s = "100101"; //01串赋值
bitset<10> bs(s);  //长度为10,前面用0补充

/*  ~取反,&与,|与或,^异或
    >>,<<  移动
    ==,!=
    []   取0/1 */

count(); //返回1的个数
any(); //判断是否至少有一个1
none(); //判断是否全为0
set(); //把所有位置赋值为1
set(k,v); //将第k位变成v
reset(); //把所有位变成0
flip(); //把所有位取反,等价于~
flip(k); //把第k位取反

5. 一些算法

math.h

fabs(double x)  //绝对值
pow(double r, double p) // r的p次方
sqrt(double x) //算数平方根

排序 sort()

#include<algorithm>
int a[5] = {
    4,2,1,3,5};
vector<int> b(a,a+5);
sort(a,a+5);//搭配数组  从小到大排序
sort(b.begin(),b.end());

// 使用比较函数cmp 来“告诉”sort 何时要交换元素(让元素的大小比较关系反过来)
bool cmp(int a, int b)
{
    
  return a > b;//可以理解为当a>b时把a放在b前面
}
sort(a, a + 4, cmp);

最大公约数 __gcd()

#include<cstdio>
#include<algorithm>
using namespace std;
int n,m;
int main()
{
    
    scanf("%d %d",&n,&m);
    int k=__gcd(n,m);//最大公约数
    printf("%d ",k);
    printf("%d", n * m / k); //最小公倍数
    return 0;
}

最大最小值 max() min()

max(a,b);//返回最大值
min(a,b);//返回最小值

交换 swap()

swap(a,b);//交换a和b

二分查找 lower_bound()、upper_bound()

lower_bound() 用来获取集合中第一个不小于指定值的元素位置
upper_bound() 用来获取集合中第一个大于指定值的元素位置
左闭右开
numbers.end()不在数组内。
没找到时 返回可以插入的位置
指针 - 指针 = 两指针之间的元素个数

std::vector<int> numbers{
     1, 3, 5, 7, 9 };
std::vector<int>::iterator iterator;
iterator = std::lower_bound(numbers.begin(), numbers.end(), 3); 
// *iterator = 3
//数组下标l
int l = lower_bound(nums.begin(), nums.end(), target) - nums.begin();

倒置 reverse()

vector<int> v={
    1,2,3,4,5};
reverse(v.begin(),v.end());//v的值为5,4,3,2,1  倒置

查找 find()

//在a中的从a.begin()(包括它)到a.end()(不包括它)的元素中查找10,
//若存在返回其在向量中的位置
  find(a.begin(),a.end(),10);

删除 erase()

erase一共三种用法:
1.erase(pos,n);删除从下标pos开始的n个字符,比如erase(0,1)就是删除第一个字符2.erase(position);删除postion处的一个字符(position是一个string类型的迭代器)
3.erase(first,last) 删除从first到last之间的字符(first和last都是迭代器)

//从c中删除迭代器p指定的元素,p必须指向c中的一个真实元素,不能等于c.end()
c.erase(p)
//从c中删除迭代器对b和e所表示的范围中的元素,返回e
c.erase(b,e)

fill()

fill(a, a + 5, 133);//将a[0]~a[4]均赋值为133 

全排列 next_permutation()

将当前排列更改为全排列中的下一个排列。
如果当前排列已经是全排列中的最后一个排列(元素完全从大到小排列),函数返回 false 并将排列更改为全排列中的第一个排列(元素完全从小到大排列);否则,函数返回 true。

// 1 结合 数组
int a[] = {
    1, 2, 3, 4, 5};
    do{
    
      for(int i = 0; i < 5; i ++) cout << a[i] << " ";
      cout << endl;
    }while(next_permutation(a, a + 5));

// 2结合 vector
vector<int> a = {
    1, 2, 3, 4, 5};
    do{
    
      for(int i = 0; i < a.size(); i ++) cout << a[i] << " ";
      cout << endl;
    }while(next_permutation(a.begin(), a.end()));

6. 迭代器

要访问顺序容器和关联容器中的元素,需要通过“迭代器(iterator)”进行。迭代器是一个变量,相当于容器和操纵容器的算法之间的中介。迭代器可以指向容器中的某个元素,通过迭代器就可以读写它指向的元素。从这一点上看,迭代器和指针类似。

itr = container.begin();
itr++;
itr--;
*itr;
itr->...

// 常规遍历方式
std::vector<int> vec;
...
for (std::vector<int>::iterator itr = vec.begin(); itr != vec.end(); ++itr)
{
    
    // 需要对itr执行解引用!
    *irt
    ...
}

c++11增加了两个工具函数begin()/end(),支持对原生数组的迭代器访问,同时也支持对已有容器的访问。

int eles[10] = {
    ...};
for (auto itr = begin(eles); itr != end(eles); ++itr)
{
    
    ...
}

7. sprintf() 和 sscanf()

sprintf(str, "%d:%.2lf,%s", n, db, str2); // 将int 型变量n 、double 型变量db、char 型数组str2 按"%d:%lf,%s" 的格式写到字符数组str 中
sscanf(str, "%d:%lf,%s", &n, &db, str2); // 将字符数组str 中的内容按"%d:%lf,%s"的格式写到int  型变量n、double 型变量db、char型数组str2中
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_41058067/article/details/134819883

智能推荐

分布式光纤传感器的全球与中国市场2022-2028年:技术、参与者、趋势、市场规模及占有率研究报告_预计2026年中国分布式传感器市场规模有多大-程序员宅基地

文章浏览阅读3.2k次。本文研究全球与中国市场分布式光纤传感器的发展现状及未来发展趋势,分别从生产和消费的角度分析分布式光纤传感器的主要生产地区、主要消费地区以及主要的生产商。重点分析全球与中国市场的主要厂商产品特点、产品规格、不同规格产品的价格、产量、产值及全球和中国市场主要生产商的市场份额。主要生产商包括:FISO TechnologiesBrugg KabelSensor HighwayOmnisensAFL GlobalQinetiQ GroupLockheed MartinOSENSA Innovati_预计2026年中国分布式传感器市场规模有多大

07_08 常用组合逻辑电路结构——为IC设计的延时估计铺垫_基4布斯算法代码-程序员宅基地

文章浏览阅读1.1k次,点赞2次,收藏12次。常用组合逻辑电路结构——为IC设计的延时估计铺垫学习目的:估计模块间的delay,确保写的代码的timing 综合能给到多少HZ,以满足需求!_基4布斯算法代码

OpenAI Manager助手(基于SpringBoot和Vue)_chatgpt网页版-程序员宅基地

文章浏览阅读3.3k次,点赞3次,收藏5次。OpenAI Manager助手(基于SpringBoot和Vue)_chatgpt网页版

关于美国计算机奥赛USACO,你想知道的都在这_usaco可以多次提交吗-程序员宅基地

文章浏览阅读2.2k次。USACO自1992年举办,到目前为止已经举办了27届,目的是为了帮助美国信息学国家队选拔IOI的队员,目前逐渐发展为全球热门的线上赛事,成为美国大学申请条件下,含金量相当高的官方竞赛。USACO的比赛成绩可以助力计算机专业留学,越来越多的学生进入了康奈尔,麻省理工,普林斯顿,哈佛和耶鲁等大学,这些同学的共同点是他们都参加了美国计算机科学竞赛(USACO),并且取得过非常好的成绩。适合参赛人群USACO适合国内在读学生有意向申请美国大学的或者想锻炼自己编程能力的同学,高三学生也可以参加12月的第_usaco可以多次提交吗

MySQL存储过程和自定义函数_mysql自定义函数和存储过程-程序员宅基地

文章浏览阅读394次。1.1 存储程序1.2 创建存储过程1.3 创建自定义函数1.3.1 示例1.4 自定义函数和存储过程的区别1.5 变量的使用1.6 定义条件和处理程序1.6.1 定义条件1.6.1.1 示例1.6.2 定义处理程序1.6.2.1 示例1.7 光标的使用1.7.1 声明光标1.7.2 打开光标1.7.3 使用光标1.7.4 关闭光标1.8 流程控制的使用1.8.1 IF语句1.8.2 CASE语句1.8.3 LOOP语句1.8.4 LEAVE语句1.8.5 ITERATE语句1.8.6 REPEAT语句。_mysql自定义函数和存储过程

半导体基础知识与PN结_本征半导体电流为0-程序员宅基地

文章浏览阅读188次。半导体二极管——集成电路最小组成单元。_本征半导体电流为0

随便推点

【Unity3d Shader】水面和岩浆效果_unity 岩浆shader-程序员宅基地

文章浏览阅读2.8k次,点赞3次,收藏18次。游戏水面特效实现方式太多。咱们这边介绍的是一最简单的UV动画(无顶点位移),整个mesh由4个顶点构成。实现了水面效果(左图),不动代码稍微修改下参数和贴图可以实现岩浆效果(右图)。有要思路是1,uv按时间去做正弦波移动2,在1的基础上加个凹凸图混合uv3,在1、2的基础上加个水流方向4,加上对雾效的支持,如没必要请自行删除雾效代码(把包含fog的几行代码删除)S..._unity 岩浆shader

广义线性模型——Logistic回归模型(1)_广义线性回归模型-程序员宅基地

文章浏览阅读5k次。广义线性模型是线性模型的扩展,它通过连接函数建立响应变量的数学期望值与线性组合的预测变量之间的关系。广义线性模型拟合的形式为:其中g(μY)是条件均值的函数(称为连接函数)。另外,你可放松Y为正态分布的假设,改为Y 服从指数分布族中的一种分布即可。设定好连接函数和概率分布后,便可以通过最大似然估计的多次迭代推导出各参数值。在大部分情况下,线性模型就可以通过一系列连续型或类别型预测变量来预测正态分布的响应变量的工作。但是,有时候我们要进行非正态因变量的分析,例如:(1)类别型.._广义线性回归模型

HTML+CSS大作业 环境网页设计与实现(垃圾分类) web前端开发技术 web课程设计 网页规划与设计_垃圾分类网页设计目标怎么写-程序员宅基地

文章浏览阅读69次。环境保护、 保护地球、 校园环保、垃圾分类、绿色家园、等网站的设计与制作。 总结了一些学生网页制作的经验:一般的网页需要融入以下知识点:div+css布局、浮动、定位、高级css、表格、表单及验证、js轮播图、音频 视频 Flash的应用、ul li、下拉导航栏、鼠标划过效果等知识点,网页的风格主题也很全面:如爱好、风景、校园、美食、动漫、游戏、咖啡、音乐、家乡、电影、名人、商城以及个人主页等主题,学生、新手可参考下方页面的布局和设计和HTML源码(有用点赞△) 一套A+的网_垃圾分类网页设计目标怎么写

C# .Net 发布后,把dll全部放在一个文件夹中,让软件目录更整洁_.net dll 全局目录-程序员宅基地

文章浏览阅读614次,点赞7次,收藏11次。之前找到一个修改 exe 中 DLL地址 的方法, 不太好使,虽然能正确启动, 但无法改变 exe 的工作目录,这就影响了.Net 中很多获取 exe 执行目录来拼接的地址 ( 相对路径 ),比如 wwwroot 和 代码中相对目录还有一些复制到目录的普通文件 等等,它们的地址都会指向原来 exe 的目录, 而不是自定义的 “lib” 目录,根本原因就是没有修改 exe 的工作目录这次来搞一个启动程序,把 .net 的所有东西都放在一个文件夹,在文件夹同级的目录制作一个 exe._.net dll 全局目录

BRIEF特征点描述算法_breif description calculation 特征点-程序员宅基地

文章浏览阅读1.5k次。本文为转载,原博客地址:http://blog.csdn.net/hujingshuang/article/details/46910259简介 BRIEF是2010年的一篇名为《BRIEF:Binary Robust Independent Elementary Features》的文章中提出,BRIEF是对已检测到的特征点进行描述,它是一种二进制编码的描述子,摈弃了利用区域灰度..._breif description calculation 特征点

房屋租赁管理系统的设计和实现,SpringBoot计算机毕业设计论文_基于spring boot的房屋租赁系统论文-程序员宅基地

文章浏览阅读4.1k次,点赞21次,收藏79次。本文是《基于SpringBoot的房屋租赁管理系统》的配套原创说明文档,可以给应届毕业生提供格式撰写参考,也可以给开发类似系统的朋友们提供功能业务设计思路。_基于spring boot的房屋租赁系统论文