4 ms·
std::vector exposes the exact same API as a C array, in terms of being able to write an external pop_back() function, since C arrays only expose the ability to
by simiones 4y ago
std::vector exposes the exact same API as a C array, in terms of being able to write an external pop_back() function, since C arrays only expose the ability to access a particular element - no more, no less (and std::vector::resize() can be used instead of realloc() if that is desired).
- gpderetta 4y agoThe equivalent of of std vector is an array+size+capacity field. pop_back would litterally be capacity--. resize has overhead as it needs to handle resize up as well as down.
- simiones 4y agoSure, and I'm saying in C you could write: struct stack { int[] elems; int len, cap; }; int pop_back(struct stack *x) { elem = x->elems[x->len - 1]; x->len--; return elem; } while in C++ you could have written: struct stack { std::vector elems; int len, cap; }; int pop_back(stack& x) { elem = x[x.len - 1]; x.len--; return elem; } If you wanted C-style speed, with no safety.
- zabzonk 4y agothat is not valid c. and in valid c++ (which this isn't) you would not need those two integer values.
- tsimionescu 4y agoThere are some minor syntax errors - I should have written `int *elems` instead of `int[] elems`, and I forgot to declare `int elem` instead. Apart from these nitpicks, it's completely valid C. As for C++, the <int> is missing on the std::vector, the elem variable is again not declared, and instead of x[...] it should have been x.elems[...]. Otherwise working valid C++. And yes, the `cap` is not really required, we could use x.elems.size() instead.
- usefulcat 4y ago> pop_back would litterally be capacity--. Minor nit: I think you meant 'size--'
- gpderetta 4y agoouch, yes of course