如何优化插入字符串中的内存使用情况?
问题描述:
强调文本任务是编写带字符串比较函数的插入排序。我已经做到了这一点,我的代码正在处理小案例。但是,在线问题检查程序无法成功执行“Memmory Limit”判决时退出。您有什么建议来优化内存使用情况?如何优化插入字符串中的内存使用情况?
UPD我已经知道我做错了事。我应该排序指针指向字符串,而不是字符串本身的数组来避免这样的复制:
arr[j + 1] = arr[j];
但是,由于我的指针的小知识我不明白如何正确地做到这一点。你有什么建议?
我已经做了以下内容:
- 使用C风格的固定(255个字)大小的它在声明中给出
- 排序指针数组将这些字符串字符串
- 通过指针将字符串传递给比较函数
less
。
这里是我的源代码:
#include <cstdio>
const int kMaxStringSize = 200;
bool less(char **s1, char **s2) {
int i = 0;
while ((*s1)[i] == (*s2)[i]) {
if ((*s1)[i] == '\0' || (*s2)[i] == '\0') {
break;
}
i++;
}
if ((*s1)[i] != '\0') {
if ((*s1)[i] < (*s2)[i]) {
return true;
} else {
return false;
}
} else {
if ((*s2)[i] != '\0') {
return true;
} else {
return false;
}
}
}
int main() {
int n;
std::scanf("%d\n", &n);
char **arr;
arr = new char*[n];
for (int i = 0; i < n; i++) {
char *temp = new char[kMaxStringSize];
fgets(temp, 256, stdin);
arr[i] = temp;
}
for (int i = 1; i < n; ++i) {
int j = i - 1;
char *temp = arr[i];
for (; (j >= 0) && less(&temp, &arr[j]); --j) {
arr[j + 1] = arr[j];
}
arr[j + 1] = temp;
}
for (int i = 0; i < n; i++) {
printf("%s", arr[i]);
}
for (int i = 0; i < n; i++) {
delete[] arr[i];
}
delete []arr;
return 0;
}
答
每个字符串使用可用的最大空间,但也许只需要几个字符。
char temp[257] = '\0'; // bigger than given to fgets
for (int i = 0; i < n; i++) {
fgets(temp, 256, stdin);
char * t = new char[ strlen(temp) + 1];
strcpy(t, temp);
arr[i] = t;
}
作为文本而不是链接发布代码。 –
如果您的代码已经运行[SE代码审查](https://codereview.stackexchange.com/)可能更适合您的问题。 – user0042
谢谢,我会试试看。 –