std :: end和std ::开始于函数(C ++)

use*_*243 2 c++ parameters function

我试图获取字符串数组的长度,并且已经在main函数中完成了工作,并且可以正常工作。之后,我需要在一个函数中执行此操作,但是它不能识别出带有错误的函数:

IntelliSense:没有任何重载函数“ begin”的实例与参数列表匹配

码:

void fun(string arr[])
{
    cout << end(arr) - begin(arr);
}

void main()
{
    string arr[] = {"This is a single string"};
    fun(arr);
}
Run Code Online (Sandbox Code Playgroud)

也是为了结束。

所以我添加了指针符号“ *”,错误消失了,但是它返回了数组中第一项的长度。

为什么会出现此错误?如何解决?

Pix*_*ist 5

您可以通过

#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);
}
Run Code Online (Sandbox Code Playgroud)

但是,在你的榜样阵列衰变成一个指针,所以你不能打电话sizeofbeginend