正确遍历C ++数组的方法 [英] Correct way of looping through C++ arrays

查看:368
本文介绍了正确遍历C ++数组的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我发现了很多示例,其中大多数都与C ++ 98有关,无论如何,我已经创建了我的简单数组和循环(

Recently I have found a lot of examples, most of them regards the C++ 98, anyways I have created my simple-array and a loop (codepad):

#include <iostream>
using namespace std;

int main ()
{
   string texts[] = {"Apple", "Banana", "Orange"};
   for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
   {
       cout << "value of a: " << texts[a] << endl;
   }

   return 0;
}

输出:

value of a: Apple
value of a: Banana
value of a: Orange

Segmentation fault

一切正常,除了最后的分割错误.

It's working fine, except the segmentation fault at the end.

我的问题是,这种数组/循环遍历是一种好方法吗?我正在使用C ++ 11,因此想确保它符合标准并且不能做更好的方法吗?

My question is, does this array/loop through is done a good way? I am using C++ 11 so would like to be sure it fits the standards and couldnt be done a better way?

推荐答案

在C/C ++ sizeof中.总是给出整个对象中的字节数,并且数组被视为一个对象.注意:sizeof指向数组第一个元素或单个对象的指针给出的是 pointer 的大小,而不是所指向的对象的大小.无论哪种方式,sizeof都不会 not 给出数组中元素的数量(其长度).要获得长度,您需要除以每个元素的大小.例如,

In C/C++ sizeof. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof a pointer--to the first element of an array or to a single object--gives the size of the pointer, not the object(s) pointed to. Either way, sizeof does not give the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,

for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )

关于C ++ 11方式,最好的方式可能是

As for doing it the C++11 way, the best way to do it is probably

for(const string &text : texts)
    cout << "value of text: " << text << endl;

这使编译器可以确定您需要进行多少次迭代.

This lets the compiler figure out how many iterations you need.

正如其他人指出的那样,在C ++ 11中,std::array比原始数组更受青睐;但是,没有其他答案可以说明为什么sizeof会失败,所以我仍然认为这是更好的答案.

as others have pointed out, std::array is preferred in C++11 over raw arrays; however, none of the other answers addressed why sizeof is failing the way it is, so I still think this is the better answer.

这篇关于正确遍历C ++数组的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