我需要你在 C/C++ 数组方面的帮助。我已经使用 Python 编程三年了,它的数组(称为 list
)非常容易使用。
>>> array = [1,2,3,4]
>>> array.append(5)
>>> array
[1,2,3,4,5]
正如我在 C/C++ 中读到的那样,我需要创建一个指向数组的指针。请你做一个包含 char
数组并且只有一个方法 append 的类的小草图,它被称为 append
并接收一个 char
作为参数。此方法将数组的大小增加 1,并将给定的 char
添加到此数组。
可能有人认为这是作业,但我就是无法理解数组、指针和内存分配的工作原理。我想这并不难,但在像 Python 这样的语言之后就很难了,因为我不关心 Python 中的这些东西。能否请您提供一小段代码并进行解释?
提前致谢!
这是一个标准的 C++ 程序:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> array = {1, 2, 3, 4};
array.push_back( 5 );
for( auto const item : array )
{
cout << item << " ";
}
cout << endl;
}
特定于 Visual C++。
即使是最新版本的 Microsoft Visual C++,即 November 2012 CTP ,这是 11.0 版,带有大量修复以支持 C++11 标准,但尚不支持上面使用的一般初始化。
对于 Visual C++,就像在 C++03 中一样,该表示法仅支持所谓的聚合类型,它们本质上是纯原始数组或纯原始结构(可能包含更多 C++'ish类型)或内置类型。因此,使用 Visual C++ 实现此目的的一种方法是将该符号用于 原始数组,然后使用该原始数组来初始化 vector
:
#include <iostream>
#include <iterator> // std::begin, std:.end
#include <vector>
using namespace std;
int main()
{
int const data[] = {1, 2, 3, 4};
vector<int> array( begin( data ), end( data ) );
array.push_back( 5 );
for( auto const item : array )
{
cout << item << " ";
}
cout << endl;
}
这也适用于 Visual Studio 2012 附带的基础 Visual C++ 11.0。
但是,基于范围的 for
循环可能无法使用 Visual C++ 10.0(对应于 Visual Studio 2010)进行编译。