C++二和.优化内存使用



我正在解决一个二和问题。 步骤:

  1. 使用以下模板读取输入文件:
7
1 7 3 4 7 9

第一行是目标编号,第二行是编号规则。

数字的范围可以是 0<999999999>

如果数字序列中两个数字的总和等于目标数字,我将"1"写入输出文件。

如果没有数字的总和等于目标数字,那么我将"0"写入输出文件。

我需要优化代码中的内存使用。我该怎么做?

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <string>
#include <algorithm>
using namespace std;
int main() {
ifstream f1;
vector<int> nums;
string line;
string source;
//Open input file and read it to a string
f1.open("input.txt");
while (getline(f1, line, 'n')) {
source+=line + " ";
} f1.close();
//Parse the string into an int vector
stringstream parser(source);
int num;
while (parser >> num) { nums.push_back(num); }
//Clear used strings
line = "";
source = "";
//Get target number
int target = nums.at(0);
//Get number sequence
nums.erase(nums.begin());
bool flag = false;
//Check number sequence for two numbers sum of which equals the target number
unordered_map<int, int> mp;
for(int i=0;i<nums.size();i++){
if(mp.count(nums[i])==1){
flag = true;
break;}
mp[target-nums[i]]=i;
}
//Write the result into the output file
ofstream f2;
f2.open("output.txt");
f2 << flag;
f2.close();
}

您可以在此处执行一些操作来最大程度地减少内存使用量。首先,您不需要将文件的全部内容读取到std::string中。您可以直接读取std::vector,或者更好的是将文件内容读取到单个int变量中,并随时处理数字。另一件事:你不需要 使用std::unordered_map,因为密钥的存在是您唯一真正感兴趣的东西,所以std::unordered_set就足够了。下面是一个利用该建议的简单解决方案:

#include <fstream>
#include <unordered_set>
int main() {
std::ifstream input {"input.txt"};
int target;
input >> target;
int current_number;
bool found = false;
std::unordered_set<int> observed_numbers;
while (input >> current_number) {
if (observed_numbers.count(target - current_number) > 0) {
found = true;
break;
}
observed_numbers.insert(current_number);
}
std::ofstream output {"output.txt"};
output << found;
}

最新更新