下面的代码按预期工作:
#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;
}现在,考虑一下当我们修改不执行排序和打印的代码时会发生什么:
#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;
}对于gcc,这将导致错误(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 ...]为什么这是个错误?我知道C++标准要求数组大小为constexpr。然而,gcc确实提供了允许非constexpr数组大小的扩展。但它没有回答为什么排列数组的行出现错误的问题,而其他的则没有。
发布于 2022-06-23 14:19:57
数组的std::end重载是
template< class T, std::size_t N >
constexpr T* end( T (&array)[N] ) noexcept;但
int n;
std::cin >> n; // take n = 3
int arr[n];意味着没有与模板参数匹配的编译时间大小。STL功能无法在您的VLA上工作。你必须用
std::sort(arr, arr + n);https://stackoverflow.com/questions/72731085
复制相似问题