Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I tried to get the length of the string array, and I've done it in the main function and it worked. Afterwards I needed to do so in a function, but it doesn't identifies the functions with error:

IntelliSense: no instance of overloaded function "begin" matches the argument list

code:

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

void main()
{
    string arr[] = {"This is a single string"};
    fun(arr);
}

also for the end.

So I added the pointer symbol '*' and the error disappeared, but it returns me the length of the first item in the array.

Why do I get this error? How to fix it?

like image 315
user2410243 Avatar asked Mar 11 '26 22:03

user2410243


1 Answers

You can do this via

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

But in your example the array is decaying into a pointer so you can't call sizeof, begin or end.

like image 160
Pixelchemist Avatar answered Mar 14 '26 11:03

Pixelchemist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!