本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解迭代器模式的动机,掌握该模式的结构;
2、能够利用迭代器模式解决实际问题。
1. 搜集并掌握JAVA和C++中常见的数据结构和迭代器的使用方法,例如,vector, list, map和set等;
Java
PriorityQueue
java
import java.util.PriorityQueue;
// 创建PriorityQueue
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
// 添加元素
priorityQueue.offer(3);
priorityQueue.offer(1);
priorityQueue.offer(2);
// 获取并移除最小元素
int minElement = priorityQueue.poll();
// 遍历(不按顺序)
while (!priorityQueue.isEmpty()) {
int element = priorityQueue.poll();
// 进行操作
}
TreeMap
java
import java.util.TreeMap;
import java.util.Map;
// 创建TreeMap
TreeMap<String, Integer> treeMap = new TreeMap<>();
// 添加键值对
treeMap.put("Apple", 10);
treeMap.put("Orange", 5);
treeMap.put("Banana", 8);
// 获取键值对集合
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
// 进行操作
}
C++
Deque
cpp
#include <deque>
// 创建deque
std::deque<int> myDeque;
// 在开头和末尾添加元素
myDeque.push_front(1);
myDeque.push_back(2);
// 访问首尾元素
int frontElement = myDeque.front();
int backElement = myDeque.back();
// 迭代器遍历
for (std::deque<int>::iterator it = myDeque.begin(); it != myDeque.end(); ++it) {
int value = *it;
// 进行操作
}
// range-based for循环
for (int num : myDeque) {
// 进行操作
}
UnorderedMap
cpp
#include <unordered_map>
// 创建unordered_map
std::unordered_map<std::string, int> myUnorderedMap;
// 添加键值对
myUnorderedMap["One"] = 1;
myUnorderedMap["Two"] = 2;
myUnorderedMap["Three"] = 3;
// 迭代器遍历
for (auto it = myUnorderedMap.begin(); it != myUnorderedMap.end(); ++it) {
std::string key = it->first;
int value = it->second;
// 进行操作
}
// range-based for循环
for (const auto& entry : myUnorderedMap) {
std::string key = entry.first;
int value = entry.second;
// 进行操作
}
2. 提交源代码;
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
struct student
{
string id;
string name;
};
void LoadStudent(vector<student>&);
int main()
{
vector<student> v,v1;
LoadStudent(v);
LoadStudent(v1);
cout<<"学号从小到大:"<<endl;
for (vector<student>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
cout << "学号:" << iter->id << " 姓名:" << iter->name << endl;
}
cout<<"***********************"<<endl;
cout<<"学号从大到小:"<<endl;
for (vector<student>::reverse_iterator iter1 = v.rbegin(); iter1 != v.rend(); ++iter1)
{
cout << "学号:" << iter1->id << " 姓名:" << iter1->name << endl;
}
return 0;
}
void LoadStudent(vector<student>& v)
{
ifstream infile;
infile.open("E:\\student.txt");
student s;
if(!infile) //判断是否存在ifstream infile
{
cout<<"读入文件不存在"<<endl;
}
if (infile.is_open()) //判断文件流是否处于打开状态
{
while (infile.good()&&!infile.eof())
{
infile>>s.id>>s.name;
v.push_back(s); //将数据读入到data_vector
}
}
infile.close();
}