如何在插入的字符串中优化内存使用?

时间:2017-10-14 07:39:15

标签: c++ arrays sorting pointers c-strings

强调文本任务是使用字符串比较函数编写插入排序。我已经完成了这个,我的代码正在处理小案例。但是,它无法在在线问题检查器中成功执行,并且退出了" Memmory Limit"判决。您有什么建议来优化内存使用?

UPD 我发现我做错了。我应该排序一个指向字符串的指针数组而不是字符串本身,以避免像这样复制:

less

然而,由于我对指针知之甚少,我无法理解如何正确地做到这一点。你有什么建议吗?

我已经完成了以下工作:

  • 使用语句
  • 中给出的固定(255个字符)大小的C风格字符串
  • 对指向这些字符串的指针数组进行排序
  • 通过指针将字符串传递给比较函数#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; }

这是我的源代码:

java.lang.module

1 个答案:

答案 0 :(得分: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;
  }