user2410243
user2410243

Reputation: 187

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?

Upvotes: 3

Views: 2666

Answers (2)

Johan
Johan

Reputation: 3778

The problem is that you're not really working on an array of string... You're working with a pointer on a std::string, because std::string arr[] decays to std::string*.

So what it means is just std::end() and std::begin() don't work for pointers.

The workaround I prefer is to use std::array<> or std::vector<> or to retrieve begin end before calling the function:

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

I do not like having the size hardcoded in a parameter like suggested in another answer, but it is a matter of personal taste.

Upvotes: 2

Pixelchemist
Pixelchemist

Reputation: 24946

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.

Upvotes: 5

Related Questions