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

查看:211
本文介绍了循环遍历 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?

推荐答案

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

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.

正如其他人所指出的,std::array 在 C++11 中比原始数组更受欢迎;然而,其他答案都没有说明为什么 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天全站免登陆