CS111 2025 Algorithms Core IO


CS111 2025 Spring Homework 2: 
Task 0 
For this program, the source code files appear in different folders: Algorithms, Core, IO, Utils, and each of them has its own Test folder containing a testing file.
Compare this organization with putting all files in a single folder. 
•Which approach is better for a project with many files, and why? 
•Consider aspects such as maintainability, compilation speed, teamwork, and ease of navigation.
Answer:  
Task 1: Answer the question.
In the Utils folder, you see files with .h, .hpp, .cpp, and .c extensions. Explain the typical use of each extension in a C++ project. When should you use .h vs .hpp, and .cpp vs .c?

Task 2: Answer the question.
In the Utils folder, according to the Makefile, the file c_utils.o (created by the C compiler gcc) will be linked with test_c_util.o (created by the C++ compiler g++). 
•How can this be done successfully? 
•What must be considered in the header files to ensure correct linkage? 

Task 3: Answer the question. 
There are three header files in the Utils folder:
•c_and_cpp_utils.hpp
•c_only_utils.h
•cpp_only_utils.hpp
What are the different intended uses of each file, and why? 
Task 4 
•In bit_stream.hpp, there is a line:
BitStream() = default;
Is this line needed? Why or why not? 
•Consider another similar case, doubly_linked_list.hpp, there is a line:
DoublyLinkedList() = default; 
Is this line needed? Why or why not? 

Task 5
In bit_stream.hpp, there is a line:
size_t size() const noexcept;
•Is the noexcept part proper or helpful here? Why or why not? 
•Discuss the implications of using noexcept regarding performance, correctness, and code design. 

Task 6
In the file, there are two lines: 
class BitProxy; 
BitProxy operator[](size_t index);
Why is the first line (class BitProxy;) needed?
Why does operator[] return a BitProxy object instead of a bool& or bool?
Compare this design to how operator[] works in standard containers like std::vector or arrays.

Task 7
Regarding the design of the BitStream as shown in the file bit_stream.hpp, why not simply use an array of bool to replace it? Explain. 
Regarding the design of the BitStream as shown in the file bit_stream.hpp, why not simply use an array of bool to replace it? Explain.
•Discuss the advantages and disadvantages of using an array of bool versus a BitStream.
•Consider aspects such as memory usage, performance, and practical implementation details, and relevance to the project. 

Task 8
In the file bit_stream.hpp, you will find the following declaration:
std::vector<uint8_t> data;
Suppose we replace uint8_t with char, i.e.,
std::vector<char> data;
•Would this change be appropriate? Why or why not? 
•Discuss the implications of using char instead of uint8_t for storing raw bit data, considering type safety, portability, and clarity.

Task 9
In bit_stream.cpp, consider the function definition of append_internal. 
a.) Explain the meaning of the following code:
 if (byte_index >= data.size()) { 
        data.push_back(0); 
    }
b.) Provide the missing statements in the following code, and briefly explain what your code does:
    if (bit) {
          // code missing
    } else {
         // code missing
    }

Task 10
In the file bit_stream.cpp, in the definition of the function write_to_file, there are two lines:
const uint64_t bit_count = end_pos - start_pos; 
file.write(reinterpret_cast<const char*>(&bit_count), sizeof(bit_count));
Explain these two lines of statements. 

Task 11
In the file bit_stream.cpp, in the function read_from_file, there is a loop to read the bits one by one from the file.
 for (uint8_t byte : buffer) { 
            for (int bit_pos = 7; bit_pos >= 0 && bits_added < bit_count; --bit_pos) { 
                append_internal((byte >> bit_pos) & 1); 
                bits_added++; 
            } 
        }
Is this necessary? Why not simply read a sequence of uint8_t bytes from the file and save them into the BitStream object? Why?

Task 12 
In doubly_linked_list.hpp, there are lines to assign values to members that are not part of a constructor, like:
Node* head = nullptr; 
Node* tail = nullptr; 
size_t len = 0;
What is the meaning of these, and why are these allowed? How does this differ from initializing these members in the constructor’s initializer list?

