简体   繁体   English

如何在C ++中向数组的末尾添加元素

[英]How to add element to last of array in c++

How to add element to last of array in c++? 如何在C ++中向数组的末尾添加元素?

int a[100] = {4,5}

How to add 6 to a[], then add 7 to a[]? 如何在a []上加6,然后在a []上加7?

Looks like, as mentioned in the comments, you're looking for a std::vector : 如评论中所述,您正在寻找一个std::vector

std::vector<int> a{4, 5};
a.push_back(6); // a now {4, 5, 6}
a.push_back(7); // a now {4, 5, 6, 7}

You have an array of 100 elements initialized by an initializer list {4, 5} . 您有一个由100个元素组成的数组 ,这些元素由初始化列表{4, 5}初始化。 This means a[0] is initialized to 4 , a[1] is initialized to 5 and all other array elements are initialized to 0 . 这意味着a[0]初始化为4a[1]初始化为5 ,所有其他数组元素初始化为0 Just because there are two elements in the initializer list doesn't mean there is an end of array after the second element. 仅仅因为初始化列表中有两个元素并不意味着第二个元素之后有一个数组结尾 There are 98 more array elements, all set to the value of 0 . 还有98个数组元素,所有元素均设置为0 Your array size is fixed. 您的数组大小是固定的。 It's 100 elements. 这是100个元素。 If you want a container that dynamically changes its size, use std::vector instead. 如果您想要一个可以动态更改其大小的容器,请改用std :: vector

您使用固定大小的C样式数组,因此只需替换下一个索引的值-或使用动态大小的std::vectorhttps://en.cppreference.com/w/cpp/container/向量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM