Jun 20, 2015 at 4:05pm UTC
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 57 58 59 60 61 62
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
string indexArray;
string input, line;
int test_case, number, i;
vector <int > index;
vector <float > input1;
vector <float > input2;
float output;
getline(cin,line);
stringstream(line) >> test_case;
//cin>>test_case;
cout<<endl;
while (test_case--)
{
getline(cin,indexArray);
stringstream iss(indexArray);
getline(cin, input);
stringstream iss1(input);
while (iss>>number)
{
index.push_back(number);
}
while (iss1>>output)
{
input1.push_back(output);
}
for (i=0; i<index.size(); i++)
{
cout<<index[i]<<" " ;
}
cout<<index.size()<<endl;
for (i=0; i<input1.size(); i++)
{
cout<<input1[i]<<" " ;
}
cout<<input1.size()<<endl;
for (i=0; i<index.size(); i++)
{
input2[index[i]-1]=input1[i];
}
for (int i=0; i<input1.size(); i++)
{
cout<<input2[i]<<" " ;
}
cout<<endl;
input1.clear();
index.clear();
}
}
My program crashes at line 50 where,
input2[index[i] - 1]=input1[i]
I can't seem to understand why
Last edited on Jun 20, 2015 at 4:07pm UTC
Jun 20, 2015 at 4:57pm UTC
input2 has 0 elements, so you cannot access it by using []. You need to fill it with numbers first.
Jun 20, 2015 at 6:32pm UTC
Well I AM trying to fill input2 with numbers by assigning input1 members to input2. Am I missing something?
Jun 20, 2015 at 6:35pm UTC
Yes, operator[] exist to allow access to existing elements. You should look at resize() method.
Jun 20, 2015 at 6:50pm UTC
So, should I write vectorSample.resize(size_type n) everytime I initialize a vector to fill it up with numbers (0 in this case) ?
Jun 20, 2015 at 6:57pm UTC
you should resize vector to make space for all objects you want to store in it. So you want to pass largest number found in index vector to make sure that you can acces value under that index.