c++ - 询问用户要在数组中搜索的整数

标签 c++ data-structures

我正在学习处理数据结构,我刚刚编写了一个程序,它对整数数组进行插入排序。 排序工作得很好,所以没有必要解决它。 但我希望为我的用户提供一种在排序数组中搜索特定数字的方法。 它不起作用:更具体地说: 我在 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 部分:它有效,但尚未使用 :-)

最佳答案

printf("Searching for %d ", query);query被声明为 char 的数组, 你不应该使用 %d用于打印有符号整数的说明符,更改 %d%squeryxx .由于这是 C++,我会使用 std::cout虽然。

sizeof(Array)不做你想让它做的事。使用 Array.size()相反。

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

这是尝试在 vector 中查找内容的一个很好的示例:

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

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

关于c++ - 询问用户要在数组中搜索的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12031774/

相关文章:

c++ - "extern string-literal declaration"在函数范围内

c++ - 如何使用 string::find 在一次操作中找到 "+"或 "-"

c++ - C++中包含<xstring>、<cstring>、<string>和<wstring>的区别

algorithm - 反转数组查询

c++ - 创建一个由链接平衡 bst 和双向链表组成的数据结构

java - 查找字符串的超字符串的最快数据结构?

c - 是否存在保留插入顺序的无锁哈希表?

performance - 预处理一组常量字符串以进行二进制搜索

c++ - parent_path()带有或不带有斜杠

c++ - 使用 BoostRegex C++ 的正则表达式