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

标签 c++ function parameters

我试图获取字符串数组的长度,我已经在主函数中完成了它并且成功了。之后我需要在一个函数中这样做,但它没有识别出错误的函数:

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

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

关于c++ - 函数中的 std::end 和 std::begin (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186924/

相关文章:

c++ - socket编程发送数据时出现Broken Pipe错误

C++ 使用函数 sort()、count() 根据词频对字符串进行排序失败

c++ - QPainter与Qt::AlignCenter不能正确居中文本

JavaScript 重启计数器

linux - 链接两个参数 - Shell 脚本

c# - SqlCommand 参数添加与 AddWithValue

c++ - 字符串到 double 转换 C++

c - 字符数组中的递归函数,用于在数组的前 3 个元素中查找辅音

javascript - 将参数传递给 asp.net 页面中的 javascript 函数

c++ - 如何修复模板内的错误重构 decltype