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

智能推荐

使用nginx解决浏览器跨域问题_nginx不停的xhr-程序员宅基地

文章浏览阅读1k次。通过使用ajax方法跨域请求是浏览器所不允许的,浏览器出于安全考虑是禁止的。警告信息如下:不过jQuery对跨域问题也有解决方案,使用jsonp的方式解决,方法如下:$.ajax({ async:false, url: 'http://www.mysite.com/demo.do', // 跨域URL ty..._nginx不停的xhr

在 Oracle 中配置 extproc 以访问 ST_Geometry-程序员宅基地

文章浏览阅读2k次。关于在 Oracle 中配置 extproc 以访问 ST_Geometry,也就是我们所说的 使用空间SQL 的方法,官方文档链接如下。http://desktop.arcgis.com/zh-cn/arcmap/latest/manage-data/gdbs-in-oracle/configure-oracle-extproc.htm其实简单总结一下,主要就分为以下几个步骤。..._extproc

Linux C++ gbk转为utf-8_linux c++ gbk->utf8-程序员宅基地

文章浏览阅读1.5w次。linux下没有上面的两个函数,需要使用函数 mbstowcs和wcstombsmbstowcs将多字节编码转换为宽字节编码wcstombs将宽字节编码转换为多字节编码这两个函数,转换过程中受到系统编码类型的影响,需要通过设置来设定转换前和转换后的编码类型。通过函数setlocale进行系统编码的设置。linux下输入命名locale -a查看系统支持的编码_linux c++ gbk->utf8

IMP-00009: 导出文件异常结束-程序员宅基地

文章浏览阅读750次。今天准备从生产库向测试库进行数据导入,结果在imp导入的时候遇到“ IMP-00009:导出文件异常结束” 错误,google一下,发现可能有如下原因导致imp的数据太大,没有写buffer和commit两个数据库字符集不同从低版本exp的dmp文件,向高版本imp导出的dmp文件出错传输dmp文件时,文件损坏解决办法:imp时指定..._imp-00009导出文件异常结束

python程序员需要深入掌握的技能_Python用数据说明程序员需要掌握的技能-程序员宅基地

文章浏览阅读143次。当下是一个大数据的时代,各个行业都离不开数据的支持。因此,网络爬虫就应运而生。网络爬虫当下最为火热的是Python,Python开发爬虫相对简单,而且功能库相当完善,力压众多开发语言。本次教程我们爬取前程无忧的招聘信息来分析Python程序员需要掌握那些编程技术。首先在谷歌浏览器打开前程无忧的首页,按F12打开浏览器的开发者工具。浏览器开发者工具是用于捕捉网站的请求信息,通过分析请求信息可以了解请..._初级python程序员能力要求

Spring @Service生成bean名称的规则(当类的名字是以两个或以上的大写字母开头的话,bean的名字会与类名保持一致)_@service beanname-程序员宅基地

文章浏览阅读7.6k次,点赞2次,收藏6次。@Service标注的bean,类名:ABDemoService查看源码后发现,原来是经过一个特殊处理:当类的名字是以两个或以上的大写字母开头的话,bean的名字会与类名保持一致public class AnnotationBeanNameGenerator implements BeanNameGenerator { private static final String C..._@service beanname

随便推点

二叉树的各种创建方法_二叉树的建立-程序员宅基地

文章浏览阅读6.9w次,点赞73次,收藏463次。1.前序创建#include&lt;stdio.h&gt;#include&lt;string.h&gt;#include&lt;stdlib.h&gt;#include&lt;malloc.h&gt;#include&lt;iostream&gt;#include&lt;stack&gt;#include&lt;queue&gt;using namespace std;typed_二叉树的建立

解决asp.net导出excel时中文文件名乱码_asp.net utf8 导出中文字符乱码-程序员宅基地

文章浏览阅读7.1k次。在Asp.net上使用Excel导出功能,如果文件名出现中文,便会以乱码视之。 解决方法: fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);_asp.net utf8 导出中文字符乱码

笔记-编译原理-实验一-词法分析器设计_对pl/0作以下修改扩充。增加单词-程序员宅基地

文章浏览阅读2.1k次,点赞4次,收藏23次。第一次实验 词法分析实验报告设计思想词法分析的主要任务是根据文法的词汇表以及对应约定的编码进行一定的识别,找出文件中所有的合法的单词,并给出一定的信息作为最后的结果,用于后续语法分析程序的使用;本实验针对 PL/0 语言 的文法、词汇表编写一个词法分析程序,对于每个单词根据词汇表输出: (单词种类, 单词的值) 二元对。词汇表:种别编码单词符号助记符0beginb..._对pl/0作以下修改扩充。增加单词

android adb shell 权限,android adb shell权限被拒绝-程序员宅基地

文章浏览阅读773次。我在使用adb.exe时遇到了麻烦.我想使用与bash相同的adb.exe shell提示符,所以我决定更改默认的bash二进制文件(当然二进制文件是交叉编译的,一切都很完美)更改bash二进制文件遵循以下顺序> adb remount> adb push bash / system / bin /> adb shell> cd / system / bin> chm..._adb shell mv 权限

投影仪-相机标定_相机-投影仪标定-程序员宅基地

文章浏览阅读6.8k次,点赞12次,收藏125次。1. 单目相机标定引言相机标定已经研究多年,标定的算法可以分为基于摄影测量的标定和自标定。其中,应用最为广泛的还是张正友标定法。这是一种简单灵活、高鲁棒性、低成本的相机标定算法。仅需要一台相机和一块平面标定板构建相机标定系统,在标定过程中,相机拍摄多个角度下(至少两个角度,推荐10~20个角度)的标定板图像(相机和标定板都可以移动),即可对相机的内外参数进行标定。下面介绍张氏标定法(以下也这么称呼)的原理。原理相机模型和单应矩阵相机标定,就是对相机的内外参数进行计算的过程,从而得到物体到图像的投影_相机-投影仪标定

Wayland架构、渲染、硬件支持-程序员宅基地

文章浏览阅读2.2k次。文章目录Wayland 架构Wayland 渲染Wayland的 硬件支持简 述: 翻译一篇关于和 wayland 有关的技术文章, 其英文标题为Wayland Architecture .Wayland 架构若是想要更好的理解 Wayland 架构及其与 X (X11 or X Window System) 结构;一种很好的方法是将事件从输入设备就开始跟踪, 查看期间所有的屏幕上出现的变化。这就是我们现在对 X 的理解。 内核是从一个输入设备中获取一个事件,并通过 evdev 输入_wayland

推荐文章

热门文章

相关标签