(这里没有其他答案中未提及的新内容,但我将尝试简洁地提供解释和示例而不会失去清晰度。)
循环检查'\0' 的char 数组是可行的,因为C 风格的字符串有一个int、double 和大多数其他类型没有的约定:空终止。 ('\0' 字符称为“null”或“NUL”,但很少使用“NULL”以避免与该名称的宏混淆。)
由于 int 和 double 数组没有这个约定,你必须使用其他东西。以下是最简单的替代方案:
// pass arrays with their size
void ex1(double const* data, int size) {
for (int n = 0; n < size; ++n) {
use(data[n]);
}
}
// use a container class which has a size() method
void ex2(vector<double> const& v) {
for (int n = 0; n < v.size(); ++n) {
use(data[n]);
}
// or:
for (vector<double>::const_iterator i = v.begin(); i != v.end(); ++i) {
use(*i);
}
// or, sometimes a slight tweak:
for (vector<double>::const_iterator i = v.begin(), end = v.end();
i != end; ++i
) {
use(*i);
}
}
// pass an iterator range, once you are familiar with iterators
void ex3(double const* begin, int const* end) {
for (double const* i = begin; i != end; ++i) {
use(*i);
}
}
以及如何使用它们:
void ex4() {
double data[] = {3, 5, 42}; // if you don't want to specify the size, then use
int length = len(data); // this special len function to get the array length
// len defined below
ex1(data, length); // easy to pass with size now
ex2(vector<double>(data, data + length)); // easy to create a container too
ex3(data, data + length);
// notice the container creation takes a similar iterator range
double buncha_zeros[42] = {}; // or even if you specify the length
length = len(buncha_zeros); // you still don't have to repeat yourself
}
template<class T, int N>
N len(T (&)[N]) {
return N;
}
// note: this exists in boost in a better, more general form as boost::size
用“int”或几乎任何其他类型替换“double”,这里的一切都一样。