By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,443 Members | 1,409 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,443 IT Pros & Developers. It's quick & easy.

My first project

P: n/a
I've just learned the basics of C++, and as my first real project I am
attempting to construct a text adventure, like back in the good old
days of Commodore 64 BASIC. This is my code so far:

#include <iostream>
#include <string>
using namespace std;

struct room {
int number;
int numofexits;
int special;
string description;
room (int a, int b, int c, string d);

};

room::room (int a, int b, int c, string d) {
number=a;
numofexits=b;
special=c;
description=d;

}

room Foyer(1,3,0,"You are in the foyer of the cathedral.\nIt's hard to
believe you've just entered for any purpose other than worship
or\nsacrifice.\n");
room* allrooms[50]={&Foyer};
int location=0;

int main () {
cout << "****************\n";
cout << "** The Depths **\n";
cout << "****************\n\n\n";
cout << allrooms[location]->description;

}

Pretty straightforward, I think. My problem is this: Each room is
going to have a number of exits (defined by "numofexits"). Obviously,
those exits will lead to different rooms based on which room you are
standing in. I've tried to make a dynamic array with different sizes
for different objects of the "room" class, but that didn't work out.
What would be the best way to do this? Sorry if I've been confusing in
any way; just point it out and I'll clarify. Thanks in advance for any
help.

Dec 20 '06 #1
Share this Question
Share on Google+
28 Replies


P: n/a

Caleb wrote:
I've just learned the basics of C++, and as my first real project I am
attempting to construct a text adventure, like back in the good old
days of Commodore 64 BASIC. This is my code so far:

#include <iostream>
#include <string>
using namespace std;

struct room {
int number;
int numofexits;
int special;
string description;
room (int a, int b, int c, string d);

};

room::room (int a, int b, int c, string d) {
number=a;
numofexits=b;
special=c;
description=d;

}

room Foyer(1,3,0,"You are in the foyer of the cathedral.\nIt's hard to
believe you've just entered for any purpose other than worship
or\nsacrifice.\n");
room* allrooms[50]={&Foyer};
int location=0;

int main () {
cout << "****************\n";
cout << "** The Depths **\n";
cout << "****************\n\n\n";
cout << allrooms[location]->description;

}

Pretty straightforward, I think. My problem is this: Each room is
going to have a number of exits (defined by "numofexits"). Obviously,
those exits will lead to different rooms based on which room you are
standing in. I've tried to make a dynamic array with different sizes
for different objects of the "room" class, but that didn't work out.
What would be the best way to do this? Sorry if I've been confusing in
any way; just point it out and I'll clarify. Thanks in advance for any
help.
I've seen it where there is no "numofexits". Instead, there are always
the 6 standard exits NSEWUD. This means your room structure doesn't
use dynamic arrays. If a room only uses 3 of the exits, the others are
set to 0 and the program prints "you can't go that way" if the player
tries to take one of those exits. Negative room numbers were used
for special effects such as -99 being GAME OVER.

The extra memory needed to hold six exits for every room as opposed
to holding a variable number of room exits worked well enough on
an Apple ][, so I doubt you'll have a problem with it.

Dec 20 '06 #2

P: n/a
On Dec 20, 6:12 am, "Mensanator" <mensana...@aol.comwrote:
Caleb wrote:
Pretty straightforward, I think. My problem is this: Each room is
going to have a number of exits (defined by "numofexits"). Obviously,
those exits will lead to different rooms based on which room you are
standing in. I've tried to make a dynamic array with different sizes
for different objects of the "room" class, but that didn't work out.
What would be the best way to do this? Sorry if I've been confusing in
any way; just point it out and I'll clarify. Thanks in advance for any
help.

I've seen it where there is no "numofexits". Instead, there are always
the 6 standard exits NSEWUD. This means your room structure doesn't
use dynamic arrays. If a room only uses 3 of the exits, the others are
set to 0 and the program prints "you can't go that way" if the player
tries to take one of those exits. Negative room numbers were used
for special effects such as -99 being GAME OVER.

The extra memory needed to hold six exits for every room as opposed
to holding a variable number of room exits worked well enough on
an Apple ][, so I doubt you'll have a problem with it.
But it would be so much better C++ to use a vector, else one might
almost as well use C.

--
Erik Wikström

Dec 20 '06 #3

P: n/a
Caleb wrote:
I've just learned the basics of C++, and as my first real project I am
attempting to construct a text adventure, like back in the good old
days of Commodore 64 BASIC. This is my code so far:

#include <iostream>
#include <string>
using namespace std;

struct room {
int number;
int numofexits;
int special;
string description;
room (int a, int b, int c, string d);

};

room::room (int a, int b, int c, string d) {
number=a;
numofexits=b;
special=c;
description=d;

}

room Foyer(1,3,0,"You are in the foyer of the cathedral.\nIt's hard to
believe you've just entered for any purpose other than worship
or\nsacrifice.\n");
room* allrooms[50]={&Foyer};
int location=0;

int main () {
cout << "****************\n";
cout << "** The Depths **\n";
cout << "****************\n\n\n";
cout << allrooms[location]->description;

}

Pretty straightforward, I think. My problem is this: Each room is
going to have a number of exits (defined by "numofexits"). Obviously,
those exits will lead to different rooms based on which room you are
standing in. I've tried to make a dynamic array with different sizes
for different objects of the "room" class, but that didn't work out.
What would be the best way to do this? Sorry if I've been confusing in
any way; just point it out and I'll clarify. Thanks in advance for any
help.
Use a list type like vector<>, and put pointers in it; don't put
objects in it directly, by value.

You can't store objects of different sizes in a vector<>. The only way
to do that would be to put objects of different types in the vector,
and you can't do that directly. But you can do it if you put in
pointers of some base class.

So, don't use (for instance) vector<Room-- use vector<Room*instead.
Then you can store not only Rooms, but subclasses of Rooms.

The main disadvantage of this scheme is that you must be careful to
delete these pointers when you remove them from the list, because
vector<doesn't do that for you. And things get hairy when you have
Rooms stored in several different lists; that's when reference-counting
begins to look attractive. But that's the price of polymorphism.

(By the way, you might consider using 'class' here instead of 'struct'.
In C++, a struct *is* a class -- the only difference is that its
members are public by default, while the members of a class are private
by default. But most people think 'C-style struct with no methods' when
they see the 'struct' keyword, so a struct with methods and access
specifiers, while perfectly legit, looks odd.)

Good luck! --mpa

Dec 20 '06 #4

P: n/a
Michael Ashton a écrit :
Caleb wrote:
>I've just learned the basics of C++, and as my first real project I am
attempting to construct a text adventure, like back in the good old
days of Commodore 64 BASIC. This is my code so far:

#include <iostream>
#include <string>
using namespace std;

struct room {
int number;
int numofexits;
int special;
string description;
room (int a, int b, int c, string d);

};

room::room (int a, int b, int c, string d) {
number=a;
numofexits=b;
special=c;
description=d;

}

room Foyer(1,3,0,"You are in the foyer of the cathedral.\nIt's hard to
believe you've just entered for any purpose other than worship
or\nsacrifice.\n");
room* allrooms[50]={&Foyer};
int location=0;

int main () {
cout << "****************\n";
cout << "** The Depths **\n";
cout << "****************\n\n\n";
cout << allrooms[location]->description;

}

Pretty straightforward, I think. My problem is this: Each room is
going to have a number of exits (defined by "numofexits"). Obviously,
those exits will lead to different rooms based on which room you are
standing in. I've tried to make a dynamic array with different sizes
for different objects of the "room" class, but that didn't work out.
What would be the best way to do this? Sorry if I've been confusing in
any way; just point it out and I'll clarify. Thanks in advance for any
help.

Use a list type like vector<>, and put pointers in it; don't put
objects in it directly, by value.
You can't store objects of different sizes in a vector<>. The only way
to do that would be to put objects of different types in the vector,
and you can't do that directly. But you can do it if you put in
pointers of some base class.

So, don't use (for instance) vector<Room-- use vector<Room*instead.
Then you can store not only Rooms, but subclasses of Rooms.

The main disadvantage of this scheme is that you must be careful to
delete these pointers when you remove them from the list, because
vector<doesn't do that for you. And things get hairy when you have
Rooms stored in several different lists; that's when reference-counting
begins to look attractive. But that's the price of polymorphism.
When using pointers in this way, Boost's shared_ptr<makes your life
easier with this kind of design:

typedef boost::shared_ptr<RoomRoomSharedPtr
std::vector< RoomSharedPtr allrooms;
....
allrooms.push_back(RoomSharedPtr(new room(1,3,0,"You are in the foyer of
the cathedral.\nIt's hard tobelieve you've just entered for any purpose
other than worship or\nsacrifice.\n")));

Michael
Dec 20 '06 #5

P: n/a

Mensanator wrote:
The extra memory needed to hold six exits for every room as opposed
to holding a variable number of room exits worked well enough on
an Apple ][, so I doubt you'll have a problem with it.
Very true. But I had hoped that by learning C++ I could expand the
program into more advanced stuff, such as not being limited to one exit
in each direction. For example, a large room with three evenly-spaced
northward exits that branch into different hallways.

Dec 20 '06 #6

P: n/a
I will look into this vector business. Thanks for all the suggestions,
and I will report back after I find out about the vector stuff. :)

Dec 20 '06 #7

P: n/a
std::vector does exactly what I want it to do. It seems to be
extremely advantageous over regular arrays, too. There's just one
thing I'm wondering....is there a way to push_back three elements at
once? For example, I'm going to have a list of door initializations
that look like this:

Foyer.destination.push_back(2);Foyer.destination.p ush_back(3);Foyer.destination.push_back(6);

And that's only for a 3-door room....is there a more efficient way to
code that?

Dec 21 '06 #8

P: n/a
LR
Caleb wrote:
Mensanator wrote:
>>The extra memory needed to hold six exits for every room as opposed
to holding a variable number of room exits worked well enough on
an Apple ][, so I doubt you'll have a problem with it.


Very true. But I had hoped that by learning C++ I could expand the
program into more advanced stuff, such as not being limited to one exit
in each direction. For example, a large room with three evenly-spaced
northward exits that branch into different hallways.
How would someone using the program distinguish between those exits? IE
what command would they give that would allow them to go to a particular
exit?

LR
Dec 21 '06 #9

P: n/a

LR wrote:
How would someone using the program distinguish between those exits? IE
what command would they give that would allow them to go to a particular
exit?

LR
Not that I understand how that's significant to my question, hehe :),
but I'm going to be adding menus of exits/objects in the room to the
room descriptions. If the player wants to move, they'll just input the
number corresponding with the door they want.

I thought of a way I could set it up where I can add multiple elements
with one statement....rather simple, really. Just overload an
"add_doors" function with one integer, two integers, five integers, and
whatever amounts of integers that I need, and write it to push_back the
elements that were provided one at a time. Contemplating whether that
would really be worth it, though.

Dec 21 '06 #10

P: n/a
r
Caleb wrote:
>
I thought of a way I could set it up where I can add multiple elements
with one statement....rather simple, really. Just overload an
"add_doors" function with one integer, two integers, five integers, and
whatever amounts of integers that I need, and write it to push_back the
elements that were provided one at a time. Contemplating whether that
would really be worth it, though.
There is an 'assign' library in boost. It may be what you are looking
for.

Dec 21 '06 #11

P: n/a
My latest problem: All commands are entered by an integer selected
from a menu (or "0" for quit). If something invalid is entered, like
"x" or ".", the program enters a neverending loop. This seems to be a
common problem for n00bs as I have researched it on Google. I have
found workarounds to detect invalid input, but they all seem to cause
"0" and invalid input to be read the same. The value is being read to
an "int" variable. Can anyone help with that one? Thanks again for
all the help.

Dec 21 '06 #12

P: n/a
Caleb a écrit :
My latest problem: All commands are entered by an integer selected
from a menu (or "0" for quit). If something invalid is entered, like
"x" or ".", the program enters a neverending loop. This seems to be a
common problem for n00bs as I have researched it on Google. I have
found workarounds to detect invalid input, but they all seem to cause
"0" and invalid input to be read the same. The value is being read to
an "int" variable. Can anyone help with that one? Thanks again for
all the help.
http://www.parashift.com/c++-faq-lit....html#faq-15.3
Dec 21 '06 #13

P: n/a
Caleb a écrit :
std::vector does exactly what I want it to do. It seems to be
extremely advantageous over regular arrays, too. There's just one
thing I'm wondering....is there a way to push_back three elements at
once? For example, I'm going to have a list of door initializations
that look like this:

Foyer.destination.push_back(2);Foyer.destination.p ush_back(3);Foyer.destination.push_back(6);

And that's only for a 3-door room....is there a more efficient way to
code that?
Certainly:
- you can read your data from a file and insert it into a vector
- you can use arrays (http://www.boost.org/doc/html/array/):
boost::array<int,3foyer_dest = { 2, 3, 6 } ;
Foyer.destination.insert(foyer_dest.begin(),foyer_ dest.end());
Dec 21 '06 #14

P: n/a

Caleb wrote:
std::vector does exactly what I want it to do. It seems to be
extremely advantageous over regular arrays, too. There's just one
thing I'm wondering....is there a way to push_back three elements at
once? For example, I'm going to have a list of door initializations
that look like this:

Foyer.destination.push_back(2);Foyer.destination.p ush_back(3);Foyer.destination.push_back(6);

And that's only for a 3-door room....is there a more efficient way to
code that?
You can use something like the code below. Something similar may even
be part of the next version of the C++ standard. Code separates into a
for_each that works on containers or arrays and some custom functors as
examples to use with it. push_back loads a container and output sends
it to output stream. functions below functors just make each functor a
bit more convenient to use.
Can also define your own functors too...

regards
Andy Little

#include <vector>
#include <algorithm>
#include <iostream>

//container for_each
template <typename Container, typename F>
void for_each(Container & c, F const & f)
{
std::for_each(c.begin(),c.end(),f);
}

//array version of for_each
template <typename T,int N,typename F>
void for_each(T (&ar)[N],F const & f)
{
for (int i = 0; i < N;++i){
f(ar[i]);
}
}

// use with foreach to load a std container
// from another container or an array
template <typename Container>
struct push_back_{
Container & c;
push_back_(Container & c_in):c(c_in){}

template <typename T>
void
operator()(T const & t)const
{
return c.push_back(t);
}
};
// function returns functor above
template <typename Container>
inline
push_back_<Containerpush_back(Container & c)
{
return push_back_<Container>(c);
}

// do output
template <typename CharType>
struct output_{
std::basic_ostream<CharType& os;
CharType sep;
output_(
std::basic_ostream<CharType& os_in,
CharType sep_in):os(os_in),sep(sep_in){}

template <typename T>
std::basic_ostream<CharType&
operator()(T const & t)const
{
return os << t << sep;
}
};
// function returns functor above
template <typename CharType>
inline
output_<CharType>
output(std::basic_ostream<CharType>& os, CharType sep)
{
return output_<CharType>(os,sep);
}

// etc
int main()
{
int array [] = {1,2,3,4,5};

std::vector<intvect;

for_each(array,push_back(vect));

for_each(vect,output(std::cout,'\n'));
}

Dec 21 '06 #15

P: n/a
kwikius a écrit :
Caleb wrote:
>std::vector does exactly what I want it to do. It seems to be
extremely advantageous over regular arrays, too. There's just one
thing I'm wondering....is there a way to push_back three elements at
once? For example, I'm going to have a list of door initializations
that look like this:

Foyer.destination.push_back(2);Foyer.destination. push_back(3);Foyer.destination.push_back(6);

And that's only for a 3-door room....is there a more efficient way to
code that?

You can use something like the code below. Something similar may even
be part of the next version of the C++ standard. Code separates into a
for_each that works on containers or arrays and some custom functors as
examples to use with it. push_back loads a container and output sends
itc to output stream. functions below functors just make each functor a
bit more convenient to use.
Can also define your own functors too...

[code]
int main()
{
int array [] = {1,2,3,4,5};

std::vector<intvect;

for_each(array,push_back(vect));

for_each(vect,output(std::cout,'\n'));
}
Yes, you can use the for_each structure but it is expected to be less
efficient than the std::vector::insert method.

I don't see the advantage of defining a for_each specifically for arrays
since there is boost::array that works fine (even though it is not
really a container).

And using POD:
int array [] = {1,2,3,4,5};
std::vector<intvect;
//should work
vect.insert(&array[0],&array[sizeof(array)/sizeof(int)]);
// if you use gcc:
vect.insert(normal_iterator(&array[0]),
normal_iterator(&array[sizeof(array)/sizeof(int)]));

Alternatively, you can use lambda programming:
http://www.boost.org/doc/html/lambda.html
Dec 21 '06 #16

P: n/a

Michael DOUBEZ wrote:
And using POD:
int array [] = {1,2,3,4,5};
std::vector<intvect;
//should work
vect.insert(&array[0],&array[sizeof(array)/sizeof(int)]);
hmm.... clearly superior to:

for_each(array,push_back(vect));

:-)

regards
Andy Little

Dec 21 '06 #17

P: n/a

Michael DOUBEZ wrote:
std::vector<intvect;
//should work
vect.insert(&array[0],&array[sizeof(array)/sizeof(int)]);
FWIW output with your version in VC7.1, gcc4.1 and VC8 ---below.
Which vector::insert signature is it meant to be using?

regards
Andy Little

/*
..
..
..
*/

int main()
{
int array [] = {1,2,3,4,5};

std::vector<intvect;

/* for_each(array,push_back(vect)); */
vect.insert(&array[0],&array[sizeof(array)/sizeof(int)]);
}

Test.cpp
VC7.1 output:

d:\Projects\Test\Test.cpp(80) : error C2664:
'std::vector<_Ty>::iterator
std::vector<_Ty>::insert(std::vector<_Ty>::iterato r,const _Ty &)' :
cannot convert parameter 2 from 'int *__w64 ' to 'const int &'
with
[
_Ty=int
]
Reason: cannot convert from 'int *__w64 ' to 'const int'
This conversion requires a reinterpret_cast, a C-style cast or
function-style cast

/////////////

gcc 4.1 output:
test.cpp: In function 'int main()':
test.cpp:80: error: no matching function for call to 'std::vector<int,
std::allo
cator<int::insert(int*, int*)'
/opt/conceptgcc-4.1.1-alpha-4/lib/gcc/i686-pc-cygwin/4.1.1/../../../../include/c
++/4.1.1/bits/vector.tcc:93: note: candidates are: typename
std::vector<_Tp, _Al
loc>::iterator std::vector<_Tp,
_Alloc>::insert(__gnu_cxx::__normal_iterator<typ
ename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer,
std::vector<_Tp,
_Alloc, const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]
/opt/conceptgcc-4.1.1-alpha-4/lib/gcc/i686-pc-cygwin/4.1.1/../../../../include/c
++/4.1.1/bits/stl_vector.h:651: note: void std::vector<_Tp,
_Alloc>::insert(__g
nu_cxx::__normal_iterator<typename std::_Vector_base<_Tp,
_Alloc>::_Tp_alloc_typ
e::pointer, std::vector<_Tp, _Alloc, size_t, const _Tp&) [with _Tp =
int, _Al
loc = std::allocator<int>]
make: *** [test.o] Error 1

//////////////////

VC8,=.o output:

..\test.cpp(80) : error C2664: 'std::_Vector_iterator<_Ty,_Alloc>
std::vector<_Ty>::insert(std::_Vector_iterator<_Ty ,_Alloc>,const _Ty
&)' : cannot convert parameter 1 from 'int *' to
'std::_Vector_iterator<_Ty,_Alloc>'
with
[
_Ty=int,
_Alloc=std::allocator<int>
]
No constructor could take the source type, or constructor
overload resolution was ambiguous

Dec 21 '06 #18

P: n/a

Michael DOUBEZ wrote:
Alternatively, you can use lambda programming:
http://www.boost.org/doc/html/lambda.html
I would be interested to see what the boost lambda version looks like
too. Not knocking it. Just have no idea. Anyone care to reveal it ?

regards
Andy Little

Dec 21 '06 #19

P: n/a

Michael DOUBEZ wrote:
I don't see the advantage of defining a for_each specifically for arrays
since there is boost::array that works fine (even though it is not
really a container).
I covered that in the example code FWIW. If you want to use
boost::array ( or another container) you can do, but you have to
specify the size, which can be inconvenient when adding stuff to the
initialiser list.
int main()
{
// int array [] = {1,2,3,4,5};

boost::array<int,5array = {1,2,3,4,5};

std::vector<intvect;

for_each(array,push_back(vect));

for_each(array,output(std::cout,'\n'));

}

regards
Andy Little

Dec 21 '06 #20

P: n/a
kwikius a écrit :
Michael DOUBEZ wrote:
>And using POD:
int array [] = {1,2,3,4,5};
std::vector<intvect;
//should work
vect.insert(&array[0],&array[sizeof(array)/sizeof(int)]);

hmm.... clearly superior to:

for_each(array,push_back(vect));

:-)
Yes, I agree that POD usage in this case is as clear as the bottom of my
boots. ;)

And you are right, it doesn't work any more (I used to do that before
iterators became iterators :) ) but I am sure one can easily design
something like the normal_iterator in no time.

Regards,
Michael
Dec 21 '06 #21

P: n/a
kwikius a écrit :
Michael DOUBEZ wrote:
>Alternatively, you can use lambda programming:
http://www.boost.org/doc/html/lambda.html

I would be interested to see what the boost lambda version looks like
too. Not knocking it. Just have no idea. Anyone care to reveal it ?
With your notation:

for_each(array,vect.push_back(_1));
Michael
Dec 21 '06 #22

P: n/a
Michael DOUBEZ a écrit :
kwikius a écrit :
>Michael DOUBEZ wrote:
>>Alternatively, you can use lambda programming:
http://www.boost.org/doc/html/lambda.html

I would be interested to see what the boost lambda version looks like
too. Not knocking it. Just have no idea. Anyone care to reveal it ?

With your notation:

for_each(array,vect.push_back(_1));
I was quick:
for_each(array,bind(&std::vector::push_back,vect,_ 1));

Sorry
Michael
Dec 21 '06 #23

P: n/a

Michael DOUBEZ wrote:
Michael DOUBEZ a écrit :
kwikius a écrit :
Michael DOUBEZ wrote:

Alternatively, you can use lambda programming:
http://www.boost.org/doc/html/lambda.html

I would be interested to see what the boost lambda version looks like
too. Not knocking it. Just have no idea. Anyone care to reveal it ?
With your notation:

for_each(array,vect.push_back(_1));

I was quick:
for_each(array,bind(&std::vector::push_back,vect,_ 1));
Unfortunately if you run it you will find there is a problem:

int main()
{
// int array [] = {1,2,3,4,5};

boost::array<int,5array = {1,2,3,4,5};

std::vector<intvect;

for_each(array,boost::bind(&std::vector<int>::push _back,vect,_1));
//for_each(array,push_back(vect));
std::cout << "elements in vect= " << vect.size() <<'\n';
for_each(vect,output(std::cout,'\n'));

}
This compiles and runs but doesnt do what it should. OTOH array version
fails with some const non const issue.

Question is how complicated are we prepared to get in the interests of
simplicity ;-)

I'm also quite amused that my custom for_each came in handier than the
official version ;-)

