Vectors C++ Out Of Range Exception
Jun 2, 2018 at 8:47pm UTC
I was working on an assignment where I have to work with vector of strings, However when I run the program it throws and Exception of being out of range when _n = 0. Any help would be appreciated.
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 47 48 49 50 51 52 53 54 55 56
#include<iostream>
#include<climits>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
int LCP(string a, string b) {
int x = 0;
for (int i = 0, j = 0; i < a.length() && j < b.length(); i++, j++) {
if (a[i] == b[j]) {
x++;
}
else {
break ;
}
}
return x;
}
int main() {
int n;
cin >> n;
vector<string> input;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
input.push_back(str);
}
int q;
for (int j = 1; j <= q; j++) {
int r;
cin >> r;
string p;
cin >> p;
vector<int > commonPrefixLengths;
for (int i = 0; i < r; i++) {
int length = LCP(input[i], p);
commonPrefixLengths.push_back(length);
}
int maxLength = INT_MIN;
for (int i = 0; i < r; i++) {
if (commonPrefixLengths[i] > maxLength) {
maxLength = commonPrefixLengths[i];
}
}
vector<string> toBeSorted;
for (int i = 0; i < n; i++) {
if (input[i].size() == maxLength) {
toBeSorted.push_back(input[i]);
}
}
sort(toBeSorted.begin(), toBeSorted.end());
cout << toBeSorted[0] << endl;
}
}
Jun 2, 2018 at 9:23pm UTC
toBeSorted
is empty
Jun 2, 2018 at 9:24pm UTC
But in the last for loop I'm using the push_back operator to insert elements in to the toBeSorted vector.
Jun 2, 2018 at 9:28pm UTC
But you're pushing nothing into it.
Check for yourself:
cout << "Size of toBeSorted: " << toBeSorted.size();
Topic archived. No new replies allowed.