How to do this in c++

J

john.burton

I used to use c++ a lot but recently I've been using java and pythons
and I'm finding it a lot harder to think of the best way to do
something in C++

Imagine I want a function that returns a "list" of selected users from
a big list of users, or a database or something based on some
selection.

In python I might use a generator function which yielded the next
relevent user each time it was called. In java I'd probably return an
Iterator which iterated through the selected users probably using an
instance of an inner class to implement the iterator that just iterated
through the items I wanted.

It's not so clear how I'd best do this in C++?

C++ iterators are totally different things to java iterators and it
doesn't seem at all elegent to define a new type of iterator which only
iterates though selected items.

I could create a new list and return that by value but that seems
somewhat inefficient so say the least. Returning any kind of reference
to an existing list seems fraught with memory management issues over
how to create and delete the memory.

What's the best way to do this in C++? I hope this makes some sense...
 
B

Bob Hairgrove

I could create a new list and return that by value but that seems
somewhat inefficient so say the least. Returning any kind of reference
to an existing list seems fraught with memory management issues over
how to create and delete the memory.

Use std::vector<> and let it manage the memory for you. Create an
empty list or vector and pass a non-const reference to it to your
function that selects the names, etc. from the database or file or
whatever, and let the function fill up the vector. You are right that
returning the vector or list by value would most likely be too
inefficient.

std::list or std::map might be more effcient than a vector if you need
to insert and delete lots of objects. std::vector is better for
sequential or random access.

And returning a reference to any object locally allocated within a
function (i.e. not created with "new", but a stack-based or automatic
variable, whatever you want to call it) is a big no-no because that
memory ceases to exist when the function returns...thus invalidating
the reference.
 
M

Michael

I used to use c++ a lot but recently I've been using java and pythons
and I'm finding it a lot harder to think of the best way to do
something in C++

Imagine I want a function that returns a "list" of selected users from
a big list of users, or a database or something based on some
selection.

In python I might use a generator function which yielded the next
relevent user each time it was called. In java I'd probably return an
Iterator which iterated through the selected users probably using an
instance of an inner class to implement the iterator that just iterated
through the items I wanted.

It's not so clear how I'd best do this in C++?

C++ iterators are totally different things to java iterators and it
doesn't seem at all elegent to define a new type of iterator which only
iterates though selected items.

I could create a new list and return that by value but that seems
somewhat inefficient so say the least. Returning any kind of reference
to an existing list seems fraught with memory management issues over
how to create and delete the memory.

What's the best way to do this in C++? I hope this makes some sense...

What do you have the "big list" as ? how about returning a list of
pointers to the relevant objects?

Mike
 
G

Giancarlo Niccolai

I used to use c++ a lot but recently I've been using java and pythons
and I'm finding it a lot harder to think of the best way to do
something in C++

Imagine I want a function that returns a "list" of selected users from
a big list of users, or a database or something based on some
selection.

In python I might use a generator function which yielded the next
relevent user each time it was called. In java I'd probably return an
Iterator which iterated through the selected users probably using an
instance of an inner class to implement the iterator that just iterated
through the items I wanted.

It's not so clear how I'd best do this in C++?

C++ iterators are totally different things to java iterators and it
doesn't seem at all elegent to define a new type of iterator which only
iterates though selected items.

Actually, you can and it is not inelegant at all.


The already proposed solution of the function receiving a non-const
reference to a vector or other container, and then filling it, is one of
the best. Let me just to remember also the possibility to return a pointer
to a new() allocated structure within the function (or 0 in case of
failure); this won't fragment your memory as much as a garbage collector
would, so as long as you delete the object properly, providing a correct
destructor if needed, you don't have to worry about it.
Let me remember also the possibility to build a class to manage your input
source, so that the data structure is a member of the class, and the
functions filling it are methods.

Bests,
Giancarlo Niccolai
 
A

Alf P. Steinbach

* (e-mail address removed):
I used to use c++ a lot but recently I've been using java and pythons
and I'm finding it a lot harder to think of the best way to do
something in C++

Imagine I want a function that returns a "list" of selected users from
a big list of users, or a database or something based on some
selection.

In python I might use a generator function which yielded the next
relevent user each time it was called. In java I'd probably return an
Iterator which iterated through the selected users probably using an
instance of an inner class to implement the iterator that just iterated
through the items I wanted.

It's not so clear how I'd best do this in C++?

The root of this problem is not with iterators (yes, they are awkward in C++)
but with lifetime and copying issues for the object you return.

To solve that use a smart-pointer to a dynamically allocated object -- which
is essentially what you have in Java and Python.

The simplest kind of smart-pointer is std::auto_ptr, which just transfers
ownership, and perhaps that will be sufficient for you. Otherwise, consider
e.g. boost::shared_ptr. For that you'll have to install the boost library.
 
J

John Burton

Bob said:
Use std::vector<> and let it manage the memory for you. Create an
empty list or vector and pass a non-const reference to it to your
function that selects the names, etc. from the database or file or
whatever, and let the function fill up the vector. You are right that
returning the vector or list by value would most likely be too
inefficient.

