循环遍历 C++ 数组的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20234898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way of looping through C++ arrays
提问by Lucas
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):
最近我发现了很多例子,其中大部分是关于 C++ 98 的,无论如何我已经创建了我的简单数组和一个循环(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;
}
Output:
输出:
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.
它工作正常,除了最后的分段错误。
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++ 11,所以想确保它符合标准并且不能以更好的方式完成?
回答by Nicu Stiurca
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 notgive the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,
在 C/C++ 中sizeof
。总是给出整个对象的字节数,数组被视为一个对象。注意:sizeof
指针——指向数组的第一个元素或单个对象——给出指针的大小,而不是指向的对象。无论哪种方式,sizeof
都不会给出数组中的元素数(其长度)。要获得长度,您需要除以每个元素的大小。例如。,
for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )
As for doing it the C++11 way, the best way to do it is probably
至于用 C++11 的方式来做,最好的方法可能是
for(const string &text : texts)
cout << "value of text: " << text << endl;
This lets the compiler figure out how many iterations you need.
这让编译器可以计算出您需要多少次迭代。
EDIT: 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.
编辑:正如其他人所指出的,std::array
在 C++11 中优于原始数组;然而,其他答案sizeof
都没有解决为什么会失败,所以我仍然认为这是更好的答案。
回答by Mark Garcia
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
Nope. Totally a wrong way of iterating through an array. sizeof(texts)
is not equal to the number of elements in the array!
不。完全错误的遍历数组的方式。sizeof(texts)
不等于数组中元素的个数!
The modern, C++11 ways would be to:
现代的 C++11 方法是:
- use
std::array
if you want an array whose size is known at compile-time; or - use
std::vector
if its size depends on runtime
std::array
如果您想要一个在编译时已知大小的数组,请使用;或者- 使用
std::vector
如果它的大小取决于运行
Then use range-for when iterating.
然后在迭代时使用 range-for。
#include <iostream>
#include <array>
int main() {
std::array<std::string, 3> texts = {"Apple", "Banana", "Orange"};
// ^ An array of 3 elements with the type std::string
for(const auto& text : texts) { // Range-for!
std::cout << text << std::endl;
}
}
You may ask, how is std::array
better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resembling std::vector
. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for or std::begin/end
on it.
你可能会问,怎么std::array
比ol'C数组好呢?答案是它具有其他标准库容器的额外安全性和功能,大多与std::vector
. 此外,答案是它没有衰减到指针并因此丢失类型信息的怪癖,一旦丢失原始数组类型,就不能使用 range-for 或std::begin/end
on 。
回答by kfsone
sizeof
tells you the size of a thing, not the number of elements in it. A more C++11 way to do what you are doing would be:
sizeof
告诉您事物的大小,而不是其中的元素数量。做你正在做的事情的更多 C++11 方法是:
#include <array>
#include <string>
#include <iostream>
int main()
{
std::array<std::string, 3> texts { "Apple", "Banana", "Orange" };
for (auto& text : texts) {
std::cout << text << '\n';
}
return 0;
}
ideone demo: http://ideone.com/6xmSrn
ideone 演示:http://ideone.com/6xmSrn
回答by Nuno Rafael Figueiredo
Add a stopping value to the array:
向数组添加一个停止值:
#include <iostream>
using namespace std;
int main ()
{
string texts[] = {"Apple", "Banana", "Orange", ""};
for( unsigned int a = 0; texts[a].length(); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
回答by SPIDERMAN
you need to understand difference between std::array::size and sizeof() operator. if you want loop to array elements in conventional way then you could use std::array::size. this will return number of elements in array but if you keen to use C++11 then prefer below code
您需要了解 std::array::size 和 sizeof() 运算符之间的区别。如果您想以传统方式循环数组元素,那么您可以使用 std::array::size。这将返回数组中的元素数,但如果您热衷于使用 C++11,则更喜欢下面的代码
for(const string &text : texts)
cout << "value of text: " << text << endl;
回答by Phidelux
If you have a very short list of elements you would like to handle, you could use the std::initializer_listintroduced in C++11 together with auto:
如果您要处理的元素列表非常短,则可以将C++11 中引入的std::initializer_list与 auto 一起使用:
#include <iostream>
int main(int, char*[])
{
for(const auto& ext : { ".slice", ".socket", ".service", ".target" })
std::cout << "Handling *" << ext << " systemd files" << std::endl;
return 0;
}
回答by bvj
sizeof(texts)
on my system evaluated to 96: the number of bytes required for the array and its string instances.
sizeof(texts)
在我的系统上评估为 96:数组及其字符串实例所需的字节数。
As mentioned elsewhere, the sizeof(texts)/sizeof(texts[0])
would give the value of 3 you were expecting.
正如其他地方提到的, thesizeof(texts)/sizeof(texts[0])
将给出您期望的 3 值。
回答by Harmen
How about:
怎么样:
#include <iostream>
#include <array>
#include <algorithm>
int main ()
{
std::array<std::string, 3> text = {"Apple", "Banana", "Orange"};
std::for_each(text.begin(), text.end(), [](std::string &string){ std::cout << string << "\n"; });
return 0;
}
Compiles and works with C++ 11 and has no 'raw' looping :)
编译并使用 C++ 11 并且没有“原始”循环:)
回答by Muhammad Ishtiaq Hussain
You can do it as follow:
你可以这样做:
#include < iostream >
using namespace std;
int main () {
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts) / 32; a++ ) { // 32 is the size of string data type
cout << "value of a: " << texts[a] << endl;
}
return 0;
}