⚠️ 泛型组件也一样,别多拷
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)⚠️ 这一节的计数**只数标准强制的那几种**(传值、传 const&、push_back 一个左值 / 一个 move 过的),**不数返回值和临时对象**——那些各编译器省略得不一样。所有 vector 都**先 reserve**,扩容搬运不掺进来。一份泛型代码套三种容器,一次拷贝都没有:
#include <iostream>
#include <list>
#include <set>
#include <vector>
/* 一份代码,套三种容器 —— 它只要求"能从头一步步走到尾" */
template <typename It>
int count_above(It first, It last, int line) {
int n = 0;
for (It it = first; it != last; ++it) if (*it > line) n++;
return n;
}
int main() {
std::vector<int> v{5, 3, 9, 1, 7};
std::list<int> l{5, 3, 9, 1, 7};
std::set<int> s{5, 3, 9, 1, 7};
std::cout << count_above(v.begin(), v.end(), 4) << "/"
<< count_above(l.begin(), l.end(), 4) << "/"
<< count_above(s.begin(), s.end(), 4) << "\n";
return 0;
}
全部评论