这是模板
template <int LEN_1, int LEN_2>
bool less (char const (*arr1)[LEN_1], char const (*arr2)[LEN_2]) {
for (int i=0; i<LEN_1 && i<LEN_2; ++i) {
if (arr1[i]<arr2[i]) return true;
if (arr1[i]>arr2[i]) return false;
}
return LEN_1 < LEN_2;
}
我正在尝试从main传递字符串文字作为其参数,例如:
std::string a = "hello";
std::string b = "ok";
::less(a, b);
根据我所知道的,如果我按值传递args,则字符串文字应衰减为char const *。但是它只是无法通过编译。
请我帮我打破这个蛋。
答案 0 :(得分:2)
这不是合法的C ++。如果要使数组衰减,则必须显式传递大小。这是它的语法:
bool less (char const *arr1, std::size_t LEN_1, char const *arr2, std::size_t LEN_2) {
for (std::size_t i=0; i<LEN_1 && i<LEN_2; ++i) {
if (arr1[i]<arr2[i]) return true;
if (arr1[i]>arr2[i]) return false;
}
return LEN_1 < LEN_2;
}
但是您似乎想通过引用传递数组。操作方法如下:
template <std::size_t LEN_1, std::size_t LEN_2>
bool less (char const (&arr1)[LEN_1], char const (&arr2)[LEN_2]) {
for (std::size_t i=0; i<LEN_1 && i<LEN_2; ++i) {
if (arr1[i]<arr2[i]) return true;
if (arr1[i]>arr2[i]) return false;
}
return LEN_1 < LEN_2;
}
请注意使用std::size_t
而不是int
。
或者,您可以使用空终止符代替大小:
bool less (char const arr1[], char const arr2[]) {
for (/*nothing*/;*arr1 && *arr2; ++arr1, ++arr2) {
if (*arr1 < *arr2) return true;
if (*arr1 > *arr2) return false;
}
return !*arr1;
}
但是,在您的示例中,您正在传递std::string
的实例,而不是char数组。在这种情况下,您不需要自定义函数。重载的operator<
可以满足您的需求。如果您确实要使用函数,请使用std::string::c_str
:
less(a.c_str(), b.c_str());
或者您可以直接传递文字:
less("hello", "ok");