错误:通过指针显示重复的结果

时间:2017-05-05 08:02:30

标签: c++ arrays pointers char

目标状态:我应该通过随机显示结果显示结果设置S = {dog,cow,chicken ...},其中随机大小可以是1-12并且动物不能被复制,所以一旦有了牛,就不再有Set S中的另一头母牛了。

错误:我一直在显示正确的随机大小1-12。但是我有重复的动物,即使我在将它插入Set S之前试图检查动物是否存在于集合S中。

UPDATE:我无法通过stackoverflow对等体进行各种更新后运行它。

约束:我必须使用指针与指针进行比较 - 动态。 “重要的提示 应该动态创建用于阵列的所有存储;并删除它们 他们不再需要了。 访问数组的元素时,应该通过指针访问它,即通过 取消引用此指针。使用表示法,例如set [k]或*(set + k) 不允许访问集合的第k个元素。“

希望听到你的建议,好朋友!

祝你好运, MM

/* 
MarcusMoo_A2.cpp by Marcus Moo
Full Time Student
I did not pass my assignment to anyone in the class or copy anyone’s work; 
and I'm willing to accept whatever penalty given to you and 
also to all the related parties involved 
*/

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;

/* Global Declaration */
const int MAX = 12; // 12 animals
const int MAXSTR = 10; 

typedef char * Element;
static Element UniversalSet [MAX] = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon",
"Snake", "Horse", "Sheep", "Monkey", "Rooster", "Dog", "Pig"};

/* Functions */

// Construct a set
void option0(int); // Menu Option 0
void constructSet (Element *, int); // Construct a set
bool checkElement (Element *, Element *, int); // Check element for replicates

int main()
{   
    // Declarations
    int mainSelect;

    int size=rand()%12+1; // Random construct


    srand (time(NULL)); // Even better randomization

    cout << "Welcome to MARCUS MOO Learning Center" << endl;

    do 
    {
        cout << "0. An example of set" << endl;
        cout << "1. Union" << endl;
        cout << "2. Intersection" << endl;
        cout << "3. Complement" << endl;
        cout << "4. Subset of" << endl;
        cout << "5. Equality" << endl;
        cout << "6. Difference " << endl;
        cout << "7. Distributive Law" << endl;
        cout << "9. Quit" << endl;
        cout << endl;

        if (mainSelect==0)
        {
            option0(size);
        }

        cout << "Your option: ";
        cin >> mainSelect;
        cout << endl;

    } while(mainSelect!=9);

    return 0;
}

/* Functions */

// Option 0 - An example of set
void option0 (int size)
{
    // Mini Declaration
    int again;
    Element *S;

    do 
    {
        cout << "Here is an example on set of animals" << endl;
        cout << endl;

        // Build set S

        constructSet (S,size);


        // Display set S
        Element *S = &S[0];

        cout << "Set S = {";

        for (int i = 0; i < size; i++)
        {
            if (i!=size)
            {
                cout << *S
                     << ", ";
            }
            else 
            {
                cout << *S
                     << "}"
                     << endl;
            }     

            S++;      
        } 


        cout << endl;
        cout << "Note that elements in S are distinct are not in order" << endl;
        cout << endl;

        // Option 0 2nd Part
        cout << "Wish to try the following operations?" << endl;
        cout << "1. Add an element to the set" << endl;
        cout << "2. Check the element in the set" << endl;
        cout << "3. Check the cardinality" << endl;
        cout << "9. Quit" << endl;
        cout << endl; 
        cout << "Your choice: ";
        cin >> again;

    } while (again!=9);   
}

// Construct a set 
void constructSet (Element *set, int size)
{
    // Declarations
    Element *ptrWalk;
    ptrWalk = &set[0];
    int randomA=0;

    for (int i = 0;i<size;i++)
    {
        bool found = true;
        while (found) 
        {
            randomA = rand()%MAX;  // avoid magic numbers in code...
            *ptrWalk = UniversalSet [randomA];

            // Ensure no replicated animals in set S
            found = checkElement (ptrWalk, set, i);
        }
        set=ptrWalk;
        set++;         
    }
}

bool checkElement (Element *ptrWalk, Element *set, int size)
{
    for (int j=0; j<size;j++)
    {
        if (ptrWalk==&set[j])
        {
            return true;
        }
    }
    return false;
}

2 个答案:

答案 0 :(得分:1)

您的代码中有两个不同的主要问题。第一个已经由Federico给出:checkElement一旦找到一个元素就应该返回true。代码应该变得简单(但请注意<中的 j<size ):

bool checkElement (char *ptrWalk, int size)
{
    for (int j=0; j<size;j++)
    {
        if (ptrWalk==S[j])
        {
            return true;
        }
    }
    return false;
}

第二个问题是你不应该搜索整个数组,而只搜索已经填充的部分。这意味着在constructSet中您应该调用checkElement(ptrWalk, i),因为当前元素的索引是已填充项的数量。所以你必须更换两行

    found = checkElement (*ptrWalk, size);

这一个

    found = checkElement (*ptrWalk, i);

