如何获取元素数量未知的数组的输入? [英] How to take input to an array with unknown number of elements?

查看:149
本文介绍了如何获取元素数量未知的数组的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int n = 10;
int a[n];  
for (int i = 0; i < n; i++)
{
    cin >> a[i];
}

当我们知道 n 的大小时,这就是我输入数组的方式.但是,当我们不知道 n 的大小时,我们必须在数组中接受输入,并在出现新行时停止接受输入.我们如何在C ++中做到这一点?

This is how I input array when we know the size of n. But when we don't know the size of n and we have to take input in an array and stop taking inputs when there is a new line. How can we do that in C++?

推荐答案

std :: vector< int> 是您所需要的.可以将其视为动态尺寸的数组.

std::vector<int> is what you need. Think of it as an array of dynamic size.

您可以使用 .push_back()

请参见 https://en.cppreference.com/w/cpp/container/向量

这篇关于如何获取元素数量未知的数组的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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