That said I bet we get lambda in the next version of the standard, but
no simple for_each. They'll not miss an opportunity to make the
blindingly simple impossibly complicated :-)

regards
Andy Little

Dec 21 '06 #24

P: n/a
Okay, thanks for all the help, it's very much appreciated, I'm just
going to keep doing the room exits the way I'm doing them....it's
working out just fine ;)

Dec 21 '06 #25

P: n/a

kwikius wrote in message ...
>
Michael DOUBEZ wrote:
>I don't see the advantage of defining a for_each specifically for arrays
since there is boost::array that works fine (even though it is not
really a container).

I covered that in the example code FWIW. If you want to use
boost::array ( or another container) you can do, but you have to
specify the size, which can be inconvenient when adding stuff to the
initialiser list.

int main(){
// int array [] = {1,2,3,4,5};
boost::array<int,5array = {1,2,3,4,5};
std::vector<intvect;
for_each(array,push_back(vect));
for_each(array,output(std::cout,'\n'));
}
regards
Andy Little
Why not?:

int main(){
int array[] = {1,2,3,4,5};
std::vector<intvect( array, array+(sizeof array/sizeof *array) );

std::copy( vect.begin(), vect.end(),
std::ostream_iterator<int>(std::cout, " ") );
return 0;
}

Sorry, I must have missed a point somewhere. :-}
Were you guys trying to find a home for 'for_each' or Boost?

