This code below works as expected:
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
int arr[] = {6, 4, 2};
std::sort(std::begin(arr), std::end(arr));
for (const auto &i : arr)
std::cout << i << ' ';
std::cout << std::endl;
}
Now consider what happens when we modify the code that doesn't do the sorting and printing:
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
int n;
std::cin >> n; // take n = 3
int arr[n];
for (int i = 0; i != n; ++i)
std::cin >> arr[i]; // take (arr[0],arr[1],arr[2])=(6,4,2)
std::sort(std::begin(arr), std::end(arr));
for (const auto &i : arr)
std::cout << i << ' ';
std::cout << std::endl;
}
With gcc this results in the error (https://godbolt.org/z/W4av94TKj):
source>: In function 'int main()':
<source>:13:25: error: no matching function for call to 'begin(int [n])'
13 | std::sort(std::begin(arr), std::end(arr));
| ~~~~~~~~~~^~~~~
In file included from /opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/bits/range_access.h:36,
from /opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/string:51,
from /opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/bits/locale_classes.h:40,
from /opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/bits/ios_base.h:41,
from /opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/ios:42,
from /opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/ostream:38,
from /opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/iostream:39,
from <source>:1:
/opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/initializer_list:88:5: note: candidate: 'template<class _Tp> constexpr const _Tp* std::begin(initializer_list<_Tp>)'
88 | begin(initializer_list<_Tp> __ils) noexcept
| ^~~~~
/opt/compiler-explorer/gcc-trunk-20220623/include/c++/13.0.0/initializer_list:88:5: note: template argument deduction/substitution failed:
<source>:13:25: note: mismatched types 'std::initializer_list<_Tp>' and 'int*'
13 | std::sort(std::begin(arr), std::end(arr));
| ~~~~~~~~~~^~~~~
[... and a long list of more overloads ...]
Why is this an error? I know that the C++ standard requires the array size to be a constexpr
. However, gcc does offer it as extensions that allow non-constexpr
array sizes. But it doesn't answer the question of why the line that sorts the array is in error, and the rest isn't.