Looking at your code as pseudo-code for an algorithm, it basically attempts to solve
- Check (via O(n) instead of O(1) cost) if the vector has at least 5 elements.
- If
true
, go to 2.
- Otherwise do nothing.
- Do something with the 5th element.
If this is indeed the case, you don't actually need a for loop for this, you could just query the size of the vector prior to conditionally accessing (O(1) random access) the 5th element to //do something...
:
#include <iostream>
#include <string>
#include <vector>
int main() {
const std::vector<std::string> v{"a", "b", "c", "d", "e", "f"};
if (v.size() > 4) {
auto s = v[4];
// do something with the 5th element, as it exists.
std::cout << e; // d
}
}
Or, you could make use of the bounds-checking element accessor at()
clong with exception handling in case of attempted out-of-bounds access.