I'm new to c++ and just learned about vectors. I'm coming from Python, so of course I checked if I could use negative indexing in c++, which did not seem to work.
While trying to check if it works, I met a very weird behaviour for negative indexes in different environments.
Using negative indexes with the .at()
function raises an error but not when using []
brackets.
Are these values contents of previous memory locations, or what do they represent? Is this what's called undefined behaviour
?
Source:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {3, 6, 9, 12, 15};
std::cout << "Length: " << numbers.size() << "\n";
for (int i = 4; i > -5; i--) {
std::cout << "Pos " << i << ": " << numbers[i] << "\n";
}
}
Output:
Length: 5
Pos 4: 15
Pos 3: 12
Pos 2: 9
Pos 1: 6
Pos 0: 3
Pos -1: 0 // other env: 201392090
Pos -2: 33 // other env: 475047512
Pos -3: 0
Pos -4: 0