C++ 为什么Stroustrup';s std_lib_facilities.h是否使用std::vector修改运算符[]的输入大小?
以下是当前std_lib_facilities.h(来源)的摘录:C++ 为什么Stroustrup';s std_lib_facilities.h是否使用std::vector修改运算符[]的输入大小?,c++,C++,以下是当前std_lib_facilities.h(来源)的摘录: 既然temps.size()返回一个size\u类型那么temps[temps.size()/2]就会出现转换警告/错误你为什么不亲自问他呢?毕竟,我们能做的就是猜测,不是吗?我想这是猜测,但我认为他有一个很好的理由这样做,而且更熟悉C++的人可以解释为什么。我假设它是未签名的INT/CUT>,因为他的学生将达不到40亿个元素。我还认为他检查
既然
temps.size()
返回一个size\u类型
那么temps[temps.size()/2]
就会出现转换警告/错误你为什么不亲自问他呢?毕竟,我们能做的就是猜测,不是吗?我想这是猜测,但我认为他有一个很好的理由这样做,而且更熟悉C++的人可以解释为什么。我假设它是<代码>未签名的INT/CUT>,因为他的学生将达不到40亿个元素。我还认为他检查<0是出于他可能有的习惯。我用他书中的代码更新了这个问题,当使用gcc的-Wconversion
标志时,会发出警告。这似乎是初学者想要的东西,不是吗?索引并不总是简单的常量,在计算中使用集合的大小似乎相当合理。
...
// 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
...
#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;
}