繁体   English   中英

有没有办法减少我的 c++ 代码中的 memory 消耗?

[英]Is there way to reduce memory consumption in my c++ code?

我是 c++ 的新手,我正在尝试在测验平台上解决教育练习,但在这个平台上我应该使用不超过 64 MB 的 memory。 我的代码使用超过 130 MB。

#include <sstream>
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <map>

using namespace std;

template<class Container>
void splitString(const std::string &basicString, Container &cont, char delim = ' ') {
   std::stringstream ss(basicString);
   std::string token;
   while (std::getline(ss, token, delim)) {
       cont.push_back(token);
   }
}

int main() {
   int target = 0;
   int count = 0;

   std::map<int, int> set;

   string line;
   ifstream fileR("input.txt");

   std::vector<string> c;

   if (fileR.is_open()) {
       while (getline(fileR, line)) {
           if (count == 0) {
               target = std::stoi(line);
               count++;
               continue;
           }

           splitString(line, c);

           for (auto &d : c) {
               int key = std::stoi(d);

               if (set.count(key)) {
                   set[key] += 1;
               } else {
                   set[key] = 1;
               }
           }

           c.clear();
       }

       fileR.clear();
       fileR.close();
   }

   ofstream fileW;
   fileW.open("output.txt");

   bool found = false;

   for (const auto &p : set) {
       int d = target - p.first;

       if (set.count(d)) {
           if (p.first != d || set[d] > 1) {
               fileW << 1;
               found = true;
               break;
           }
       }
   }

   if (!found) {
       fileW << 0;
   }
   fileW.close();
   return 0;
}

我可以添加、删除或更改什么以保留在梦寐以求的 64 MB 内? 我手动尝试了免费的 memory 但没有效果。 我不确定是否可以编写更有效的算法。

您的向量 (c) 在循环外声明,并且每次调用拆分字符串时都不会被清除。 这意味着每次您传入要拆分的字符串时,您的向量都会包含上一次运行的内容。 这是故意的吗? 如果不是,则在调用拆分字符串之前将向量移动到循环中,或者在拆分字符串 function 中清除它。 如果这是故意的,请提供有关您的代码应该做什么的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM