如何将元素添加到C ++数组? [英] How to add element to C++ array?
问题描述
我想在数组中添加一个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::vector
.
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
:
You can use a vector
in this way:
std::vector< int > arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
这篇关于如何将元素添加到C ++数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!