我试图获取字符串数组的长度,我已经在主函数中完成了它并且成功了。之后我需要在一个函数中这样做,但它没有识别出错误的函数:
IntelliSense: no instance of overloaded function "begin" matches the argument list
代码:
void fun(string arr[])
{
cout << end(arr) - begin(arr);
}
void main()
{
string arr[] = {"This is a single string"};
fun(arr);
}
也为结束。
所以我添加了指针符号“*”,错误消失了,但它返回数组中第一项的长度。
为什么会出现此错误?如何解决?
最佳答案
你可以通过
#include <iostream>
#include <string>
template<size_t N>
void fun(std::string (&arr)[N])
{
std::cout << std::end(arr) - std::begin(arr);
}
int main (void)
{
std::string arr[] = {"This is a single string"};
fun(arr);
}
但在您的示例中,数组正在衰减为指针,因此您无法调用 sizeof
、begin
或 end
。
关于c++ - 函数中的 std::end 和 std::begin (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186924/