这应该足以让您的计划给出预期的结果。但如果你想要它很好,仍然有一些改进:

  • 您正确声明了int main(),但在return 0;
  • 结束时忘记了main
  • 您在定义之前调用函数时未能转发声明函数(至少应该发出警告......)
  • 你大量使用全局变量,这不是一个好习惯,因为它不允许轻松测试
  • 您的算法应该简化为遵循不要重复自己的原则。代码重复对于将来的维护是不利的,因为如果在不同的地方应用代码更改的力量和遗漏这样做会导致令人讨厌的错误(看起来这很糟糕但是我已经修复了它 - 是的但是只在一个地方... 。)

constructSet可能只是:

// Construct a set 
void constructSet (Element *set, int size)
{
    // Declarations
    //Element *ptrBase;
    voidPtr *ptrWalk;
    ptrWalk = &set[0];
    int randomA=0;

    for (int i = 0;i<size;i++)
    {
        bool found = true;
        while (found) {
            randomA = rand()%MAX;  // avoid magic numbers in code...
            *ptrWalk = UniversalSet [randomA];

            // Ensure no replicated animals in set S
            found = checkElement (*ptrWalk, i);
        }
        ptrWalk++;          
    }
}

答案 1 :(得分:0)

我已经在我的C ++讲师的指导下解决了这个问题!你们可以参考这个来解决下次指针困境的指针!干杯!

/* 
MarcusMoo_A2.cpp by Marcus Moo
Full Time Student
I did not pass my assignment to anyone in the class or copy anyone’s work; 
and I'm willing to accept whatever penalty given to you and 
also to all the related parties involved 
*/

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;

/* Global Declaration */
const int MAX = 12; // 12 animals
const int MAXSTR = 10; 

typedef char * Element;
static Element UniversalSet [MAX] = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon",
"Snake", "Horse", "Sheep", "Monkey", "Rooster", "Dog", "Pig"};

/* Functions */

// Construct a set
void option0(int); // Menu Option 0
void constructSet (Element *, int); // Construct a set
bool checkElement (Element, Element *, int); // Check element for replicates

// This function is to get a random element
// with storage allocated
Element getAnElement ()
{
    Element *p = &UniversalSet [0];
    int k = rand () % MAX;

    for (int i = 0; i < k; i++)
        ++p;

    Element e = new char [MAXSTR];
    strcpy (e, *p);

    return e;
}

int main()
{   
    // Declarations
    int mainSelect;

    int size=rand()%12; // Random construct


    srand (time(NULL)); // Even better randomization

    cout << "Welcome to MARCUS MOO Learning Center" << endl;

    do 
    {
        cout << "0. An example of set" << endl;
        cout << "1. Union" << endl;
        cout << "2. Intersection" << endl;
        cout << "3. Complement" << endl;
        cout << "4. Subset of" << endl;
        cout << "5. Equality" << endl;
        cout << "6. Difference " << endl;
        cout << "7. Distributive Law" << endl;
        cout << "9. Quit" << endl;
        cout << endl;

        if (mainSelect==0)
        {
            option0(size);
        }

        cout << "Your option: ";
        cin >> mainSelect;
        cout << endl;

    } while(mainSelect!=9);

    return 0;
}

/* Functions */

// Option 0 - An example of set
void option0 (int size)
{
    // Mini Declaration
    int again;
    Element *S;

    // You need to assign storage
    S = new Element [MAX];
    for (int i = 0; i < MAX; i++)
        S [i] = new char [MAXSTR];


    do 
    {
        cout << "Here is an example on set of animals" << endl;
        cout << endl;

        // Build set S

        constructSet (S,size);


        // Display set S
        Element *p = &S[0];  // Change to p

        cout << "Set S = {";

        for (int i = 0; i < size; i++)
        {
            if (i!=size-1)
            {
                cout << *p
                     << ", ";
            }
            else 
            {
                cout << *p
                     << "}"
                     << endl;
            }     

            p++;      
        } 


        cout << endl;
        cout << "Note that elements in S are distinct are not in order" << endl;
        cout << endl;

        // Option 0 2nd Part
        cout << "Wish to try the following operations?" << endl;
        cout << "1. Add an element to the set" << endl;
        cout << "2. Check the element in the set" << endl;
        cout << "3. Check the cardinality" << endl;
        cout << "9. Quit" << endl;
        cout << endl; 
        cout << "Your choice: ";
        cin >> again;

    } while (again!=9);   
}

// Construct a set 
void constructSet (Element *set, int size)
{
    // Declarations

    Element *ptrWalk;
    ptrWalk = &set[0];

    int randomA=0;

    Element temp = new char [MAXSTR];

    for (int i = 0;i<size;i++)
    {
        bool found = true;
        while (found) 
        {
           // randomA = rand()%MAX;  ..
            temp = getAnElement ();

            // Ensure no replicated animals in set S
            found = checkElement (temp, set, i);
        }

        // set=ptrWalk;
        // set++;


        strcpy (*ptrWalk, temp);
        ++ptrWalk;         
    }
}

bool checkElement (Element ptrWalk, Element *set, int size)
{
    Element *p = &set[0];

    for (int j=0; j<size;j++)
    {
        if (strcmp (ptrWalk, *p) == 0)
        {
            return true;
        }

        p++;
    }
    return false;
}