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

时间:2016-04-12 18:52:51

标签: c++ arrays struct

假设我有这样的结构:

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;

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

提前感谢。

1 个答案:

答案 0 :(得分:2)

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

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

最好对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;
}

然后你可以删除一个元素。

相关问题