帮我编写一份C++代码,满足文件要求
时间: 2024-12-19 19:23:39 浏览: 10
好的,我将为你提供两个任务的完整代码实现:
### Task 1: `myString.h`
```cpp
#ifndef MYSTRING_H
#define MYSTRING_H
#include <cstddef>
#include <stdexcept>
class myString {
private:
size_t m_len;
char m_str[257];
public:
// Default constructor
myString() : m_len(0) {
m_str[0] = '\0';
}
// Parameterized constructor
myString(const char* str) {
m_len = 0;
while (str[m_len] != '\0' && m_len < 256) {
m_str[m_len] = str[m_len];
++m_len;
}
m_str[m_len] = '\0';
}
// Length of the string
size_t len() const {
return m_len;
}
// Substring
myString substr(size_t begin, size_t len) const {
if (begin >= m_len || begin + len > m_len) {
return myString();
}
char temp[len + 1];
for (size_t i = 0; i < len; ++i) {
temp[i] = m_str[begin + i];
}
temp[len] = '\0';
return myString(temp);
}
// Access a character
char& at(size_t index) {
if (index >= m_len) {
throw std::out_of_range("Index out of range");
}
return m_str[index];
}
// Convert to upper case
myString to_upper() const {
char temp[m_len + 1];
for (size_t i = 0; i < m_len; ++i) {
temp[i] = toupper(m_str[i]);
}
temp[m_len] = '\0';
return myString(temp);
}
// Convert to lower case
myString to_lower() const {
char temp[m_len + 1];
for (size_t i = 0; i < m_len; ++i) {
temp[i] = tolower(m_str[i]);
}
temp[m_len] = '\0';
return myString(temp);
}
// Get content
const char* get_content() const {
return m_str;
}
// Find substring
size_t find(const char* substr) const {
for (size_t i = 0; i <= m_len - strlen(substr); ++i) {
if (strncmp(&m_str[i], substr, strlen(substr)) == 0) {
return i;
}
}
return m_len;
}
};
#endif // MYSTRING_H
```
### Task 2: `real_sort.cpp`
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
// Function to compare two floating-point numbers based on their absolute values
bool compare_by_absolute_value(double a, double b) {
return std::abs(a) < std::abs(b);
}
int main() {
int n;
std::cout << "Enter the number of real values: ";
std::cin >> n;
std::vector<double> values(n);
std::cout << "Enter your real values: ";
for (int i = 0; i < n; ++i) {
std::cin >> values[i];
}
// Sort the values based on their absolute values
std::sort(values.begin(), values.end(), compare_by_absolute_value);
// Display the sorted values
std::cout << "Sorted values: ";
for (double value : values) {
std::cout << value << " ";
}
std::cout << std::endl;
return 0;
}
```
### 提交要求
请将上述两个文件压缩成一个 `.zip` 文件,并命名为 `lab4_submission.zip`。该压缩包应包含以下文件:
1. `myString.h`
2. `real_sort.cpp`
3. 实验报告(按照 Lab1 的格式编写)
确保所有文件在编译时没有错误,并且能够通过提供的测试用例。提交截止时间为 2024 年 11 月 29 日 23:59 北京时间。
阅读全文