Task 13 
In doubly_linked_list.hpp, the structure Node is declared in the public section of the class. Compared to another choice, putting this declaration in a private section of the class, what are the advantages and disadvantages of these two choices? Which is better for this project, and why? 

Task 14
In doubly_linked_list.hpp, consider the constructor of Node:
explicit Node(const T&& val) : ... 
What is the meaning of this? When does the method of the DoublyLinkedList class call this constructor of Node? 

Task 15
In doubly_linked_list.hpp, in the function link_node, the code part for inserting a new node before an existing node is missing. Provide the missing code.
•You can put it in both places, here in this report file, and in the missing-code place in doubly_linked_list.hpp. 

Task 16 
In doubly_linked_list, there is a template function:
template<typename U>  
  void insert_back(U&& value) {
      link_node(new Node(std::forward<U>(value)), tail, false);
  }
What is the meaning of calling the forward function here?

Task 17 
Since the insert_back function appears in the template class DoublyLinkedList, it is automatically a template function. So, maybe the template type name can be ignored and shared with the template type name T of the class. Then, can we use the following function? Why? 
  void insert_back(T&& value) {
      link_node(new Node(std::forward<T>(value)), tail, false);
  }

Task 18
How about writing the insert_back function as follows:
  template <typename T>
  void insert_back(T&& value) {
      link_node(new Node(std::forward<T>(value)), tail, false);
  }
Is it ok? Why? 

Task 19
In the file linked_list_and_priority_queue_tests.cpp, we see a range-based for loop: 
for (auto& item : list) {
        forward.push_back(item);
        std::cout << item << " " << "pushed back" << " forwardly " <<std::endl;
}
Here list is an object of the DoublyLinkedList class. Why is the range-based for loop supported here?
Alternatively, for a class X to support range-based for loop, what are the requirements of X?

Task 20
In doubly_linked_list.hpp, inside the iterator class, 
there is a statement: 
using iterator_category = std::bidirectional_iterator_tag;
Which header file is needed for this statement? 
How about a typedef in this line, like:
typedef std::bidirectional_iterator_tag iterator_category ; 
Which is better, and why? 

Task 21
The type alias iterator_category, which is defined in doubly_linked_list.hpp, is not used in the program. Why is it needed or useful? 

Task 22 
In the file priority_queue.hpp, the template class PriorityQueue is declared as follows:
template < 
    typename T, 
    typename Compare = std::greater<T>, 
    //template <typename, typename> class Container = VectorHeapContainer 
    // Use the VectorHeapContainer for faster performance.  
    template <typename, typename> class Container = OrderedLinkedListContainer 

class PriorityQueue { 
    //... 
};
By observing this code snippet, we should have learned something. Answer the following questions: 
•When a template class has a template parameter that is also another template class, how do you express the code?
•How do you specify the default choice of a template parameter?

Task 23
In priority_queue.hpp, by observing, the PriorityQueue class can use any template class that satisfies some specific requirements, working as the container. Briefly describe what these requirements are. 

Task 24
The requirements for a possible container class are similar to the concepts of interface and the is-a relationship, which the public inheritance mechanism can describe. 
Sketch some design: a Container class that describes these requirements, so that any derived class of the Container class can be used by the PriorityQueue, which is adjusted accordingly. 
Bonus Points if the adjusted program can compile and run correctly. 

Task 25
In priority_queue.hpp, in the class OrderedLinkedListContainer, in the insert function, there is a statement.
static_assert(
            std::is_convertible<typename std::decay<U>::type, T>::value, // C++11 syntax
            "calling OrderedLinkedListContainer::insert() with data of type U. Type U must be implicitly convertible to T");
What is the meaning of this statement? Explain in terms of the usage of:
•is_convertible
•std::decay
•and std::static_assert; 
Is it similar to some validation function defined in this program? What are the differences? 
Task 26
In the file priority_queue.hpp, inside the class OrderedLinkedListcontainer, in the insert function, there is a statement missing, which is to locate the iterator it to the first place where the value is larger than the data of it or it reaches the end. 
Provide the missing code (write the code here and in the . hpp file)

