Reputation: 39
I am stuck with simple vector input and output operations. The compiler returns error saying 'std::outof range'
Here is the code
int main()
{
int size;
cout <<"Enter size of vector\n";
cin>>size;
cout<<"Now to input the vector of size "<<size<<endl;
vector <int> trial;
for (size_t i=0;i<size;++i){
int x;
cout<<"write at position"<<trial.at(i)<<'t';
cin>>x;
trial.push_back(x);
cout<<endl;
}
ostream_iterator<int> output(cout,"");
copy(trial.begin(),trial.end(),output);
}
I would appreciate a brief explanation of the internal workings of the problem.
Upvotes: 0
Views: 3474
Reputation: 19032
The problem is this line:
cout<<"write at position"<<trial.at(i)<<'t';
You call this before you have set the size of the vector. I'm not really sure what that line is trying to accomplish anyway. If you're trying to print the in memory position (address) that won't do it, if you're trying to print what was already there then it would work if it had already been allocated. Using vector::push_back()
means that you don't need to preallocate though.
You can fix this by resizing the vector
and accessing the elements directly like this:
trial.resize(size);
// loop
// vector.push_back(x) -- now becomes
vector[i] = x;
Or, you can simply remove the printing of the position and use push_back()
as you are now.
Since it seems you're investigating how to use vector
I would suggest trying to gain an understanding of how the push_back()
and resize()
methods differ, and have also have a look at the vector::reserve()
function.
Upvotes: 0
Reputation: 224089
You invoke trial.at(i)
before trial.push_back(x)
, accessing a not yet existing element. Since the element doesn't (yet) exist, i
is an invalid index, and at()
will throw a std::out_of_range
exception when passed an invalid index. If an exception isn't caught, it will terminate the program. Presumably your platform's runtime library displays the exception that caused the program to be terminated.
I suppose what you actually want is this:
std::cout << "write at position " << i << '\t';
Upvotes: 5
Reputation: 490218
Consider the first iteration of this loop:
vector <int> trial;
for (size_t i=0;i<size;++i){
int x;
cout<<"write at position"<<trial.at(i)<<'t';
At the first iteration nothing has been pushed into the vector, so trial.at(0)
isn't yet valid. The result will be an exception. Since you don't have a try
/catch
anywhere, that will end your program's execution.
It looks to me like you want cout << "write at position " << i;
instead. i
is the position; after it has been pushed onto the vector so it's valid, vector.at(i)
will be the value at that position.
Upvotes: 2
Reputation: 258618
trial.at(i)
You're accessing an element that doesn't exist.
You probably want cout<<"write at position"<< i <<'t';
anyway.
Upvotes: 0