test1
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
cmake_minimum_required(VERSION 3.30)
|
||||
project(homework6)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
|
||||
add_executable(test1 test1.cpp)
|
||||
@@ -0,0 +1,38 @@
|
||||
// 编写一个程序,输出在顺序表(3,6,2,10,l,8,5,7,4,9) 中采用顺序查找方法查找关键字5的过程。
|
||||
#include <list>
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
template <typename T>
|
||||
int seqSearch(list<T> l,T value) {
|
||||
if (l.empty()) {
|
||||
cout << "空表" << endl;
|
||||
return -1;
|
||||
}
|
||||
bool found = false;
|
||||
int index = 0;
|
||||
for (typename list<T>::iterator it = l.begin(); it != l.end(); ++it) {
|
||||
cout<<"正在顺序查找第"<<index<<"位元素"<<"其值为"<<*it<<endl;
|
||||
|
||||
if (*it == value) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
cout<<"未查找到:"<<value<<endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
cout<<"查找次数:"<<index+1<<endl;
|
||||
return index;
|
||||
}
|
||||
|
||||
int main() {
|
||||
list<int> l={3,6,2,10,'l',8,5,7,4,9};
|
||||
int index=seqSearch(l,5);
|
||||
cout<<index<<endl;
|
||||
}
|
||||
Reference in New Issue
Block a user