linternetsansfil
linternetsansfil

Reputation: 199

Using basic arrays for compatibility

Imagine a function from a library that takes an array as argument, in their own code, the users may use various array implementations, some will use std::vectors, some will use std::array, some will use basic arrays, some may even create their own classes, we can't satify every user. But every type of array works with a pointer and a size (stored somewhere or not, but known), could using a pointer and a size (if needed) as arguments solve this problem ?

Upvotes: 2

Views: 89

Answers (1)

KamilCuk
KamilCuk

Reputation: 141135

could using a pointer and a size (if needed) as arguments solve this problem ?

Yes. That's typical C-ish api used since forever, like string functions with bounds checking or mem* functions like memcpy or memcmp functions or qsort takes a pointer and count of elements etc.

But C++ saw that not every "array" has to be an array really, so C++ uses iterators to abstractly pass the information of something that you can "iterate" on. Every std::vectors and std::array and "basic arrays" all have their own iterators and all algorithms are abstractly written with iterators in mind. Because iterators are overloaded with custom operators, you can do almost anything, like ex. inserter allows for putting elements into a vector as they come.

There is also the recent addition of ranges. Ranges invert the syntax of iterators like inside out and offer simpler and safer use and amazing and simple functionality.

Upvotes: 3

Related Questions