0

I know that for arrays we can use std::begin(arr) but not arr.begin(), but that's the only case I can think of. In other cases, even when writing templates, I think we can just stick to xxx.begin(), where xxx is of template type T. So what's the benefit of using std::begin()? Is there any reason other than arrays?

For example, in the following case there seems to be no difference between the two.

template<typename T>
void print_first(T sth){
    std::cout << *sth.begin() << std::endl;
}
    
int main()
{
    std::vector<int> vec{1,2,3} ;
    print_first(vec);
    return 0;
}
  • 1
    Your function signature doesnt permit it because you take the parameter by value (which is wasteful) but if you had `const T& sth` and used `std::begin` it would work for arrays and containers. Its specifically so you can write generic code that works in both cases. – Borgleader Oct 31 '22 at 02:56
  • @Borgleader thanks for pointing out the signature defect. but I don't get what you meant by "doesn't permit it". And yes, it seems that the difference lies in the array type. I'm wondering if there're other cases. – Daniel Mendoza Oct 31 '22 at 03:11
  • @JeJo it seems from these posts that array is the only case where .begin() doesn't work. – Daniel Mendoza Oct 31 '22 at 03:14
  • @DanielMendoza if you take the parameter by value the array decays to a pointer to its first element, you need to take it by ref if you want to use [the ctor that takes an array](https://en.cppreference.com/w/cpp/iterator/begin) – Borgleader Oct 31 '22 at 03:24

0 Answers0