0

我正在学习处理数据结构,并且我刚刚编写了一个程序,该程序 Insertion_Sorts 一个整数数组。排序工作得很好,所以没有必要解决它。但我希望为我的用户提供一种在排序数组中搜索特定数字的方法。它不起作用:更具体地说:我已经在 Win7 x64 Ultimate 下的 MS VS 2010 中编译了以下代码,并且在编写“指定要搜索的数字”之后它崩溃了,并且调试器说“访问冲突”。

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <vector>
using namespace std;


int swap(int x, int y)
{
if(x != y)
  {
       _asm
      {
        mov eax,x;
        mov ebx, y;
        mov y,eax;
        mov x, ebx;
      }

  }
return 0;
}

int insertion_sort()
{
int or_size = 2;
int i,j,k,h, size, temp;
char answ;
int xx;
char query [20];


printf("Specify array size\n");
scanf_s("%d", &size);
printf(" Now, input all elements of the array \n");

vector<int> Array(size, 0);
if (size > or_size)
    Array.resize(size);

for (int i = 0; i < size; i++)
{
    scanf_s("%d\n", &temp);
    Array[i] = temp;
}

printf ("Your array appears to be as follows: \n");
for (int i = 0; i < size; i++)
    printf("%d  ", Array[i]);


for (i =0; i < size; i++)
    for (j = 0; j < i; j++)
        if (Array[j] > Array[i])
        {
        temp = Array[j];
        Array[j] = Array[i];
        for (k = i ; k > j ; k-- )
                    Array[k] = Array[k - 1] ;

        Array[k + 1] = temp ;
        }
printf ("\n Your Array has been insertion_sorted and should know look like this: \n");
for (int i = 0; i < size; i++)
    printf("%d ", Array[i]);

printf("\n Would you like to search for a specific value? (Yy/Nn) \n");
answ = _getch();
if (answ == 'Y' || answ == 'y')
{
    printf("Specify number to be searched \n");
    scanf_s("%s", query);
    xx = atoi(query);
    printf("Searching for %d ", query);
    for(h = 0; h < sizeof(Array); h++)
        if (Array.at(h) == xx)
            printf("%d\n", h); 
        else
            printf("No such number was found in a sorted array\n");
}    

Array.clear();

return 0;
}

int main()
{
    insertion_sort();
    return 0;
}

PS忽略_asm部分:它有效,但尚未使用:-)

4

1 回答 1

1

printf("Searching for %d ", query);由于query声明为 的数组char,因此不应使用%d用于打印带符号整数的说明符,更改%d%s或。由于这是 C++,我会使用它。queryxxstd::cout

sizeof(Array)不做你想让它做的事情。改为使用Array.size()

在 C++ 中,您不必在函数的开头声明所有变量。我相信那是 C89 的旧部分。这意味着您可以像这样声明您的 for 循环for(int h = 0; h < Array.size(); h++)

这是尝试在向量中查找某些内容的一个很好的示例:

if(std::find(Array.begin(), Array.end(), xx) != Array.end())
    std::cout << "found" << std::endl;
else
    std::cout << "not found" << std::endl;

您正在混合 C 和 C++ 代码。我建议选择一种语言并仅使用该语言。

于 2012-08-20T03:22:57.593 回答