Of course. I used to know all this. I've been doing java and python too long!
Thanks for this suggestion and the others who posted!
 
S

Shezan Baig

I used to use c++ a lot but recently I've been using java and pythons
and I'm finding it a lot harder to think of the best way to do
something in C++

Imagine I want a function that returns a "list" of selected users from
a big list of users, or a database or something based on some
selection.


If you would like to keep as close as possible to Java semantics, then
the function should return shared_ptr< list<Item> >, where you allocate
the list inside your function. And the shared_ptr will delete it
automatically. This is semantically similar to what you would do in
Java.

Hope this helps,
-shez-
 
J

john.burton

Shezan said:
If you would like to keep as close as possible to Java semantics, then
the function should return shared_ptr< list<Item> >, where you allocate
the list inside your function. And the shared_ptr will delete it
automatically. This is semantically similar to what you would do in
Java.

Thanks for the suggestion. I'm not particularly interested in
replicating the java solution, I just couldn't remember how this was
done in c++ after a year or so of doing very little with it! I think
that passing in an empty list or vector to fill in is the best solution
for what I wanted.
 
P

persenaama

Actually, it's not too difficult to write a filter which returns a new
iterator for each iteration. The usage pattern could boil down to
something similiar to this:

container::iterator i = container_instance.begin();
for ( ; i != container_instance.end(); ++i )
{
if ( filter(*i) )
{
// object passes the inspection, what now boss?
}
}

Looks straightforward to me, iterate and inspect.. if your goal is to
immediately act it might be a good idea to do it inside the if-block.

If you really want to keep record around, it depends.. you might want
to return std::vector<yourtype*>, or you might want to copy objects
then have std::vector<yourtype> if you intend to pass the new container
around for some other processing.

It really depends what you have in mind after you do the filtering.. I
cannot go and assume what you have in mind, I design code to solve a
problem and in your case there isn't any.. just return whatever you
want as long as it gets the job done. How optimal in memory, time,
etc.. you can and want solution to be depends on how you going to
access the results.. I just don't know that.

Ofcourse, if I knew what this is used for might result in a completely
different answer. :)
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

Imagine I want a function that returns a "list" of selected users from
a big list of users, or a database or something based on some
selection.
It's not so clear how I'd best do this in C++?

The best way would be to get yourself familiar with the C++ standard library
and use its features. In this case, you need the copy_if algorithm, which
unfortunately in not part of the standard :) (There is some story to that.)

copy_if may be present as an extension in your library, you can find it on
the web, or you can write it yourself. I found one at

http://www.bauklimatik-dresden.de/privat/nicolai/html/en/cpp.html#algorithms

template <typename InputIt, typename OutputIt, typename Predicate>
OutputIt copy_if (InputIt first, InputIt last,
OutputIt result, Predicate pred)
{
while (first != last) {
if (pred(*first)) *result++ = *first;
++first;
}
return result;
}

With that, what you need is very simple:


typedef list<User> Users;

// The original users
Users const users = get_users_from_somewhere();

Users selected_ones;

copy_if(users.begin(), users.end(),
back_inserter(selected_ones),
my_predicate);

my_predicate is either a function that returns bool depending on whether a
User meets your criteria:

bool my_predicate(User const & user)
{
/* ... */
}

or it is a function object:

class MyPredicate
{
/* ... */

bool operator() (User const & user)
{
/* ... */
}
};

In that case, the usage might be:

copy_if(users.begin(), users.end(),
back_inserter(selected_ones),
MyPredicate(/* parameters to help the predicate */));


If you wrap copy_if in one of your functions, then you end up with a nice
little function:

Users get_selected_ones(Users const & users)
{
Users selected_ones;

copy_if(users.begin(), users.end(),
back_inserter(selected_ones),
my_predicate);

return selected_ones;
}

And yes, return by value! It is a myth that returning by value is slow.
Usually it is the named-return-value optimization (NRVO) that takes care of
the seeming cost of a copy. Or as in most cases, even if the copy cannot be
elided, the cost is non-detectable by the users of the program.
C++ iterators are totally different things to java iterators and it
doesn't seem at all elegent to define a new type of iterator which only
iterates though selected items.

Use function templates like copy_if to avoid typedefing or defining
iterators.
I could create a new list and return that by value but that seems
somewhat inefficient so say the least.

That is premature optimization. What you want to return is a list of users;
just return them.

I know that some groups use the method of receiving references for the
results to be put in:

int get_selected_ones(Users const & users, Users & selected_ones);

What are the semantics if selected_ones is not empty?

a) clear it anyway?
b) append?
c) return an error?

It is simply not clear.

Ali
 
J

John Harrison

I know that some groups use the method of receiving references for the
results to be put in:

int get_selected_ones(Users const & users, Users & selected_ones);

What are the semantics if selected_ones is not empty?

a) clear it anyway?
b) append?
c) return an error?

It is simply not clear.

Clear it anyway or, more precisely, build up the results in a local
variable and then swap the local variable with selected_ones as the last
action of get_selected_ones(), this is for exception safety.

Since passing in a reference is meant as a more efficient alternative to
return by value options b and c do not apply since they would not be
possible using return by value. The best fit with return by value is
option a.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top