繁体   English   中英

函数中的std :: end和std :: begin(C ++)

[英]std::end and std::begin in a function (C++)

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

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

码:

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);
}

但在您的示例中,数组会衰减为指针,因此您无法调用sizeofbeginend

问题在于您实际上不是在处理字符串数组...您正在使用std::string上的指针,因为std::string arr[]会衰减为std::string*

因此,这意味着std::end()std::begin()不适用于指针。

我更喜欢的解决方法是使用std::array<>std::vector<>或在调用函数之前检索begin end:

template <typename iterator>
void fun(iterator begin, iterator end)
{
    std::cout << end - begin; 
}

int main()
{
    std::string arr[] = {"This is a single string"};
    fun(std::begin(arr), std::end(arr));
    return 0;
}

我不喜欢在另一个答案中建议的参数中硬编码大小,但这是个人喜好问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM