[c++] set of values returned from a function

Z

ZikO

Hi

What would you do to return the set of values from a function
1) the list of values
2) a couple values of different types

Something like in LUA:
-- lua code
function f()
-- something to do
return 1, 2, "name";
end

after running
a,b,c = f();

a = 1, b = 2, c = "name".

I know c++ is different than LUA but sometimes I need to get a set of
values from a function. I know there is the pair<T1, T2> type by which I
could have a pair of different values but this is only 2.
I would use one of the containers like the vector, the list or the
deqeue etc. like in example

vector<string> f() {
// something to do
vector<string> list = {"aaa","bbb","ccc"};
return list;
}

But this is not quite efficient Im affraid. Second, vector<> seems to be
difficult to deal with if there's an error and the list can't be generated.

Any suggestions appreciated very much =)
Regards.
 
K

Kai-Uwe Bux

ZikO said:
Hi

What would you do to return the set of values from a function
1) the list of values
2) a couple values of different types

Something like in LUA:
-- lua code
function f()
-- something to do
return 1, 2, "name";
end

after running
a,b,c = f();

a = 1, b = 2, c = "name".

I know c++ is different than LUA but sometimes I need to get a set of
values from a function. I know there is the pair<T1, T2> type by which I
could have a pair of different values but this is only 2.

There will be tuples in C++0X, I think.

I would use one of the containers like the vector, the list or the
deqeue etc. like in example

vector<string> f() {
// something to do
vector<string> list = {"aaa","bbb","ccc"};
return list;
}

But this is not quite efficient Im affraid. Second, vector<> seems to be
difficult to deal with if there's an error and the list can't be
generated.

Any suggestions appreciated very much =)

It all values have the same type, you can try an output iterator:

template < typename OutIter >
OutIter some_function ( OutIter where, ... );


Best

Kai-Uwe Bux
 
T

Thomas J. Gritzan

ZikO said:
Hi

What would you do to return the set of values from a function
1) the list of values
2) a couple values of different types

Something like in LUA:
-- lua code
function f()
-- something to do
return 1, 2, "name";
end

You can use

* a struct, which is good because you can name the values and define
operations on it (member functions)

* boost::tuple and boost::tie, with those you can do similar to what you
do in Lua.

* boost::array (or tr1::array) for homogenous lists of a fixed length.

* output parameters
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top