Task 27 
In doubly_linked_list.hpp, in the class DoublyLinkedList, there are two iterator classes, iterator and const_iterator, defining the same overloaded operators. Why do we need these iterator classes ? Alternatively, asking, what would happen if only one iterator type were provided?

Task 28
In doubly_linked_list.hpp, the arrow operator -> will return a pointer. Explain how it works. Alternatively, explain, given the following sketch of statements:
iterator it = ...;
it->some_member; 
What is an expression equivalent to it->some_member? 

Task 29
The -- operator has a prefix version and a postfix version. How are the two operator functions declared differently, as shown in doubly_linked_list.hpp? A similar mechanism can overload the ++ operators. 

Task 30
In the file link_list_and_priority_queue_tests.cpp. Two macros, TEST_FUNCTION and END_TEST, are defined. Some tests are carried out and the number of passing and failure are recorded. This mechanism is similarly used in the huffman_tests.cpp in the Algorithms folder. Describe this pattern of writing and testing code. What is the advantage of doing so? 

Task 31:
In the file IO/Bit_stream/bit_stream.hpp
For the class BitStream, we observe that the BitProxy class has no copy constructor or copy assignment. 
•Is defining these special methods (with copy semantics) problematic for this class? Why? 
•If we want to turn off using these methods for this class explicitly, how do we do it? 
–Discuss the legacy way and/or a modern C++ way.

Task 32:
In the file huffman_tree.hpp. The two concrete classes LeafNode and InternalNode share the same base class Node. What are the advantages and usefulness of this design? Consider the print_huffman_tree function defined in the huffman_tree.cpp as an example for the explanation. 

Task 33:
In huffman_tree.hpp, in the classInternalNode, its two members left and right are unique pointers: 
const std::unique_ptr<HuffmanNode> left;
const std::unique_ptr<HuffmanNode> right;
Why are these unique pointers proper? Comparing using raw pointers for left and right, what are the advantages/disadvantages? 

Task 34:
In huffman_tree.cpp, in the print_huffman_tree definition, the code in the else block is missing, which should handle the recursive case of the function. It will print the left subtree, the internal node (the root of the subtree), and the right subtree. Provide the missing code. 
•Write missing statements in the .cpp file, and also paste them here. 

Task 35:
In huffman_algorithm.cpp, in the function string_to_frequence_map, a part is missing, which is to compute the count of each character in a string text. 
Provide the missing code in the .cpp file and paste the lines here in this report file. 

Task 36:
In huffman_tree.cpp, in the constructor of HuffmanTree, which builds a tree based on a frequency map (the parameter), there are missing parts of code. 
•Provide code for both (a) inserting leaf nodes into the priority queue and (b) combining nodes to build the tree.
–The comments in the file are helpful.
–Put the missing code in the .cpp file and here in the report document.
•Explain in Part (b) why is needed when combining nodes?

