Below you will find pages that utilize the taxonomy term “C++”
March 14, 2025
c++语法
万能开头:
#include<bits/stdc++.h>
using namespace std;
在 C++ 中,using namespace std;
指令允许用户使用 std 命名空间中的所有标识符,而无需在它们前面加上 std::
。
标准输入输出
标准输入是 cin
, cin
用 >>
运算符把输入传给变量。
标准输出是 cout
,用 <<
运算符把需要打印的内容传递给 cout
,endl
是换行符。
#include <bits/stdc++.h>
int a;
cin >> a; // 从输入读取一个整数
// 输出a
std::cout << a << std::endl;
// 可以串联输出
// 输出:Hello, World!
std::cout << "Hello" << ", " << "World!" << std::endl;
string s = "abc";
a = 10;
// 输出:abc 10
std::cout << s << " " << a << std::endl;
March 14, 2025
算法 - C++STL常用容器
插入函数总结
方法 | 适用容器 | 作用 | 性能特性 |
---|---|---|---|
push | queue 、stack 、priority_queue | 添加元素到容器末尾或顶部 | 适用于特定容器,性能与容器实现相关 |
push_back | vector 、deque 、list | 添加元素到容器末尾 | 需要拷贝或移动元素 |
emplace | set 、map 、unordered_set 等 | 在容器中直接构造元素 | 避免不必要的拷贝或移动 |
emplace_back | vector 、deque 、list | 在容器末尾直接构造元素 | 避免不必要的拷贝或移动 |
insert | 大多数容器 | 将元素插入到容器的指定位置 | 需要拷贝或移动元素 |
February 13, 2025
unordered_map
unordered_map | unordered_set | |
---|---|---|
存储内容 | 键值对 (std::pair<const Key, T> ) | 仅存储键 (Key ) |
是否允许重复键 | 键唯一(重复键会覆盖) | 键唯一(重复插入无效) |
主要用途 | 快速通过键查找值 | 快速判断键是否存在 |
典型操作 | map[key] = value 、map.find(key) | set.insert(key) 、set.count(key) |
内存占用 | 更高(需存储键和值) | 更低(仅存储键) |
1. 创建 unordered_map
对象
#include <unordered_map>
#include <string>
int main() {
// 默认构造函数
std::unordered_map<std::string, int> map1;
// 初始化列表构造函数
std::unordered_map<std::string, int> map2 = {{"apple", 1}, {"banana", 2}};
// 拷贝构造函数
std::unordered_map<std::string, int> map3(map2);
return 0;
}
2. 插入
insert
插入一个键值对
map1.insert({"orange", 3}); map1.insert(std::make_pair("grape", 4));
operator[]
通过键插入或访问值。如果键不存在,会插入一个默认值。
map1["apple"] = 10; // 插入或修改 int value = map1["apple"]; // 访问
3. 访问元素
at
访问指定键的值,如果键不存在会抛出
std::out_of_range
异常。int value = map1.at("apple");
operator[]
访问或插入指定键的值。
int value = map1["apple"];