繁体   English   中英

在Xcode下在C ++中声明int数组

[英]Declaring array of int in C++ under Xcode

这两个声明有什么区别?

int myints[5];

array<int,5> myints;

如果我使用第一个声明和函数size(),将出现错误“成员引用基本类型'int [5]'不是结构或联合”。 但是,如果我使用第二个声明和函数size(),则该程序可以运行。 为什么第一个声明不起作用?

#include <iostream>
#include <iomanip>
#include <array>

using namespace std;

int main()
{
//int myints[5];      //illegal

array<int,5> myints;  //legal

cout << "size of myints: " << myints.size() << endl;    //Error if I use the first declarations
cout << "sizeof(myints): " << sizeof(myints) << endl;
}

正如其他人指出的那样, std::array是C ++ 11中添加的扩展(因此您可能没有),它包装了C样式数组,以便为​​其提供一些(但不是全部)STL-像界面。 目的是可以在C样式数组可以使用的任何地方使用它。 特别是,它接受与C样式数组相同的初始化语法,并且如果初始化类型允许静态初始化,则其初始化也可以是静态的。 (另一方面,编译器无法从初始值设定项列表的长度推断出它的大小,这对于较早的C样式数组而言是可以的。)

关于大小,任何经验丰富的程序员都将在其工具箱中具有大小函数,与std::beginstd::end (它们是C ++ 11扩展,并且每个人在C +之前的工具箱中都具有)相同+11标准化了)。 就像是:

template <typename T>
size_t
size( T const& c )
{
    return c.size();
}

template <typename T, size_t n>
size_t
size( T (&a)[n] )
{
    return n;
}

(在现代C ++中,第二个甚至可以是constexpr 。)

鉴于此,无论size( myInts )std::array还是C样式数组,您都可以编写size( myInts )

array<int,5> myints使用std::array ,该模板在“基本” C / C ++数组( int myints[5]是什么)上覆盖了增强的功能。 使用基本数组,您仅保留一块存储空间,并负责自己跟踪其大小(尽管您可以使用sizeof()来帮助解决此问题)。

使用std::array可以获得帮助程序函数,这些函数可以使数组更安全,更易于使用。

std::array是C ++ 11中的新增功能。 如您所见,它具有size功能。 这告诉您数组中有多少个项目。
另一方面, sizeof告诉您变量占用了多少内存,即其大小(以字节为单位)。

array是一个模板类,其成员函数具有size(),而int []是简单的C数组

通过使用int myints[5]; ,您要在堆栈上声明一个5个整数的数组,这是基本的C数组。

而是使用array<int,5> myints; 您要声明一个类型为array的对象,该对象是STL( http://en.cppreference.com/w/cpp/container/array )定义的容器类,而该类又实现了size()函数来检索容器的尺寸。

STL容器建立在“基本” C类型的基础上,以提供额外的功能并使其更易于管理。

int myints[5]; 没有函数size()但可以

int size = sizeof(myints)/ sizeof(int);

获取数组的大小。

所以基本上你可以做:

#include <iostream>
#include <iomanip>
#include <array>

using namespace std;

int main()
{

int myintsArr[5];      //legal

array<int,5> myints;  //legal

cout << "size of myints: " << myints.size() << endl;    //Error if I use the first declarations
cout << "sizeof(myintsArr): " << sizeof(myintsArr)/ sizeof(int) << endl;

}

并从两个数组中获得相同的结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM