4 ms·
As another commenter pointed out, it's only the indices that are one-based. I think it would look something like this: int count_occurrences(std::vector<int>
by tg3 13y ago
As another commenter pointed out, it's only the indices that are one-based. I think it would look something like this:
int count_occurrences(std::vector<int> vec, int value) {
int count = 0;
for(int i = 1; i <= vec.size(); ++i) { // using 1-based index
if(vec[i] == value)
++count;
}
return count;
}
Off the top of my head, this has a number of benefits in higher level languages. For instance in Javascript, here are some common inconveniences caused by zero-based indices:
var lastEl = arr[arr.length - 1];
if(arr.indexOf(someEl) !== -1) {
// do something knowing that someEl is in the array
}
and if we lived in a one-based world, here's what they would look like:
var lastEl = arr[arr.length];
if(arr.indexOf(someEl)) {
// do something knowing that someEl is in the array
}