如何制作一个动态数组?两个参数 [英] How to make a dynamic array? Two parameters

查看:84
本文介绍了如何制作一个动态数组?两个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想在程序中创建一个数组.我正在获取用户的数组和大小.然后将其添加到数组中.
我该怎么办?

我实际上要执行此操作!

Hi
I want to create an array in the program. I''m getting the array and the size of the user. Then I add it to the array.
How can I do it?

I actually want to do this operation!

int i,j;
cin>>i>>j;
int a[i][j];


如果要使此示例正常工作,该怎么办?
如果数组2元素?


If want this example to work correctly, what should I do?
if array 2 element ?

推荐答案

您可以使用new运算符,即 ^ ]提供示例代码.

您还可以使用STL容器,例如std::vector (例如,参见此处 [ ^ ]).
You may use the new operator, the documentation[^] provides sample code.

You could also use a STL container, like the std::vector (see, for instance here[^]).


此代码段可能可以帮助您:

Perhaps this snippet can help:

    vector<int> x;

    int size;
    cin >> size;

    while (size--)
    {
        int temp; cin >> temp; x.push_back(temp);
    }
/*
    Better is, but the compiler dislikes it:
    while (size--)
        cin >> x.push_back();
    or
    while (size--)
        x.push_back(cin>>);
*/ 

    // processing...

    for (vector<int>::iterator it = x.begin(); it != x.end(); it++)
        cout << *it << endl;

    x.clear();


# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>

int main()
{
	int size;
	scanf("%d",&size);
	int* p = (int *)malloc(sizeof(int)*size);
	if(NULL == p)
		exit(-1);
	for(int i = 0;i < size;++ i)
		scanf("%d",&p[i]);
	for(int i = 0;i < size;++ i)
		printf("%3d",p[i]);
	return 0;
}</stdlib.h></malloc.h></stdio.h>


这篇关于如何制作一个动态数组?两个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