现代C++学习

C/C++基础复习

关于new

  • new一个数组:int *dp = new int[nums.size()-1];

  • new一个二维数组,常用的有两种方式,指针数组或模拟二维数组,推荐后者(管理方便)

    1
    2
    int* arr = new int[rows * cols];
    memset(arr, 0, sizeof(int) * rows * cols); // 初始化所有元素为0

C++11核心特性[^1]

语言特性

库功能特性

  • 并发支持(<thread>
  • 智能指针

STL

容器

Algorithms

字符串

  • 查找

    1
    2
    3
    size_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
    7
    string 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,简化路径)

    • 第一种方法是采用stringstreamistringstream

      1
      2
      3
      4
      5
      istringstream ss(path);
      string token;
      while (getline(ss, token, '/')) {
      /* ... */
      }
    • 第二种方法是采用ranges库(C++20引入)

      1
      2
      3
      4
      for (auto&& part : path | ranges::views::split('/')) {
      string s(part.begin(), part.end());
      /* ... */
      }
      • ranges库:管道(挖坑 后补)

      • 注意,上文中的&&右值引用(rvalue reference),用于绑定右值(临时对象),避免不必要的拷贝,提高效率。ranges::views::split('/') 产生一个 范围视图(view),part 可能是 string_view 之类的对象,它不应该被复制。

参考资料

https://zh.cppreference.com/w/cpp/11


现代C++学习
https://mfqwq.cn/2025/03/06/learn-cpp/
作者
murphyqwq
发布于
2025年3月6日
许可协议