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

智能推荐

while循环&CPU占用率高问题深入分析与解决方案_main函数使用while(1)循环cpu占用99-程序员宅基地

文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。​​​​​​while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99

【无标题】jetbrains idea shift f6不生效_idea shift +f6快捷键不生效-程序员宅基地

文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效

node.js学习笔记之Node中的核心模块_node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是-程序员宅基地

文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是

数学建模【SPSS 下载-安装、方差分析与回归分析的SPSS实现(软件概述、方差分析、回归分析)】_化工数学模型数据回归软件-程序员宅基地

文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件

利用hutool实现邮件发送功能_hutool发送邮件-程序员宅基地

文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件

docker安装elasticsearch,elasticsearch-head,kibana,ik分词器_docker安装kibana连接elasticsearch并且elasticsearch有密码-程序员宅基地

文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码

随便推点

Python 攻克移动开发失败!_beeware-程序员宅基地

文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware

Swift4.0_Timer 的基本使用_swift timer 暂停-程序员宅基地

文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停

元素三大等待-程序员宅基地

文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待

Java软件工程师职位分析_java岗位分析-程序员宅基地

文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析

Java:Unreachable code的解决方法_java unreachable code-程序员宅基地

文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code

标签data-*自定义属性值和根据data属性值查找对应标签_如何根据data-*属性获取对应的标签对象-程序员宅基地

文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象

推荐文章

热门文章

相关标签