使用动态内存从数组中删除重复项。分配

Removing duplicates from an array, using dynamic mem. allocation

这个方法是我的 class sets(for college) 的成员函数,它有成员 Set(pointer) 和 card(int)(cardinality)。我应该删除重复项并减少分配的内存。

nSet 指针用于临时保存数据。

不幸的是,无论何时调用它都会崩溃。做什么?

void remdup() {
    int *nSet;
    for(int x=0;x<card-1;x++) {
        for(int y=x+1;y<card;y++) {
            if(Set[x]==Set[y]) {
                for(int g=y;g<card-1;g++) {
                    Set[g]=Set[g+1];
                } card--;
            }
        }
    }
    nSet=new int[card];
    for( int u=0;u<card;u++) {
        nSet[u]=Set[u];
    }
    delete Set;
    Set=new int[card];
    for(int u=0;card;u++) {
        Set[u]=nSet[u];
    }

你的 for 循环有误。 for(intialization;condition;increment) {}

void remdup() {
        int *nSet;
        for(int x=0;x<card-1;x++) {
            for(int y=x+1;y<card;y++) {
                if(Set[x]==Set[y]) {
                    for(int g=y;g<card-1;g++) {
                        Set[g]=Set[g+1];
                    } card--;
                }
                }
        }
        nSet=new int[card];
        for( int u=0;u<card;u++) {
            nSet[u]=Set[u];
        }
        delete Set;
        Set=new int[card];
        for(int u=0;u<card;u++) {<---
            Set[u]=nSet[u];
        }

使用 std::set 而不是发明另一个更糟糕的集合。

首先我推荐使用std::set而不是自己动手。 除此之外,如果您将 for(int u=0;card;u++) 更改为 for(int u=0;u<card;u++),则在您的代码末尾它将起作用。 但是如果你喜欢自己做所有的工作并缩小一个 int 的数组,你应该使用 std::memcpy 将数据从旧的动态内存复制到新的:

#include <cstring> // memcpy

int *nSet = new int[card];
std::memcpy( nSet, Set, card );
delete [] Set;
Set = nSet;