can someone please explain what's wrong with this code? I'm getting this error in console when I try to run the program.
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
vector<int> nums = {2,1,9,4,4,56,90,3};
int target = 8;
unordered_map<int,int> m;
for(int i=0;i<nums.size();i ){
m[nums[i]] = i;
}
int req_num;
for (int i=0; i<nums.size(); i ){
req_num = target - nums[i];
auto search = m.find(req_num);
int first = search->first;
int second = search->second;
if(first == req_num && second != i){
cout << second << endl;
}
}
return 0;
}
I'm not sure what I'm doing wrong. If someone can point out my error and explain what I did wrong, that'd be of great help!!
I tried running the program multiple times thinking it might be a build error. I'm getting the same result.
It was working fine until I changed map from ordered to unordered.
CodePudding user response:
I bet you are doing two sum question. The reason for segmentation fault is find() may not always find your req_num in the map. By solving this problem, I modified your code and it works properly.
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
vector<int> nums = {2,1,9,4,4,56,90,3};
int target = 8;
unordered_map<int,int> m;
for(int i=0;i<nums.size();i ){
m[nums[i]] = i;
}
int req_num;
for (int i=0; i<nums.size(); i ){
req_num = target - nums[i];
auto search = m.find(req_num);
if(search == m.end()) continue;
int first = search->first;
int second = search->second;
if(first == req_num && second != i){
cout << second << endl;
}
}
return 0;
}
I also modified your code to make more sense.
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
vector<int> nums = {2,1,9,4,4,56,90,3};
int target = 8;
unordered_map<int,int> m;
for(int i=0;i<nums.size();i ){
m[nums[i]] = i;
}
int req_num;
for (int i=0; i<nums.size(); i ){
req_num = target - nums[i];
if(m.find(req_num) != m.end()){
if(m[req_num]!=i){
cout << m[req_num] << endl;
}
};
}
return 0;
}