std::vector
operator []
won't throw any out of range error. It's a undefined behaviour to access element greater than the vector size using []
operator.
Use std::vector::at
instead, which throws std::out_of_range
문제
Today I try something like this in VS2012 and Max OS 10.7
vector<int> vec;
vector<int> vec2;
for(int i = 0;i < 100 ;i++){
vec.push_back(i);
}
cout << "size: " << vec.size() << endl;
cout << "capacity: " << vec.capacity() << endl;
cout << vec[127] << endl;
//vec2.reserve(10);
fill_n(vec.begin(),128,-1);
cout << vec[127] << endl;
return 0;
as we know the size of vector is the real number of elements in the container, the code above can cause runtime error in VS2012, but it works fine on Max OS, and I try it in Ideone.com and also run successfully, I am not sure if something wrong with the definition of size and capacity, why I can access element out of size?
PS: the capacity at this situation on my computer is 141 on VS2012 and 128 on Mac OS and Ideone.com
해결책
std::vector
operator []
won't throw any out of range error. It's a undefined behaviour to access element greater than the vector size using []
operator.
Use std::vector::at
instead, which throws std::out_of_range
다른 팁
Bump into this problem, I try to elaborate the answer from @P0W.
If someone wants to access the elements of the 2d vector,
one should do the following and aware of the API 2dvector.at(row#).at(col#)
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector <vector<int> > vi;
vi.push_back( vector <int>() ); // add empty 1d vector
vi.at(0).push_back( 1 ); // push 1st element
cout << vi.at(0).at(0) << endl; // access element of 2d vector and prints 1
vi.at(0).at(0) = 2; // change number
cout << vi.at(0).at(0) << endl; // access element of 2d vector and prints 2
}
std::out_of_range
if you have difficulty finding the example of std::out_of_range
, here is one
// out_of_range example
#include <iostream> // std::cerr
#include <stdexcept> // std::out_of_range
#include <vector> // std::vector
int main (void) {
std::vector<int> myvector(10);
try {
myvector.at(20)=100; // vector::at throws an out-of-range
}
catch (const std::out_of_range& oor) {
std::cerr << "Out of Range error: " << oor.what() << '\n';
}
return 0;
}
Out of Range error: vector::_M_range_check