💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
无序表搜索就是一个个的遍历, 从头开始逐个检查, 直到表中关键字值等于给定关键字值, 则查找成功. 或者查完整个表, 查找失败为止. 搜索失败的平均搜索长度:(n + 1) / 2. 实现代码: ~~~ #include "iostream" #include "cstdio" #include "cstring" #include "algorithm" #include "assert.h" using namespace std; enum ResultCode { Underflow, Overflow, Success, Duplicate, NotPresent }; template <class T> class DynamicSet { public: virtual ResultCode Search(T &x) const = 0; // 表中搜索与x关键字相同的元素, 若存在则赋值给x并且返回Success, 否则返回NotPresent virtual ResultCode Insert(T &x) = 0; // 表中搜索与x关键字相同的元素, 若存在该元素, 赋值给x返回Duplicate, 若表已满返回Overflow, 若表未满返回Success virtual ResultCode Remove(T &x) = 0; // 表中搜索与x关键字相同的元素, 若存在该元素, 赋值给x返回Success, 否则返回NotPresent virtual bool IsEmpty() const = 0; // 集合为空返回true virtual bool IsFull() const = 0; // 集合为满返回true /* data */ }; template <class T> class ListSet: public DynamicSet<T> { public: ListSet( int mSize ); ~ListSet() { delete []l; } bool IsEmpty() const { return n == 0; } bool IsFull() const { return n == maxSize; } ResultCode Search(T &x) const; ResultCode Insert(T &x); ResultCode Remove(T &x); void Print(); private: T *l; int maxSize, n; /* data */ }; template <class T> void ListSet<T>::Print() { for(int i = 0; i < n; ++i) cout << l[i] << "\t"; cout << endl; } template <class T> ListSet<T>::ListSet(int mSize) { maxSize = mSize; l = new T[maxSize]; n = 0; } template <class T> ResultCode ListSet<T>::Insert(T &x) { assert(!IsFull()); l[n++] = x; return Success; } template <class T> ResultCode ListSet<T>::Remove(T &x) { } template <class T> ResultCode ListSet<T>::Search(T &x) const { for(int i = 0; i < n; ++i) if(l[i] == x) { x = l[i]; return Success; } return NotPresent; } int main(int argc, char const *argv[]) { ListSet<int> ls(20); int x = 34; ls.Insert(x); x = 88; ls.Insert(x); x = 77; ls.Insert(x); x = 55; ls.Insert(x); x = 44; ls.Insert(x); x = 100; ls.Insert(x); ls.Print(); x = 88; if(ls.Search(x) == Success) cout << "Found " << x << endl; return 0; } ~~~