现代C++学习
C/C++基础复习
关于new
- 
new一个数组:
int *dp = new int[nums.size()-1]; - 
new一个二维数组,常用的有两种方式,指针数组或模拟二维数组,推荐后者(管理方便)
1
2int* arr = new int[rows * cols];
memset(arr, 0, sizeof(int) * rows * cols); // 初始化所有元素为0 
C++11核心特性[^1]
语言特性
- 
【★】
autoanddecltype - defaulted and deleted functions
 finalandoverride- trailing return type
 - 【★】rvalue references
 - move constructors and move assignment operators
 - scoped enums
 constexprand literal types- 【★】list initialization
 - delegating and inherited constructors
 - brace-or-equal initializers
 nullptrlong long- char16_t and char32_t
 - type aliases
 - variadic templates
 - generalized (non-trivial) unions
 - generalized PODs (trivial types and standard-layout types)
 - Unicode string literals
 - user-defined literals
 - attributes
 - 【★】lambda expressions
- lambda表达式,实现了闭包(能够捕获作用域中的变量的匿名函数对象)。
 
 noexceptspecifier andnoexceptoperatoralignofandalignas- multithreaded memory model
 - thread-local storage
 - GC interface (removed in C++23)
 - 【★】range-for (based on Boost library)
 static_assert(based on Boost library)
库功能特性
- 并发支持(
<thread>) - 智能指针
 
STL
容器
Algorithms
字符串
- 
查找
1
2
3size_t find(const std::string& str, size_t pos = 0) const;
size_t find(const char* s, size_t pos = 0) const;
size_t find(char c, size_t pos = 0) const;- 查找失败时,返回 
std::string::npos(通常是size_t的最大值,即-1)。 
 - 查找失败时,返回 
 - 
截取子串
1
2
3
4
5
6
7string substr(size_t pos = 0, size_t len = npos) const;
int main() {
string str = "Hello, World!";
string sub = str.substr(7, 5); // "World"
cout << sub << endl;
return 0;
} - 
分割(例:Leetcode 71,简化路径)
- 
第一种方法是采用
stringstream(istringstream)1
2
3
4
5istringstream ss(path);
string token;
while (getline(ss, token, '/')) {
/* ... */
} - 
第二种方法是采用ranges库(C++20引入)
1
2
3
4for (auto&& part : path | ranges::views::split('/')) {
string s(part.begin(), part.end());
/* ... */
}- 
ranges库:管道(挖坑 后补)
 - 
注意,上文中的
&&是 右值引用(rvalue reference),用于绑定右值(临时对象),避免不必要的拷贝,提高效率。ranges::views::split('/')产生一个 范围视图(view),part可能是string_view之类的对象,它不应该被复制。 
 - 
 
 - 
 
参考资料
现代C++学习
      https://mfqwq.cn/2025/03/06/learn-cpp/