Insight 13.3.1.
Just as with strings, because we index starting with 0, a vector with \(x\) elements has indices from 0 to \(x - 1\text{.}\)
The last element is always at index \(x - 1\text{.}\)
vector<int>
counts = {12, 6, 3, 14} creates something like this:
counts containing 12, 6, 3, and 14..at(index) function.
.at(index) function returns the element at the specified index. The type of that value always matches the type of the vectorโs elements.
vector<int> counts = {10, 20, 30, 40};
int first = counts.at(0); // first is 10
vector<string> words = {"apple", "banana", "cherry"};
string second = words.at(1); // second is "banana"
vector<double> measurements = {1.1, 2.2, 3.3};
double third = measurements.at(2); // third is 3.3
vec.at(index) to change a value in a vector. The value we assign to that location must be of the same type as the elements in the vector:
vector<char> symbols = {'x', 'q', '*', '!'};
symbols.at(2) = '$'; //{'x', 'q', '$', '!'}
vector<string> words = {"apple", "banana", "cherry"};
words.at(1) = "blueberry"; // {"apple", "blueberry", "cherry"}
.at(index) to ask for an index that is not valid (less than 0 or >= .size()), there will be a runtime error when that statement executes. This program runs fine until we try to access counts.at(4):
out_of_range message. This means that the index you provided was not valid. After that, there is vector::_M_range_check: __n (which is 4) >= this->size() (which is 4). This tells us that the problem comes from a vector and we asked for index 4 in a vector with size of 4. Unfortunately, we do not get a line number, so we have to use print statements or a debugger to help track down the exact location.
vec.at(index) = ... is only for changing existing values. You canโt use it to add a value at an index that is not already in use.
vectorName[index]) notation for accessing elements. However, when using that syntax, there is no bounds checking. You can ask for element 100 in a 4 element vector and will be given some piece of memory that is unrelated to the vector (it will be whatever is in memory where element 100 would be if it existed).
cout << counts[4] << endl;. Then run the program. There will not be an exception. Instead, some unpredictable value (possibly 0, possibly not) will be printed.
.at(index)) is worth it to avoid these kinds of bugs in the vast majority of situations.
vector<string> message = {"happy", "to", "you", "September", "birthday", "girl"}
string word = message.at(4)string word = message.at(5)string word = message.at(6)string word = message(4)string word = message(5)vector<int> vec by one?
vec.at(3) = vec.at(3)++;vec(3) = vec(3) + 1;vec.at(2)++;vec.at(2) is the third element and we increment it by using the ++ operator.vec(2) = vec(2)++;vec.at(2) = vec.at(2) + 1vec.at(2) is the third element and we increment it by adding 1.vec to a 6, multiplies the third element of vec by 2, and increments the last element of vec by 1 (in that order). This should work no matter what vec is.