Jul 30, 2015 at 11:43am UTC
I wrote a code to get two numbers which add up to the target.
here's the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public :
vector<int > twoSum(vector<int > &numbers, int target)
{
int len = numbers.size();
vector<int > r;
for (int i = 0; i < len - 1; i++)
{
int k = target - numbers[i];
for (int j = i + 1; j < len; j++)
{
if (numbers[j] == k)
{
r.push_back(i + 1);
r.push_back(j + 1);
}
}
}
return r;
}
};
int main(void )
{
vector<int > numbers = { 2,7,11,15 };
vector<int > s;
int targ;
cout << "input the target:" ;
cin >> targ;
Solution s1;
s = s1.twoSum(numbers, targ);
for (int i = 0; i < s.size(); i++)
cout << "index1 = " << s[i] << "," << " index2 = " << s[i + 1] << endl;
system("pause" );
return 0;
}
I got the error message "vector subscript out of range" at cout<<"index1 = "...
I coundn't figure what's error. pls help...
Last edited on Jul 30, 2015 at 11:44am UTC
Jul 30, 2015 at 11:48am UTC
line 42.
s[i + 1]
That's probably your culprit.
If you are at the ith element in your vector when 'i' is equal s.size() (i.e. the last element in your vector), then i+1 is royally going to screw you up.
In other words, if you have a vector with 10 elements for example, you're asking for the 11th element. Which is bad.
Last edited on Jul 30, 2015 at 11:57am UTC
Jul 30, 2015 at 12:10pm UTC
thanks for the tip. It works. thanks you very much!