如何在c++中从结构数组中删除元素

How to delete an element from a struct array in c++

本文关键字:数组 删除 元素 结构 c++      更新时间:2023-10-16

假设我有一个这样的结构:

struct customer{
    int c1;
    int c2;
    int c3;
};
customer phone[10];
phone[0].c1 = 1;
phone[0].c2 = 1;
phone[0].c3 = 1;
phone[1].c1 = 2;
phone[1].c2 = 2;
phone[1].c3 = 2;

所以我的问题是如何从struct数组中移除phone[1]

提前谢谢。

你能做的最好的事情就是覆盖它。

这是一个内置数组。所以其他元素没有初始化。同样,一旦你向其中一个元素写入了一些东西,它就会一直呆在那里,直到数组超出范围,或者你在那里写入了其他东西。

最好对std::vector:也这样做

#include <iostream>
#include <vector>
int main()
{
    struct customer {
        int c1;
        int c2;
        int c3;
    };
    customer phone[10];
    phone[0].c1 = 1;
    phone[0].c2 = 1;
    phone[0].c3 = 1;
    phone[1].c1 = 2;
    phone[1].c2 = 2;
    phone[1].c3 = 2;
    std::vector<customer> phonev{{1,1,1},{2,2,2}};
    phonev.erase(phonev.begin()+1);
    return 0;
}

然后可以擦除元素。