简体   繁体   中英

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

I am new in c++ and I am trying to solve educational exercise in quiz platform, but in this platform I should use no more than 64 MB of memory. My code use more than 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;
}

What I can add, remove or change for keep within the coveted 64 MB? I tried free memory manually but no effects. I am not sure that is possible to write more effective algorithm.

Your vector (c) is declared outside the loop and is not cleared every time you call split string. This means every time you pass in a string to split, your vector contains stuff from the previous run. Is this intentional? If it is not, then move your vector into the loop, before you call split string, or clear it in your split string function. If it is intentional please provide more info about what your code is supposed to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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