473,378 Members | 1,426 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

My first project

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
28 1701

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
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
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
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

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
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
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
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

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
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
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
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
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

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
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

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

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

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

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
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
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
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

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
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

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

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
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

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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: DotNetIsHorrible | last post by:
I write CRUD database applications for a living for an audience of about 100 users per application using classic ASP. I maintain and frequently change on user's request 22 different applications...
6
by: Mark Broadbent | last post by:
this might sound like an obvious question but I have found that usually these two evolve at the same time. One of the biggest reasons for creating the abstraction in the first place (in my...
10
by: Mike L | last post by:
This is for a Win form. Currently, the first record is shown in the combo box. I want the combo box to be blank and when the user clicks on the down arrow to choose from the list and clicks on...
11
by: Larry Bird | last post by:
I'm attempting to build my first VC++ .net project and I'm unable to get a clean compile. Please view code below: // This is the main project file for VC++ application project // generated...
6
by: Frank Wilson | last post by:
Tom, It sounds to me like ASP, not ASP.NET is handling the request for WebForm1.aspx. This is most likely an IIS config issue that may have been caused by order of installation or...
7
by: tshad | last post by:
I have a problem with a VS 2003 project. This project was designed and works fine in VS 2003. But trying to open the project I get the following error....
4
by: nospam | last post by:
I have been running .NET 2003 for some time now. I have been working on the same C++ project for about a year now. All of a sudden, the first file in the project is being built every time I build...
7
by: michigaki | last post by:
hello, we are having problems in compiling a 'slightly' altered x264. We are always receiving a 'helloWorld' undeclared (first use this function) error. We may be commiting a very simple error but...
10
by: KDawg44 | last post by:
Hi, I am new to Python and am trying to write a little front end to another application in Python. What I want is to have a gui pop up listing some items with several buttons. The guts of...
2
by: =?Utf-8?B?SmltIE93ZW4=?= | last post by:
Hi John, Hopefully this post will find its way back to you - or perhaps be answered by someone else. As I mentioned in my last post on the earlier portion of this thread, changing the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.