我试着获取字符串数组的长度,我在主函数中完成了它,并且它工作了。之后,我需要在一个函数中这样做,但它没有用错误标识函数:
IntelliSense:没有重载函数"begin“的实例与参数列表匹配
代码:
void fun(string arr[])
{
cout << end(arr) - begin(arr);
}
void main()
{
string arr[] = {"This is a single string"};
fun(arr);
}
也是为了结束。
因此,我添加了指针符号'*‘,错误消失了,但它返回数组中第一个项的长度。
为什么我会有这个错误?怎么修呢?
发布于 2014-01-17 13:26:52
你可以通过
#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
。
发布于 2014-01-17 13:16:18
问题是你不是真的在处理字符串数组.您正在使用std::string
上的指针,因为std::string arr[]
会衰减到std::string*
。
所以这意味着std::end()
和std::begin()
不适用于指针。
我喜欢的解决方法是在调用函数之前使用std::array<>
或std::vector<>
或检索开始结束:
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;
}
我不喜欢像在另一个答案中建议的那样在参数中硬编码大小,但这是个人品味的问题。
https://stackoverflow.com/questions/21186924
复制相似问题