Luc*_*cas 49 c++ arrays loops c++11
最近我发现了很多例子,其中大部分都是关于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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
value of a: Apple value of a: Banana value of a: Orange Segmentation fault
它工作正常,除了最后的分段错误.
我的问题是,这个数组/循环是否完成了一个好方法?我正在使用C++ 11,所以我想确保它符合标准并且无法以更好的方式完成?
Nic*_*rca 81
在C/C++中sizeof
.始终给出整个对象中的字节数,并将数组视为一个对象.注意:sizeof
指向数组的第一个元素或单个对象的指针给出指针的大小,而不是指向的对象.无论哪种方式,sizeof
都不会给出数组中的元素数量(它的长度).要获得长度,您需要除以每个元素的大小.例如.,
for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )
Run Code Online (Sandbox Code Playgroud)
至于做C++ 11的方式,可能是最好的方法
for(const string &text : texts)
cout << "value of text: " << text << endl;
Run Code Online (Sandbox Code Playgroud)
这使编译器可以计算出您需要多少次迭代.
编辑:正如其他人所指出的,std::array
在C++ 11中优于原始数组; 然而,没有其他答案解决了为什么sizeof
会失败的原因,所以我仍然认为这是更好的答案.
Mar*_*cia 18
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
Run Code Online (Sandbox Code Playgroud)
不.完全是一种迭代数组的错误方法.sizeof(texts)
不等于数组中的元素数量!
现代的C++ 11方式是:
std::array
如果你想要一个在编译时已知大小的数组,请使用; 要么std::vector
如果它的大小取决于运行然后在迭代时使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
你可能会问,怎么std::array
比ol'C阵列更好?答案是它具有其他标准库容器的额外安全性和功能,大多非常相似std::vector
.此外,答案是它没有对指针进行衰减的怪癖,从而丢失了类型信息,一旦丢失了原始数组类型,就不能使用range-for或std::begin/end
on.
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;
}
Run Code Online (Sandbox Code Playgroud)
ideone演示:http://ideone.com/6xmSrn