⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pex7_5.cpp

📁 数据结构C++代码,经典代码,受益多多,希望大家多多支持
💻 CPP
字号:
#include <iostream.h>
#include <string.h>
#pragma hdrstop

// declaration of Student and "==" for Student
#include "student.h"

// overload "!=" by comparing student id
int operator!= (Student a, Student b)
{
    return a.studID != b.studID;
}

// fast sequential search
template <class T>
int FastSeqSearch(T A[], int n, T key)
{
    int i = 0, keyindex = -1;		// default is -1 if key not found

    A[n] = key;						// copy key at the end of the list
    while(A[i] != key)              // search for the key
        i++;
    if(i < n)
        keyindex = i;				// found it in the original list
    return keyindex;				// return index or -1
}

// search array of strings for match with string key
int FastSeqSearch(char *list[], int n, char *key)
{
    int i = 0, keyindex = -1;		// default is -1 if key not found
    
	list[n] = key;					// copy key at the end of the list
    while(strcmp(list[i],key) != 0)	// search for string match
    	i++;
    if (i < n)
    	keyindex = i;				// found in original list
    return keyindex;				// return index or -1
}

void main()
{
    // three different array types. note that each array
    // has an extra entry at the end. this space is needed
    // by the fast sequential search
    int     list[11] = {5, 9, 1, 3, 4, 8, 2, 0, 7, 6};
    Student studlist[4] = {{1000, 3.4},{1555, 2.6},{1625, 3.8}};
    char    *strlist[6] = {"zero","one","two","three","four"};
    
    int i, index;
    // this record is used as key to search array studlist
    Student studentKey = {1555, 0};
    
    if ((i = FastSeqSearch(list,10,8)) >= 0)
        cout << "Item 8 is found at index " << i << endl;
    else
		cout << "Item 8 is not found" << endl;
		
    index = FastSeqSearch(studlist, 3, studentKey);     
    cout << "Student 1555 has gpa " << studlist[index].gpa
    	 << endl;

    cout << "String 'two' is at index "
    	 << FastSeqSearch(strlist,5,"two") << endl;
    	 
	if (FastSeqSearch(strlist,5,"six") != -1) 
    	cout << "String 'six' is in the list" << endl;
    else
    	cout << "String 'six' is not in the list" << endl;
}

/*
<Run of Modified Program 7.1>

Item 8 is found at index 5
Student 1555 has gpa 2.6
String 'two' is at index 2
String 'six' is not in the list
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -