掌握C++标准库算法的实用技巧
1. 选择最具体的算法
在编写C++程序时,选择正确的算法至关重要。虽然 for_each 算法非常灵活,但它并不是最佳选择。更具体的算法,如 count 、 count_if 、 find 、 find_if 等,不仅能简化代码,还能提高性能。例如,如果你想计算一个向量中有多少个元素大于100,使用 count_if 比编写一个类传递给 for_each 更为直接和高效。
示例代码
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110};
int count = std::count_if(vec.begin(), vec.end(), [](int n) { return n > 100; });
std::cout << "Number of elements greater than 100: " << count << std::endl;
}
2. 在算法中使用函数
C++
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



