当我做这样的事情时:
int my_array[5] = {1, 2, 3, 4, 5};
for (int &x : my_array) {
x *= 2;
}
Run Code Online (Sandbox Code Playgroud)
C++ 11显然知道我的数组只有5个元素.这些信息是否存储在my_array对象的某个位置?
如果是这样,有什么理由说明为什么它不能作为开发人员提供给我(或者是它?!?!?)?如果C++开发人员总是知道他们正在处理的数组的界限,似乎很多世界的问题都将得到解决.
我这些天自己学习C++并且我有一些问题需要理解为什么这段代码不能编译使用#g++ -std=c++11 source.cpp
.实际上我使用哪个特定标准并不重要,它只是不编译.
#include <iostream>
#include <string>
using namespace std;
int print_a(char array[])
{
for(char c : array)
cout << c;
cout << endl;
return 0;
}
int main(void)
{
char hello[] {"Hello!"};
print_a(hello);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误消息:
debian@debian:~/Documents$ g++ -std=c++11 source.cpp
source.cpp: In function ‘int print_a(char*)’:
source.cpp:6:15: error: ‘begin’ was not declared in this scope
for(char c : array)
^
source.cpp:6:15: note: suggested alternatives:
In file included from /usr/include/c++/4.9/bits/basic_string.h:42:0,
from /usr/include/c++/4.9/string:52,
from /usr/include/c++/4.9/bits/locale_classes.h:40,
from /usr/include/c++/4.9/bits/ios_base.h:41,
from /usr/include/c++/4.9/ios:42, …
Run Code Online (Sandbox Code Playgroud) 请考虑以下代码段:
#include <iostream>
int main() {
int s[6] {0, 1, 2, 3, 4, 5};
for ( auto && i: s ) {
std::cout << " " << i << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这在g ++和clang ++下编译和运行都很愉快.
它在许多帖子中被认为是理所当然的(例如这里和这里),但我不清楚编译器如何在for range
没有迭代器的情况下正确地推断出数组的大小.
任何人都可以回答或添加引用的链接吗?
我正在尝试使用foreach循环在调用的函数中打印数组的值,但遇到编译错误。在Linux平台上使用c ++ 11编译器并使用VIM编辑器。
当从调用函数传递大小时,尝试使用C样式进行循环并成功
#include <iostream>
using namespace std;
void call(int [], int);
int main()
{
int arr[] = {1,2,3,4,5};
int size = sizeof(arr)/sizeof(arr[0]);
call(arr,size);
}
void call(int a[],int size)
{
for(int i =0 ; i<size; i++)
cout << a[i];
}
Run Code Online (Sandbox Code Playgroud)
以下代码中使用的for-each循环无法编译。
#include <iostream>
using namespace std;
void call(int []);
int main()
{
int arr[] = {1,2,3,4,5};
call(arr);
}
void call(int a[])
{
for ( int x : a )
cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)
C ++ 11中的for-each循环希望知道要迭代的数组的大小?如果是这样,那么相对于传统的for循环它将如何有所帮助。还是我在这里编码的错误?
期待您的帮助。提前致谢。