Task 37:
In huffman_algorithm.cpp, in the function buildwere_table, why need to handle the special case that, if the prefix is empty, push afalseinto theprefix`? What would happen if this special case was not handled?

Task 38:
In huffman_algorithm.cpp, for the class HuffmanEncoder, the body is missing for the method encod. Write the missing code of the body. 
•Hint: The comments in the function are helpful. 
•Paste the code in the .cpp file and also here in this report file. 

Task 39:
In huffman_algorithm.cpp, for the class HuffmanDecoder, the method decode, a loop is missing. Provide the missing code. 
•Hint: the comments in the function are helpful. 
•Paste the code in the .cpp file and also here in this report file. 

Task 40:
Based on your code, 
•During the encoding process, what will happen if there is a character in the string that is not in a leaf of the tree, therefore is not included in the encoding table? 
•Any idea to solve the problem? 
•Bonus , modify the code so that this problem be solved. 

Task 41:
In huffman_tree.cpp, in the constructor of HuffmanTree, we see a line:
PriorityQueue<std::unique_ptr<HuffmanNode>, CompareNodes> pq;
So, the HuffmanTree object will always choose the default container choice of PriorityQueue. That is, there is no way to have two HuffmanTree objects simultaneously using different containers for their PriorityQueue.
How can the HuffmanTree declaration be modified so that different kinds of containers can possibly be used? Describe your idea.
Bonus: Compile and test the modified code. 

Task 42
Based on a Makefile that you possibly want to use, explain the meaning of the following two rules: 
1.
bit_stream.o: ../../IO/Bit_stream/bit_stream.cpp
    $(CXX) $(CXXFLAGS) -c $< -o $@
1.
bit_stream_tests: bit_stream_tests.o bit_stream.o
    $(CXX) $(CXXFLAGS) -o $@ $^
1.
all_exe: huffman_tests linked_list_and_priority_queue_tests \
         bit_stream_tests c_utils_tests
4.
clean_o:
    rm -f *.o

Task 43: Compilation and Execution 
•Compile the program using the provided Makefile for your OS (Linux/MAC/Windows). 
•Run and test all your generated executable files. 
–If there are some errors and you can not fix them, describe the errors here. 
Deliverable: 
a) Paste a screenshot of your terminal showing: 
•Simply type your name, and the terminal will ignore it as a wrong command 
•The compilation command that uses a Makefile. 
–You may use make or mingw32-make. 
Paste the image in this report. 
A sample screenshot could show something like: 
  \Huffman_code_program\Build\Windows_g++> my name is LI, BAI
'my' is not recognized as an internal or external command,
operable program or batch file.

\Huffman_code_program\Build\Windows_g++> mingw32-make
g++ -c ../../IO/Bit_stream/bit_stream.cpp -o bit_stream.o
g++ -o bit_stream_tests bit_stream_tests.o bit_stream.o
...
b) a screen shot of running an exectuable file. Paste the image in this report. 
c) [optional]: redirect output to a file, like: 
\Huffman_code_program\Build\Windows_g++>huffman_tests.exe > huffman_tests_output.txt
 Upload test ouptut .txt files together with the report file. 

Task 44
[optional]
Describe any other extra work that worth bonus points. 

Task 45
Summarize your experience, what you have learned in this project. You may think in the aspects like: 
•The specific C++ features you found valuable: design patterns, skills of debugging, testing and compiling skills ... 
•How will this experience help you in future programming projects? 
•How this project can assist a future Data Structure and algorithm course? Submission Instructions: 
Submit the folloing files: 
1.The completed report file (Word/PDF) with answers 
2.A .zip file made by compressing the whole program folder, which contain all subfolders as distributed by this homework. The folder should contain all your modified program files. 
3.Other supporting files, like
•the executing output recording files. 

1. Vision.Data.Models.dll - 数据模型和接口 text Vision.Data.Models.dll/ ├── Models/ # 数据模型类 │ ├── InspectionResult.cs # 检测结果模型 │ ├── CameraInfo.cs # 相机信息模型 │ ├── Recipe.cs # 检测配方模型 │ ├── SystemConfig.cs # 系统配置模型 │ ├── AlgorithmResult.cs # 算法结果模型 │ ├── DeviceStatus.cs # 设备状态模型 │ └── LogEntry.cs # 日志条目模型 │ ├── Interfaces/ # 接口定义 │ ├── IVisionAlgorithm.cs # 算法通用接口 │ ├── ILogger.cs # ✅ 日志接口 │ ├── IConfigurable.cs # 可配置接口 │ ├── IInitializable.cs # 可初始化接口 │ └── IDisposableResource.cs # 资源释放接口 │ ├── Enums/ # 枚举定义 │ ├── DeviceType.cs # 设备类型枚举 │ ├── InspectionStatus.cs # 检测状态枚举 │ ├── ErrorCodes.cs # 错误代码枚举 │ ├── TriggerMode.cs # 触发模式枚举 │ └── LogLevel.cs # ✅ 日志级别枚举 │ └── Events/ # 事件参数 ├── ImageGrabbedEventArgs.cs # 图像采集事件 ├── InspectionCompletedEventArgs.cs # 检测完成事件 └── DeviceStatusChangedEventArgs.cs # 设备状态变化事件 2. Vision.Device.Interfaces.dll - 设备驱动接口 text Vision.Device.Interfaces.dll/ ├── Camera/ # 相机接口 │ ├── ICamera.cs # 相机主接口 │ ├── ICameraInfo.cs # 相机信息接口 │ └── ICameraAsync.cs # 相机异步接口 │ ├── Light/ # 光源接口 │ ├── ILightController.cs # 光源控制器接口 │ └── ISerialLight.cs # 串口光源接口 │ ├── IO/ # IO接口 │ ├── IIOController.cs # IO控制器接口 │ └── ICommunication.cs # 通信接口 │ ├── Common/ # 通用设备接口 │ ├── IDevice.cs # 设备基础接口 │ ├── IConnectable.cs # 可连接接口 │ ├── IConfigurableDevice.cs # 可配置设备接口 │ └── IDeviceStatus.cs # 设备状态接口 │ └── Exceptions/ # 异常类 ├── DeviceException.cs # 设备异常基类 ├── CameraException.cs # 相机异常 └── ConnectionException.cs # 连接异常 3. Vision.Core.dll - 核心引擎(包含日志实现) text Vision.Core.dll/ ├── Engine/ # 引擎核心 │ ├── VisionEngine.cs # 视觉引擎主类 │ ├── DeviceManager.cs # 设备管理器 │ └── AlgorithmExecutor.cs # 算法执行器 │ ├── Services/ # 核心服务 │ ├── ConfigManager.cs # 配置管理服务 │ ├── RecipeManager.cs # 配方管理服务 │ ├── InspectionService.cs # 检测流程服务 │ └── DataService.cs # 数据服务 │ ├── Utilities/ # 工具类(✅包含日志实现) │ ├── Logger.cs # ✅ 日志系统实现 │ ├── FileLogWriter.cs # ✅ 文件日志写入器 │ ├── ConsoleLogWriter.cs # ✅ 控制台日志写入器 │ ├── PluginLoader.cs # 插件加载器 │ ├── ImageHelper.cs # 图像工具类 │ └── ExtensionMethods.cs # 扩展方法 │ └── Events/ # 事件处理 ├── VisionEventArgs.cs # 事件参数基类 ├── DeviceEventArgs.cs # 设备事件参数 └── InspectionEventArgs.cs # 检测事件参数 4. 设备驱动DLL结构 Vision.Device.Camera.Hik.dll - 海康相机 text Vision.Device.Camera.Hik.dll/ ├── HikCamera.cs # 海康相机实现类 ├── HikCameraInfo.cs # 海康相机信息类 ├── HikSDKWrapper.cs # 海康SDK封装类 └── HikConstants.cs # 海康常量定义 Vision.Device.Camera.HalconGeneric.dll - Halcon通用相机 text Vision.Device.Camera.HalconGeneric.dll/ ├── HalconGenericCamera.cs # Halcon通用相机实现 ├── HalconAcquisition.cs # Halcon采集封装 ├── CameraDiscoverer.cs # 相机发现类 └── HalconConversion.cs # Halcon转换工具 Vision.Device.Light.Serial.dll - 串口光源 text Vision.Device.Light.Serial.dll/ ├── SerialLightController.cs # 串口光源控制器 ├── LightProtocol.cs # 光源通信协议 ├── CommandBuilder.cs # 命令构建器 └── SerialPortManager.cs # 串口管理 5. 算法模块DLL结构 Vision.Algorithms.Base.dll - 基础算法 text Vision.Algorithms.Base.dll/ ├── BasicAlgorithms.cs # 基础算法主类 ├── ImageProcessing/ # 图像处理算法 │ ├── ThresholdAlgorithm.cs # 二值化算法 │ ├── FilterAlgorithm.cs # 滤波算法 │ └── MorphologyAlgorithm.cs # 形态学算法 │ ├── Measurement/ # 测量算法 │ ├── EdgeDetection.cs # 边缘检测 │ ├── CaliperTool.cs # 卡尺工具 │ └── CircleFitting.cs # 圆拟合 │ ├── Recognition/ # 识别算法 │ ├── BarcodeReader.cs # 条码识别 │ ├── QRCodeReader.cs # 二维码识别 │ └── OCRBasic.cs # 基础OCR │ └── Analysis/ # 分析算法 ├── BlobAnalyzer.cs # 斑点分析 ├── ColorAnalysis.cs # 颜色分析 └── StatisticalAnalysis.cs # 统计分析 Vision.Algorithms.Advanced.dll - 高级算法接口 text Vision.Algorithms.Advanced.dll/ ├── Interfaces/ # 高级算法接口 │ ├── IAdvancedAlgorithm.cs # 高级算法接口 │ ├── ITrainableAlgorithm.cs # 可训练算法接口 │ └── IModelBasedAlgorithm.cs # 基于模型的算法接口 │ ├── Models/ # 算法模型 │ ├── AlgorithmParameters.cs # 算法参数模型 │ ├── TrainingData.cs # 训练数据模型 │ └── ModelInfo.cs # 模型信息 │ ├── Management/ # 算法管理 │ ├── AlgorithmExecutor.cs # 算法执行器 │ ├── PluginManager.cs # 插件管理器 │ └── ModelManager.cs # 模型管理器 │ └── Utilities/ # 算法工具 ├── AlgorithmHelper.cs # 算法工具类 ├── ValidationHelper.cs # 验证工具类 └── PerformanceMonitor.cs # 性能监控 这样看呢
11-07
VisionPlatform/ │ ├── src/ ← 源码根目录 │ │ │ ├── Vision.Core/ ← 【必须】核心库(数据结构、日志、工具) │ │ └── Vision.Core.csproj │ │ │ ├── Vision.Hardware/ ← 【必须】硬件抽象层 │ │ ├── Camera/ ← 相机相关 │ │ │ ├── ICamera.cs │ │ │ └── TriggerMode.cs │ │ ├── Light/ ← 光源控制(预留) │ │ │ └── ILightController.cs │ │ └── IO/ ← IO 控制(预留) │ │ └── IDigitalIO.cs │ │ │ ├── Vision.Algorithm/ ← 【必须】算法接入层 │ │ ├── IAlgorithm.cs │ │ ├── AlgorithmResult.cs │ │ └── Preprocessing/ ← 预处理算法(去噪、增强等) │ │ └── Inspection/ ← 检测类算法(定位、测量、缺陷) │ │ │ ├── Vision.Job/ ← 【推荐】任务流程引擎 │ │ ├── VisionJob.cs │ │ ├── JobResult.cs │ │ └── JobStep.cs ← 支持多步骤流程(如:拍照→定位→测量) │ │ │ ├── Vision.UI.Controls/ ← 【推荐】UI 控件库 │ │ ├── CameraViewControl.cs ← 图像显示 │ │ ├── ParameterPanel.cs ← 参数配置面板(动态生成) │ │ └── StatusStripEx.cs ← 状态栏增强控件 │ │ │ └── Vision.Common.Services/ ← 【新增】公共服务(可选) │ ├── LoggerService.cs ← 日志服务 │ ├── ConfigService.cs ← 配置管理 │ └── PluginLoader.cs ← 插件加载器 │ ├── Plugins/ ← 外部插件(编译后复制到这里) │ ├── Cameras/ ← 所有相机实现 │ │ ├── Vision.Camera.Mock.dll │ │ ├── Vision.Camera.Hikvision.dll │ │ └── Vision.Camera.Basler.dll │ │ │ ├── Algorithms/ ← 所有算法实现 │ │ ├── Vision.Algorithm.TemplateMatch.dll │ │ ├── Vision.Algorithm.DefectDetect.dll │ │ └── Vision.Algorithm.OCR.dll │ │ │ └── Devices/ ← 其他设备(光源、运动控制器等) │ ├── Vision.Device.SentechLight.dll │ └── Vision.Device.StepperMotor.dll │ ├── HostApps/ ← 主程序(可多个) │ ├── VisionApp.Standalone.exe ← 单机版 │ ├── VisionApp.Client.exe ← 客户端(对接MES) │ └── VisionApp.Simulator.exe ← 测试仿真工具 │ └── docs/ ← 文档(建议保留) └── Architecture.md ← 架构说明文档 这个框架的环境和软件都已配置安装好。接下来要做那部分
10-30
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值