--
Bob R
POVrookie
Dec 21 '06 #26

P: n/a

BobR wrote:
kwikius wrote in message ...

Michael DOUBEZ wrote:
I don't see the advantage of defining a for_each specifically for arrays
since there is boost::array that works fine (even though it is not
really a container).
I covered that in the example code FWIW. If you want to use
boost::array ( or another container) you can do, but you have to
specify the size, which can be inconvenient when adding stuff to the
initialiser list.

int main(){
// int array [] = {1,2,3,4,5};
boost::array<int,5array = {1,2,3,4,5};
std::vector<intvect;
for_each(array,push_back(vect));
for_each(array,output(std::cout,'\n'));
}
regards
Andy Little

Why not?:

int main(){
int array[] = {1,2,3,4,5};
std::vector<intvect( array, array+(sizeof array/sizeof *array) );
Why not? Because Its a mess! 2 sizeof, raw pointers and 4 repeats of
the array variable.
Yuch. If you read the O.P you also need to assign that. So we have:

vect = std::vector<int>( array, array+(sizeof array/sizeof
*array) );

compared with :

for_each(array,push_back(vect));

What is loverly concise and expressive in comparison withe the previous
coding crime!
Sorry, I must have missed a point somewhere. :-}
Maybe... Its my fault I guess, for casting my pearls before swine ...

