You can do that using at. You can try out the following simple example:
const size_t N = 20;
std::vector<int> vec(N);
try {
vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);
Notice that method at
returns an allocator_type::reference
, which is that case is a int&
. Using at
is equivalent to assigning values like vec[i]=...
.
There is a difference between at
and insert as it can be understood with the following example:
const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
vec[i] = i + 1;
}
vec.insert(vec.begin()+2, 10);
If we now print out vec
we will get:
1 2 10 3 4 5 0 0 0
If, instead, we did vec.at(2) = 10
, or vec[2]=10
, we would get
1 2 10 4 5 0 0 0
Insert
will mean adding an element at a location and moving all subsequent elements up one place in the vector (ie growing the vector by one element). On the other hand you can usesetting
to indicate you want to change an existing vector element to a new value. – Lyndes