(注意:这个问题是不必指定元素的数量,仍然允许直接初始化嵌套类型.)
这个问题讨论了C数组的用途int arr[20];
.在他的回答中,@ James Kanze展示了C阵列的最后一个据点,它具有独特的初始化特性:
int arr[] = { 1, 3, 3, 7, 0, 4, 2, 0, 3, 1, 4, 1, 5, 9 };
Run Code Online (Sandbox Code Playgroud)
我们没有必要指定元素的数量,万岁!现在遍历它与C++ 11的功能std::begin
和std::end
从<iterator>
(或您自己的变体),你永远需要甚至认为它的大小.
现在,有没有(可能是TMP)方法实现同样的目标std::array
?使用宏可以使它看起来更好.:)
??? std_array = { "here", "be", "elements" };
Run Code Online (Sandbox Code Playgroud)
编辑:中间版本,从各种答案编译,如下所示:
#include <array>
#include <utility>
template<class T, class... Tail, class Elem = typename std::decay<T>::type>
std::array<Elem,1+sizeof...(Tail)> make_array(T&& head, Tail&&... values)
{
return { std::forward<T>(head), std::forward<Tail>(values)... };
}
// in code …
Run Code Online (Sandbox Code Playgroud) 我两天前开始学习 C++,我遇到的这个错误对我来说很模糊,我正在尝试执行以下操作
\n\nint sumArray(const int arr)\n{\n int sum = 0;\n for (auto &n : arr) {\n sum += n;\n }\n return sum;\n};\n\nint main () \n{\n int numbers[] = {1, 2, 5, 10};\n return sumArray(numbers);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n这与“C++ 之旅”中的示例略有不同,我收到的错误是
\n\ncpprepl.cpp: In function \xe2\x80\x98int sumArray(int)\xe2\x80\x99:\ncpprepl.cpp:4:18: error: \xe2\x80\x98begin\xe2\x80\x99 was not declared in this scope\n for (auto &n : arr) {\n ^~~\ncpprepl.cpp:4:18: error: \xe2\x80\x98end\xe2\x80\x99 was not declared in this scope\ncpprepl.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\ncpprepl.cpp:13:26: error: invalid conversion from \xe2\x80\x98int*\xe2\x80\x99 to \xe2\x80\x98int\xe2\x80\x99 [-fpermissive]\n return …