:-)

regards
Andy Little

Dec 22 '06 #27

P: n/a
kwikius a écrit :
Michael DOUBEZ wrote:
>Michael DOUBEZ a écrit :
>>kwikius a écrit :
Michael DOUBEZ wrote:

Alternatively, you can use lambda programming:
http://www.boost.org/doc/html/lambda.html
I would be interested to see what the boost lambda version looks like
too. Not knocking it. Just have no idea. Anyone care to reveal it ?

With your notation:

for_each(array,vect.push_back(_1));
I was quick:
for_each(array,bind(&std::vector::push_back,vect, _1));

Unfortunately if you run it you will find there is a problem:

int main()
{
// int array [] = {1,2,3,4,5};

boost::array<int,5array = {1,2,3,4,5};

std::vector<intvect;

for_each(array,boost::bind(&std::vector<int>::push _back,vect,_1));
//for_each(array,push_back(vect));
std::cout << "elements in vect= " << vect.size() <<'\n';
for_each(vect,output(std::cout,'\n'));

}
This compiles and runs but doesnt do what it should. OTOH array version
fails with some const non const issue.

Question is how complicated are we prepared to get in the interests of
simplicity ;-)

I'm also quite amused that my custom for_each came in handier than the
official version ;-)

That said I bet we get lambda in the next version of the standard, but
no simple for_each. They'll not miss an opportunity to make the
blindingly simple impossibly complicated :-)
True but I am not a specialist of lambda programing :)
The main advantage I saw was the following notation:
for_each(vect,std::cout<<_1<<'\n');

It is true that in this case, your way is more elegant but then again I
expect a single call to std::vector::insert to be more efficient (which
is of no import here) because beeing able to compute the distance
between begin() and end() he can allocate the memory (or fail to do it)
at once and make only one move of objects. I have to check this in the
implementation of gcc.

Before calling your function, I would have to call std::vector::reserve
or use the following implementation:
template <typename T,int N>
void vector_insert(std::vector<T&v, T (&ar)[N])
{
v.reserve(v.size()+N);
for (int i = 0; i < N;++i){
v.push_back(ar[i]);
}
}

and then :
vector_insert(vect,array);

I hope the compiler inlines the functions correctly, otherwise I may
have a function for each size of array I use (which is not the case
begin/end range).

Michael
Dec 22 '06 #28

P: n/a

kwikius wrote in message ...
>
>Sorry, I must have missed a point somewhere. :-}

Maybe... Its my fault I guess, for casting my pearls before swine ...
:-)
Oink.

--
Bob R
POVrookie
Dec 22 '06 #29

This discussion thread is closed

Replies have been disabled for this discussion.