[实验任务一]:JAVA和C++常见数据结构迭代器的使用
信1305班共44名同学,每名同学都有姓名,学号和年龄等属性,分别使用JAVA内置迭代器和C++中标准模板库(STL)实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。
实验要求:
- 搜集并掌握JAVA和C++中常见的数据结构和迭代器的使用方法,例如,vector, list, map和set等;
- 提交源代码;
- 注意编程规范。
`JAVA
(1)List 是一个有序集合,允许重复的元素。在 Java 中常用的 List 实现包括 ArrayList 和 LinkedList。
ArrayList:底层使用动态数组实现,支持快速随机访问。
LinkedList:底层使用双向链表实现,适合频繁插入和删除元素。
实现方法:import java.util.*;
public class ListExample {
public static void main(String[] args) {// 使用 ArrayList 实现 ListList<String> list = new ArrayList<>();list.add("Java");list.add("C++");list.add("Python");// 迭代器遍历Iterator<String> iterator = list.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}// 使用 LinkedListList<Integer> linkedList = new LinkedList<>();linkedList.add(1);linkedList.add(2);linkedList.add(3);// 增强 for 循环遍历for (Integer number : linkedList) {System.out.println(number);}}
}
(2)Set 是一个无序集合,不允许重复元素。在 Java 中常用的 Set 实现包括 HashSet 和 TreeSet。
HashSet:底层使用哈希表实现,元素是无序的。
TreeSet:底层使用红黑树实现,元素会自动按升序排序。
实现方法:import java.util.*;
public class SetExample {
public static void main(String[] args) {// 使用 HashSet 实现 SetSet<String> set = new HashSet<>();set.add("Java");set.add("C++");set.add("Python");// 迭代器遍历Iterator<String> iterator = set.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}// 使用 TreeSetSet<Integer> treeSet = new TreeSet<>();treeSet.add(3);treeSet.add(1);treeSet.add(2);// 增强 for 循环遍历for (Integer number : treeSet) {System.out.println(number);}}
}
(3)Map 是一个键值对集合,不允许重复的键。在 Java 中常用的 Map 实现包括 HashMap 和 TreeMap。
HashMap:底层使用哈希表实现,键值对无序。
TreeMap:底层使用红黑树实现,键按升序排序。
实现方法:import java.util.*;
public class MapExample {
public static void main(String[] args) {// 使用 HashMap 实现 MapMap<Integer, String> map = new HashMap<>();map.put(1, "Java");map.put(2, "C++");map.put(3, "Python");// 通过键遍历for (Map.Entry<Integer, String> entry : map.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());}// 使用 TreeMapMap<Integer, String> treeMap = new TreeMap<>();treeMap.put(3, "Java");treeMap.put(1, "C++");treeMap.put(2, "Python");// 遍历for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());}}
}
C++
(1)vector 是一个动态数组,支持快速随机访问,元素按插入顺序排列。
实现方法:#include
include
using namespace std;
int main() {
vector<string> vec = {"Java", "C++", "Python"};// 迭代器遍历for (vector<string>::iterator it = vec.begin(); it != vec.end(); ++it) {cout << *it << endl;}// 增强 for 循环遍历for (const auto& str : vec) {cout << str << endl;}return 0;
}
(2)list 是双向链表实现的容器,适用于频繁的插入和删除操作。
实现方法:#include
include
using namespace std;
int main() {
list<int> myList = {1, 2, 3, 4, 5};// 迭代器遍历for (list<int>::iterator it = myList.begin(); it != myList.end(); ++it) {cout << *it << " ";}cout << endl;// 增强 for 循环遍历for (const auto& num : myList) {cout << num << " ";}cout << endl;return 0;
}
(3)set 是一个不允许重复元素的集合,元素按升序排列。
实现方法:#include
include
using namespace std;
int main() {
set<string> mySet = {"Java", "C++", "Python"};// 迭代器遍历for (set<string>::iterator it = mySet.begin(); it != mySet.end(); ++it) {cout << *it << endl;}// 增强 for 循环遍历for (const auto& str : mySet) {cout << str << endl;}return 0;
}
(4)map 是一个有序的键值对集合,键不重复。
实现方法:#include
include
using namespace std;
int main() {
map<int, string> myMap = {{1, "Java"}, {2, "C++"}, {3, "Python"}};// 迭代器遍历for (map<int, string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {cout << it->first << ": " << it->second << endl;}// 增强 for 循环遍历for (const auto& entry : myMap) {cout << entry.first << ": " << entry.second << endl;}return 0;
}
2、源代码
C++
include
include
include
using namespace std;
class Student{
public:
long studentid;
string name;
int age;
string major;
public:
Student(long studentid, string name, int age, string major) {
this->studentid = studentid;
this->name = name;
this->age = age;
this->major = major;
}
void show(){
cout<<"姓名: "<
}
};
bool compMax(Student *a,Student *b){
if (a->studentid> b->studentid)
return true;
else
return false;
}
bool compMin(Student *a,Student *b){
if (a->studentid< b->studentid)
return true;
else
return false;
}
int main(){
Student s1 = new Student(20223794, "袁", 20, "软工");
Student s2 = new Student(20224056, "高", 21, "软工");
Student s3 = new Student(20223782, "艾", 21, "软工");
Student s4 = new Student(20223695, "万", 20, "软工");
vector<Student> vec;
vec.push_back(s1);
vec.push_back(s2);
vec.push_back(s3);
vec.push_back(s4);
cout<<"按照学号从大到小输出: "<<endl;
vector<Student>::iterator it;
sort(vec.begin(), vec.end(),compMax);
for(it=vec.begin();it!=vec.end();it++){
(it)->show();
}
cout<<"-----------------------------------------------------------------"<<endl;
cout<<"按照学号从小到大输出: "<<endl;
sort(vec.begin(), vec.end(),compMin);
for(it=vec.begin();it!=vec.end();it++){
(it)->show();
}
}
JAVA
package org.example;
class Student {
String name;
int studentId;
int age;
String major; // 添加专业属性
public Student(String name, int studentId, int age, String major) {this.name = name;this.studentId = studentId;this.age = age;this.major = major; // 初始化专业
}@Override
public String toString() {return "姓名: " + name + ", 学号: " + studentId + ", 年龄: " + age + ", 专业: " + major;
}
}
package org.example;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class StudentIterator {
public static void main(String[] args) {
List
// 创建学生对象时添加专业
students.add(new Student("袁", 20223794, 20, "软工"));
students.add(new Student("高", 20224056, 21, "软工"));
students.add(new Student("艾", 20223782, 21, "软工"));
students.add(new Student("万", 20223695, 20, "软工"));
// 按学号从小到大排序students.sort(Comparator.comparingInt(s -> s.studentId));System.out.println("按学号从小到大排序:");Iterator<Student> iterator = students.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}// 按学号从大到小排序students.sort((s1, s2) -> Integer.compare(s2.studentId, s1.studentId));System.out.println("\n按学号从大到小排序:");iterator = students.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}
}
}`
[实验任务一]:解释器模式
某机器人控制程序包含一些简单的英文指令,其文法规则如下:
expression ::= direction action distance | composite
composite ::= expression and expression
direction ::= ‘up’ | ‘down’ | ‘left’ | ‘right’
action ::= ‘move’ | ‘run’
distance ::= an integer //一个整数值
如输入:up move 5,则输出“向上移动5个单位”;输入:down run 10 and left move 20,则输出“向下移动10个单位再向左移动20个单位”。
实验要求:
- 提交类图;
- 提交源代码;
- 注意编程规范。
import java.util.Stack;
public abstract class AbstractNode {
public abstract String interpret();
}
public class ActionNode extends AbstractNode{
private String action;
public ActionNode(String action) {
this.action = action;
}
//动作(移动方式)表达式的解释操作
public String interpret() {
if (action.equalsIgnoreCase("move")) {
return "移动";
}
else if (action.equalsIgnoreCase("run")) {
return "快速移动";
}
else {
return "无效指令";
}
}
}
public class AndNode extends AbstractNode{
private AbstractNode left; //And的左表达式
private AbstractNode right; //And的右表达式
public AndNode(AbstractNode left, AbstractNode right) {
this.left = left;
this.right = right;
}
//And表达式解释操作
public String interpret() {
return left.interpret() + "再" + right.interpret();
}
}
public class DirectionNode extends AbstractNode{
private String direction;
public DirectionNode(String direction) {
this.direction = direction;
}
//方向表达式的解释操作
public String interpret() {
if (direction.equalsIgnoreCase("up")) {
return "向上";
}
else if (direction.equalsIgnoreCase("down")) {
return "向下";
}
else if (direction.equalsIgnoreCase("left")) {
return "向左";
}
else if (direction.equalsIgnoreCase("right")) {
return "向右";
}
else {
return "无效指令";
}
}
}
public class DistanceNode extends AbstractNode{
private String distance;
public DistanceNode(String distance) {
this.distance = distance;
}
//距离表达式的解释操作
public String interpret() {
return this.distance;
}
}
public class InstructionHandler {
private String instruction;
private AbstractNode node;
public void handle(String instruction) {
AbstractNode left = null, right = null;
AbstractNode direction = null, action = null, distance = null;
Stack stack = new Stack(); //声明一个栈对象用于存储抽象语法树
String[] words = instruction.split(" "); //以空格分隔指令字符串
for (int i = 0; i < words.length; i++) {
//本实例采用栈的方式来处理指令,如果遇到“and”,则将其后的三个单词作为三个终结符表达式连成一个简单句子SentenceNode作为“and”的右表达式,而将从栈顶弹出的表达式作为“and”的左表达式,最后将新的“and”表达式压入栈中。
if (words[i].equalsIgnoreCase("and")) {
left = (AbstractNode)stack.pop(); //弹出栈顶表达式作为左表达式
String word1= words[++i];
direction = new DirectionNode(word1);
String word2 = words[++i];
action = new ActionNode(word2);
String word3 = words[++i];
distance = new DistanceNode(word3);
right = new SentenceNode(direction,action,distance); //右表达式
stack.push(new AndNode(left,right)); //将新表达式压入栈中
}
//如果是从头开始进行解释,则将前三个单词组成一个简单句子SentenceNode并将该句子压入栈中
else {
String word1 = words[i];
direction = new DirectionNode(word1);
String word2 = words[++i];
action = new ActionNode(word2);
String word3 = words[++i];
distance = new DistanceNode(word3);
left = new SentenceNode(direction,action,distance);
stack.push(left); //将新表达式压入栈中
}
}
this.node = (AbstractNode)stack.pop(); //将全部表达式从栈中弹出
}
public String output() {
String result = node.interpret(); //解释表达式
return result;
}
}
public class SentenceNode extends AbstractNode{
private AbstractNode direction;
private AbstractNode action;
private AbstractNode distance;
public SentenceNode(AbstractNode direction,AbstractNode action,AbstractNode distance) {
this.direction = direction;
this.action = action;
this.distance = distance;
}
//简单句子的解释操作
public String interpret() {
return direction.interpret() + action.interpret() + distance.interpret();
}
}
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
String instruction1 = "up move 5 and down run 10 and left move 5";
String instruction2="down run 10 and left move 20";
InstructionHandler handler = new InstructionHandler();
handler.handle(instruction1);
String outString;
outString = handler.output();
System.out.println(outString);
handler.handle(instruction2);
outString = handler.output();
System.out.println(outString);
}
}