相关疑难解决方法(0)

什么是阵列衰减?

什么是阵列的衰变?与数组指针有关系吗?

c c++ arrays pointers

358
推荐指数
8
解决办法
5万
查看次数

C++ 11基于范围的for循环如何知道数组大小?

当我做这样的事情时:

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++ for-loop c++11

9
推荐指数
3
解决办法
4745
查看次数

基于函数循环的范围,它将数组作为值传递

我这些天自己学习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)

c++ for-loop c++11

6
推荐指数
1
解决办法
1732
查看次数

范围循环如何推断普通数组大小

请考虑以下代码段:

#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没有迭代器的情况下正确地推断出数组的大小.
任何人都可以回答或添加引用的链接吗?

c++ arrays for-loop range c++11

4
推荐指数
1
解决办法
195
查看次数

当在调用方函数中将数组作为参数传递时,为什么不能使用被调用函数中的foreach循环来打印数组的值?

我正在尝试使用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循环它将如何有所帮助。还是我在这里编码的错误?

期待您的帮助。提前致谢。

c++ foreach c++11

0
推荐指数
1
解决办法
60
查看次数

标签 统计

c++ ×5

c++11 ×4

for-loop ×3

arrays ×2

c ×1

foreach ×1

pointers ×1

range ×1