6.25小学期CPP基础语法记录:反转、字符串查找、稳定sort
reverse函数在 C 中reverse是一个非常常用的 STL 算法用于就地反转序列中的元素顺序。它定义在algorithm头文件中。 函数定义template class BidirectionalIterator void reverse(BidirectionalIterator first, BidirectionalIterator last);参数说明first反转范围的起始迭代器包含。last反转范围的终止迭代器不包含。返回值无void它是就地修改直接在原容器上改变顺序。迭代器要求必须是双向迭代器如vector,list,deque都支持forward_list不支持。✅ 示例1. 反转vectorint#include iostream #include vector #include algorithm // for reverse int main() { std::vectorint v {1, 2, 3, 4, 5}; std::reverse(v.begin(), v.end()); for (int i : v) std::cout i ; return 0; }输出5 4 3 2 12. 反转string也支持因为string::iterator是双向的#include iostream #include string #include algorithm int main() { std::string s abcdef; std::reverse(s.begin(), s.end()); std::cout s; // 输出: fedcba return 0; }3. 局部反转cpp复制编辑std::vectorint v {10, 20, 30, 40, 50, 60}; // 只反转中间部分 [1, 4) std::reverse(v.begin() 1, v.begin() 4); // - 10, 40, 30, 20, 50, 60 reverse 的底层实现原理使用的是双向迭代器通过交换front和back元素来实现反转。伪代码while (first ! last first ! --last) { swap(*first, *last); first; } 时间复杂度与空间复杂度时间复杂度O(n)空间复杂度O(1)原地操作不使用额外空间 举一反三std::reverse_copy(first, last, dest)把反转结果复制到另一个位置不影响原数据。std::vectorint v {1,2,3,4,5}; std::vectorint res(5); std::reverse_copy(v.begin(), v.end(), res.begin()); // res 5,4,3,2,1如果你想自己实现一个reverse函数可以练习写模板函数操作双向迭代器。 string::find函数C 中的string::find是处理字符串查找的核心函数常用于查找某个子串或字符第一次出现的位置。下面我们详细分析它的用法、变体、返回值再拓展介绍其他常见的字符串查找函数比如rfind、find_first_of、find_last_of、find_first_not_of等。 一、string::find基本用法size_t find(const string str, size_t pos 0) const; size_t find(const char* s, size_t pos 0) const; size_t find(const char* s, size_t pos, size_t n) const; size_t find(char c, size_t pos 0) const;✅ 参数说明str/s/c: 要查找的目标字符串/字符。pos: 从原字符串的哪个位置开始查找默认为 0。✅ 返回值成功返回目标第一次出现的位置类型为size_t。失败返回string::npos一个极大的无符号整数表示未找到。 示例一查找子串std::string s hello world; size_t pos s.find(world); // 返回 6 示例二查找字符std::string s abcabc; size_t pos s.find(b); // 返回 1第一个 b 的位置 示例三未找到std::string s hello; size_t pos s.find(abc); if (pos std::string::npos) std::cout not found; 示例四从指定位置开始查找std::string s abcabc; size_t pos s.find(b, 2); // 返回 4跳过前面的 b 二、其他查找方法汇总1️⃣rfind从右往左找返回最后一次出现的位置std::string s abcabc; size_t pos s.rfind(b); // 返回 42️⃣find_first_of查找任一字符第一次出现的位置std::string s hello world; size_t pos s.find_first_of(aeiou); // 返回 1‘e’是第一个元音3️⃣find_last_of查找任一字符最后一次出现的位置std::string s abcabc; size_t pos s.find_last_of(ab); // 返回 4‘b’在位置4最后出现4️⃣find_first_not_of找第一个不是指定字符集的字符std::string s aaaabc; size_t pos s.find_first_not_of(a); // 返回 4‘b’不是 ‘a’5️⃣find_last_not_of找最后一个不是指定字符集的字符std::string s abcddd; size_t pos s.find_last_not_of(d); // 返回 2‘c’不是 ‘d’ 实战对比与举一反三函数名含义查找方向典型用途find第一次出现左→右查找特定子串或字符rfind最后一次出现右→左查找最后一个位置find_first_of第一次出现任一左→右查找多个候选字符之一find_last_of最后一次出现任一右→左find_first_not_of第一个不是指定字符左