C++ 模块类 vector - 动态长度数组

2016-12-16  本文已影响0人  静_谷

曾经参加用Pascal参加NOIP,因为数组的内存问题被整的死去活来。Pascal中只有array,且数组长度在编译期时便确定。现在学习了C++,猛然发现了一个 模块类 vector,(一个悲伤的故事:NOIP不支持vector库,但是这里可以用 指针动态创建数组,以达到相同目的)于是……

首先让我们看一下,vector的声明:

vector<typeName> vt(n_elem)

这个声明创建了一个名为vt的vector对象,它可以储存 n_elem 个类型为 typeName 的元素,关键是参数 n_elem 可以是变量!
(注意 vector 来自 头文件vector,所以要在程序前面加一句#include <vector>

所以,我便默默地敲下了下面这个栗子:
#include <iostream>
#include <vector>

using namespace std;
int main()
{
    int n;
    cin>>n;
    vector<int> vd(n);
    for(int i=0;i!=n;i++)
    {cin>>vd[i];}
    for(int i=0;i!=n;i++)
    {cout<<vd[i]<<endl;}

    system("pause");
    return 0;
}

Success!
测试数据:

4
3
2
1
3
3
2
1
3
请按任意键继续. . .

Now,enjoy your code!

上一篇 下一篇

猜你喜欢

热点阅读