这是当前std_lib_facilities.h(来自his website)的摘录:
...
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
using size_type = typename std::vector<T>::size_type;
using std::vector<T>::vector; // inheriting constructor
T& operator[](unsigned int i) // rather than return at(i);
{
if (i<0||this->size()<=i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
const T& operator[](unsigned int i) const
{
if (i<0||this->size()<=i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
};
// disgusting macro hack to get a range checked vector:
#define vector Vector
...
我对此有几个问题:
operator[]
的参数通常为size_type
(通常size_t
},所以为什么要更改为unsigned int
?i
定义为unsigned int
,因此比较i < 0
始终为false,不是吗?如果这是真的,为什么要进行比较?在使用gcc启用-Wconversion
并使用其书中的代码后,我注意到了这一点:
#include "../std_lib_facilities.h"
int main(int argc, char** argv) {
vector<double>temps;
for (double temp; cin >> temp; )
temps.push_back(temp);
// compute mean temperature:
double sum = 0;
for (auto x : temps) sum += x;
cout << "Average temperature: " << sum / temps.size() << '\n';
// compute median temperature:
sort(begin(temps), end(temps));
cout << "Median temperature: " << temps[temps.size()/2] << '\n';
keep_window_open();
return 0;
}
由于temps.size()
返回size_type
,temps[temps.size()/2]
发生了转化警告/错误。