随机数输入425500

时间:2018-04-04 03:42:39

标签: c++

我正在开发一个数组程序,用于在删除重复项后使用数组。

 #include <iostream>
 #include <string>

 using namespace std;

 int main(){

int x;
int y;
int z;
int ArrayLength;
int tempArrayValue;

//prompt for array length
cout << "How many numbers do you want the array to be?" << endl;
cin >> ArrayLength;

//initialize array
int D[ArrayLength];

//Put values into each element of the array
for (int a = 0; a < ArrayLength; a++)
{
    cout << "Enter in Values." <<endl;
    cin >> tempArrayValue;
    D[a] = tempArrayValue;
    cout << endl;
}

//compare each element
for (int x = 0; x < ArrayLength; x++) 
{

    for (int y = x + 1; y < ArrayLength; y++)
    {
             if (D[x] == D[y])  
             {
                D[y] = 0;   
             }    

            //system("PAUSE");

    for (z = 0; z < ArrayLength; z++)
        {
        if (D[z] == 0)
            {
                D[z] = D[z+1];  
                D[z+1] = 0;
                //cout << D[z];     
            }
        }



    }   


}
cout << D[0] << endl << D[1] << endl << D[2] << endl << D[3] << endl << D[4] <<endl << D[5] <<endl;
 } 

我得到了输出:

How many numbers do you want the array to be?
6
Enter in Values.
1

Enter in Values.
1

Enter in Values.
2

Enter in Values.
9

Enter in Values.
4

Enter in Values.
9

1
2
9
4
4255009
0

让我感到困惑的是:那里有多大人在做什么?我认为这九个可能是我输入的最后一个数字,它可以正常取代第一个,但第二个副本存在问题。我理论上它可能是编译器,其他一些编译器,我现在正在使用dev-c ++。

2 个答案:

答案 0 :(得分:1)

D[z+1]可以访问已分配数组的末尾,从而导致未定义的行为。

此外,声明int D[ArrayLength](可变长度数组)是某些编译器支持的非标准扩展,不会在任何地方编译。您应该使用std::vector代替。

答案 1 :(得分:1)

根据您的要求,您可以从中获益。

正如@ 1201ProgramAlarm所述,您正在索引数组的末尾,这是未定义的行为,并且您看到该行为导致的垃圾值

您正在x循环中重新定义yfor。您应该在需要之前和之前声明变量。这将有助于跟踪事情。

正如其他人所说,有些C ++工具可以满足您的要求。也就是说,std::set将允许您维护具有唯一值的容器。

除非您绝对需要,否则您可能不应该使用原始数组。如果您不确定“是否需要”使用std::vector

如果你的目标是使用 C ++ ,那么你应该使用它,不要错过它的功能。

#include <iostream>
#include <set>
#include <vector>

void delete_duplicates(std::vector<int>& A)
{
    // delete the duplicates in A
}

void insertion_sort(std::vector<int>& A)
{
    // sort by insertion, selection, or exchange
}

std::vector<int> get_user_values()
{
    // require user input as before
    // with a small amount of input
    // you can just return a copy of
    // a vector
    std::vector<int> a_copy_of_a_vector;
    return a_copy_of_a_vector;
}

void display_results(const std::vector<int>& A)
{
    for (auto& elem : A)
        std::cout << elem << " ";
    std::cout << '\n';
}

根据您的问题,您希望排序删除重复项。您会发现值得花时间将这些任务分解为 功能

现在,如果您的代码出现问题,您可能会更好地了解要去哪里寻找。

int main()
{
    std::vector<int> user_values = get_user_values();
    insertion_sort(user_values);

    // You may find it easier to delete
    // duplicates from a sorted list.
    delete_duplicates(user_values);

    return 0;
}
相关问题