如何将元素添加到 C++ 数组? [英] How to add element to C++ array?

查看:41
本文介绍了如何将元素添加到 C++ 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数组中添加一个 int,但问题是我现在不知道索引是什么.

I want to add an int into an array, but the problem is that I don't know what the index is now.

int[] arr = new int[15];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

该代码有效,因为我知道要分配给哪个索引,但是如果我不知道该索引怎么办...

That code works because I know what index I am assigning to, but what if I don't know the index...

在 PHP 中,我可以只做 arr[]=22;,它会自动将 22 添加到数组的下一个空索引.但是在 C++ 中我不能这样做,它给了我一个编译器错误.大家有什么建议?

In PHP, I can just do arr[]=22;, which will automatically add 22 to the next empty index of the array. But in C++ I can't do that, it gives me a compiler error. What do you guys suggest?

推荐答案

使用普通数组无法实现您在 C++ 中所说的那样.对此的 C++ 解决方案是使用 STL 库,该库为您提供 std::矢量.

There is no way to do what you say in C++ with plain arrays. The C++ solution for that is by using the STL library that gives you the std::vector.

你可以这样使用vector:

#include <vector>

std::vector< int > arr;

arr.push_back(1);
arr.push_back(2);
arr.push_back(3);

这篇关于如何将元素添加到 C++ 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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