Tuesday, January 26, 2010

comp.lang.c++ - 25 new messages in 12 topics - digest

comp.lang.c++
http://groups.google.com/group/comp.lang.c++?hl=en

comp.lang.c++@googlegroups.com

Today's topics:

* writing binary files - 7 messages, 3 authors
http://groups.google.com/group/comp.lang.c++/t/3acbfe82ba5d0012?hl=en
* Virtual construtors - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.c++/t/aea7843ff0dd519f?hl=en
* STL/CLR library in Visual Studio 2008 - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c++/t/2108ce8aea45b62f?hl=en
* std::not1() doesn't accept a function pointer - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/940b7aa3b05d8e70?hl=en
* Object (de)serialization - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/9fc67e8f28fe4918?hl=en
* complex struct - 2 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/59f0b47ab3f08848?hl=en
* How to copy vector? - 4 messages, 3 authors
http://groups.google.com/group/comp.lang.c++/t/4adcee4457a06858?hl=en
* How to identify the exe file associated with core dump - 1 messages, 1
author
http://groups.google.com/group/comp.lang.c++/t/ae385d53872a2543?hl=en
* Support for export keyword ? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/0878ed0c9c1ca584?hl=en
* memory leaks - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/d9b20823062f2cb3?hl=en
* Type of elements of std::string - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/b6aba4785e69df38?hl=en
* generate rand number - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/fcb11e63c73e0db8?hl=en

==============================================================================
TOPIC: writing binary files
http://groups.google.com/group/comp.lang.c++/t/3acbfe82ba5d0012?hl=en
==============================================================================

== 1 of 7 ==
Date: Tues, Jan 26 2010 12:51 pm
From: "John H."


On Jan 26, 1:50 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
> operator<<
> converts the internal representation of the double into a string of
> characters and then writes that out.

That is correct. Don't use the ofstream::operator<<(double) to
achieve binary output.


== 2 of 7 ==
Date: Tues, Jan 26 2010 2:20 pm
From: "Thomas J. Gritzan"


Am 26.01.2010 20:50, schrieb Victor Bazarov:
>> On Jan 26, 10:31 am, aaragon <alejandro.ara...@gmail.com> wrote:
>>> double test = 10.;
>>> fout.write((char*)&test, sizeof(double));
>>> Is there a way to
>>> better write this line? I really want to avoid the C way of casting.
[...]
> To OP: don't do C style casting, do 'static_cast'. That's what it is
> for (among other things).

But static_cast won't cast a double* to a char*. You'ld need to double
cast: static_cast<char*>(static_cast<void*>(&test)).

--
Thomas


== 3 of 7 ==
Date: Tues, Jan 26 2010 4:25 pm
From: "John H."


On Jan 26, 4:20 pm, "Thomas J. Gritzan" <phygon_antis...@gmx.de>
wrote:
> But static_cast won't cast a double* to a char*. You'ld need to double
> cast: static_cast<char*>(static_cast<void*>(&test)).

He could try a reinterpret cast:
fout.write(reinterpret_cast<char*>(&test), sizeof(double));

Unions will probably work on your compiler:
union
{
double as_double;
char as_bytes[sizeof(double)];
};
as_double = test;
fout.write(as_bytes, sizeof(double));
although I am not sure if this is guaranteed by the standard.


== 4 of 7 ==
Date: Tues, Jan 26 2010 5:33 pm
From: James Kanze


On Jan 26, 4:31 pm, aaragon <alejandro.ara...@gmail.com> wrote:

> I'm experimenting with binary files, and it seems pretty
> straightforward. It seems that I have to use the read and
> write member functions, inherited by ostream. However, there
> is something I really don't like about using this function and
> I want to know if there is a way to avoid it.

> Let's say you're writing an double to the binary file, a very simple
> example:

> int main() {
> std::ofstream fout("test.out", std::ofstream::binary);
> double test = 10.;
> fout.write((char*)&test, sizeof(double));
> fout.close();
> return 0;
> }

> I hate to see the C cast in the write function. Is there a way
> to better write this line? I really want to avoid the C way of
> casting.

For starters, your code doesn't make sense, and doesn't do
anything useful. You can't necessarily reread anything written
this way. (There are specific cases where you can, but until
you understand what you are doing, you can't really determine
what they are.)

For starters, define exactly what you want to write, and how
you intend to read it (and possibly who might have to read it).
Then format the double into a buffer according to your
definition, and write that. (You might still want to use a
buffer of unsigned char, in which case, you will need a
reinterpret_cast when caling write.)

--
James Kanze


== 5 of 7 ==
Date: Tues, Jan 26 2010 5:37 pm
From: James Kanze


On Jan 26, 5:31 pm, Öö Tiib <oot...@hot.ee> wrote:
> On Jan 26, 6:31 pm, aaragon <alejandro.ara...@gmail.com> wrote:
> > I'm experimenting with binary files, and it seems pretty
> > straightforward. It seems that I have to use the read and
> > write member functions, inherited by ostream. However, there
> > is something I really don't like about using this function
> > and I want to know if there is a way to avoid it.

> > Let's say you're writing an double to the binary file, a very simple
> > example:

> > int main() {

> > std::ofstream fout("test.out", std::ofstream::binary);
> > double test = 10.;
> > fout.write((char*)&test, sizeof(double));

> You can use C++ cast there:
> fout.write( reinterpret_cast<char*>(&test),
> sizeof(double) );

Which does make it clearer that what he's doing isn't likely to
work.

> > fout.close();

> close() is not needed, ofstream destructor does it.

Not really. He's forgotten an important part: you have to check
the status of the stream after the close.

> > return 0;

And return EXIT_ERROR if it's not OK. (The only time counting
on the close in the destructor is acceptable is in case of a
lower level error, when you're going to delete the file and
return an error status anyway.)

> > }

> > I hate to see the C cast in the write function. Is there a
> > way to better write this line? I really want to avoid the C
> > way of casting.

> Bare binary form is probably bad idea to serialize something.
> On platform you write the sizes alignments and so on may be
> different than on platform you read.

> Better write some supporting information too, what it is and
> how lot of bytes it contains (it is called TLV
> tag-length-value). Use memcpy() to copy all such information
> into char vector and then write it to file all at once.
> memcpy() takes void* and you must not cast anything into void*
> that does not do so silently.

memcpy also just copies the bits of the internal representation,
so it is generally not a good idea either.

--
James Kanze


== 6 of 7 ==
Date: Tues, Jan 26 2010 5:41 pm
From: James Kanze


On Jan 26, 7:50 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
> John H. wrote:
> > On Jan 26, 10:31 am, aaragon <alejandro.ara...@gmail.com> wrote:
> >> double test = 10.;
> >> fout.write((char*)&test, sizeof(double));
> >> Is there a way to
> >> better write this line? I really want to avoid the C way of casting.

> > You might leverage the << operator:

> > #include <fstream>

> > int main()
> > {
> > std::ofstream fout("Test.out", std::ofstream::binary);
> > double test_out = 10.;

> > //fout.write((char*)&test_out, sizeof(double));
> > fout << test_out;
> > fout.close();

> > std::ifstream fin("Test.out", std::ifstream::binary);
> > double test_in = 0.0;
> > fin >> test_in;

> > return 0;
> > }

> The fact that round trip delivers the same value (likely)

Unlikely, in the case of double (except for a few privileged
values like 0.0). Unless you explicitly set the precision---by
default, it's only 6 digits, which is far from enough for a
round trip.

Writing two values one directly after the other isn't likely to
work either. You'll need some sort of separator.

> does not actually demonstrate the writing to the binary file.
> operator<< converts the internal representation of the double
> into a string of characters and then writes that out. That,
> IIUIC, is not what the OP wanted.

> To OP: don't do C style casting, do 'static_cast'. That's
> what it is for (among other things).

Exactly. And the fact that it won't compile here is a strong
indication that you're doing something wrong.

--
James Kanze


== 7 of 7 ==
Date: Tues, Jan 26 2010 5:43 pm
From: James Kanze


On Jan 27, 12:25 am, "John H." <oldman_fromt...@yahoo.com> wrote:
> On Jan 26, 4:20 pm, "Thomas J. Gritzan" <phygon_antis...@gmx.de>
> wrote:

> > But static_cast won't cast a double* to a char*. You'ld need to double
> > cast: static_cast<char*>(static_cast<void*>(&test)).

> He could try a reinterpret cast:
> fout.write(reinterpret_cast<char*>(&test), sizeof(double));

> Unions will probably work on your compiler:
> union
> {
> double as_double;
> char as_bytes[sizeof(double)];
> };
> as_double = test;
> fout.write(as_bytes, sizeof(double));
> although I am not sure if this is guaranteed by the standard.

It's undefined behavior. And probably won't work, unless the
internal representation on your machine happens to correspond
exactly to the external format. (Not generally the case for
PC's, since the external formats are generally based on VAXes or
earlier processors.)

--
James Kanze

==============================================================================
TOPIC: Virtual construtors
http://groups.google.com/group/comp.lang.c++/t/aea7843ff0dd519f?hl=en
==============================================================================

== 1 of 3 ==
Date: Tues, Jan 26 2010 1:18 pm
From: Joshua Maurice


On Jan 26, 10:34 am, Mukesh <mukeshs...@gmail.com> wrote:
> Why dont we have virtual constructors?

Generally, a virtual call goes to a particular function definition
based on the type of the most derived complete object it acts on. A
constructor is first called before the object it acts on exists, so
you can't do that same lookup. What semantics do you propose virtual
constructors have?


== 2 of 3 ==
Date: Tues, Jan 26 2010 3:50 pm
From: red floyd


On Jan 26, 10:34 am, Mukesh <mukeshs...@gmail.com> wrote:
> Why dont we have virtual constructors?

This is a FAQ. Please see the FAQ, in particular FAQ 20.8

http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8


== 3 of 3 ==
Date: Tues, Jan 26 2010 5:28 pm
From: James Kanze


On Jan 26, 6:34 pm, Mukesh <mukeshs...@gmail.com> wrote:
> Why dont we have virtual constructors?

Because virtual functions are dispatched on the type of an
existing object, and when you use a constructor, there is no
existing object.

--
James Kanze

==============================================================================
TOPIC: STL/CLR library in Visual Studio 2008
http://groups.google.com/group/comp.lang.c++/t/2108ce8aea45b62f?hl=en
==============================================================================

== 1 of 2 ==
Date: Tues, Jan 26 2010 1:22 pm
From: Öö Tiib


On Jan 26, 8:59 pm, Vicent Giner-Bosch <vgi...@gmail.com> wrote:
> This is a question related with Visual Studio 2008 --I hope you don't
> mind.   ;-)
>
> At  http://msdn.microsoft.com/es-es/library/bb385954.aspx  they say
> that "The STL/CLR Library is a packaging of the Standard Template
> Library (STL), a subset of the Standard C++ Library, for use with C++
> and the .NET Framework common language runtime (CLR). With STL/CLR,
> you can use all the containers, iterators, and algorithms of STL in a
> managed environment."
>
> If I am not going to use .NET features, but only "Visual Studio" ones,
> do I need STL/CLR library, or not? What does exactly "a managed
> environment" mean??

Microsoft has useful real C++ compiler in Visual Studio 2008. That
compiles real C++. It compiles quite well. If you do not want .NET
then you can use that C++ compiler just fine but everything 'managed'
turn off.

A "managed environment" there means .NET byte-code. In connection with
C++ it means a ghoul. It is a thing MS calls C++/CLI. It is undead C+
+, and .NET byte-code runs in its veins. If you want to use .NET then
write software in Visual Basic or C# but keep away from that ugly
abomination. In this newsgroup it is dangerous to mention it, people
may think you are infected. ;)


== 2 of 2 ==
Date: Tues, Jan 26 2010 1:24 pm
From: Victor Bazarov


Öö Tiib wrote:
> [..]
> A "managed environment" there means .NET byte-code. In connection with
> C++ it means a ghoul. It is a thing MS calls C++/CLI. It is undead C+
> +, and .NET byte-code runs in its veins. If you want to use .NET then
> write software in Visual Basic or C# but keep away from that ugly
> abomination. In this newsgroup it is dangerous to mention it, people
> may think you are infected. ;)

.. and they will try to shoot you in the head! :-)

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

==============================================================================
TOPIC: std::not1() doesn't accept a function pointer
http://groups.google.com/group/comp.lang.c++/t/940b7aa3b05d8e70?hl=en
==============================================================================

== 1 of 1 ==
Date: Tues, Jan 26 2010 1:37 pm
From: Pete Becker


Juha Nieminen wrote:
> Basically any STL algorithm which requires a predicate as parameter
> can be given either a function object or a regular function as that
> parameter. For example, you can give a function object or a regular
> function pointer as the third parameter to std::remove_if(), and it
> will work ok.
>
> If you want to *negate* the predicate, you can do it with std::not1().
> However, for some reason std::not1() can only be called with a function
> object, not a function pointer. If you want to use it with a regular
> function, you have to do it like std::not1(std::ptr_fun(theFunction)).
>
> But why? Why couldn't std::not1() accept a regular function as parameter?
>

Because it has to return an object whose type has a couple of nested
typedefs, and their definitions are propagated from the type that you
instantiate it with. A pointer to function doesn't have those typedefs,
so can't be used here. The same problem arises with not2, bind1st and
bind2nd. The solution is to wrap the function pointer in a type that
provides those typedefs, using ptr_fun.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of
"The Standard C++ Library Extensions: a Tutorial and Reference"
(www.petebecker.com/tr1book)

==============================================================================
TOPIC: Object (de)serialization
http://groups.google.com/group/comp.lang.c++/t/9fc67e8f28fe4918?hl=en
==============================================================================

== 1 of 1 ==
Date: Tues, Jan 26 2010 2:38 pm
From: "Thomas J. Gritzan"


Am 26.01.2010 01:19, schrieb Philip Pemberton:
> On Mon, 25 Jan 2010 21:31:55 +0100, Thomas J. Gritzan wrote:
>> But instead using this prototype based meachanism, I suggest using a
>> factory functor and storing a boost::function in creationMap, if you
>> have access to Boost (std::tr1::function is the same). Example:
> (snip code)
>
> That looks better than my solution, but I'm not keen on adding Boost to
> my application's build dependencies. As nice as it is, it's an utter pig
> to build on Win32 (IIRC last time I did it, I had to build Cmake, which
> was great fun). Dead easy on *nix, but unfortunately this code has to
> work in the Evil Empire too...

1) Most of Boost's code is header only, so you don't need to build
anything. Just put the headers somewhere and add the path to the
compiler's include path.
2) If your compiler supports TR1, it has std::tr1::function, which is
practically the same.
TR1 has some really nice classes like random number generators, regular
expression parsers, smart pointers and std::tr1::function.
See <http://en.wikipedia.org/wiki/C%2B%2B_Technical_Report_1>.

AFAIK, Visual Studio 2008 comes with TR1 support since Service Pack 1.

> The only other thing I'm not keen on is having to hack around with main()
> to add new chunks, although that's probably solvable by putting the
> registration stuff in a static class's ctor or a global
> RegisterChunkDeserialisers() function.
>
> Still not as nice as just being able to create a module with two classes,
> and have that module auto-initialise and register on startup (see
> TriangleInitialiser above). But that said, I'm still concerned about what
> happens if the TriangleInitialiser object gets initialised before
> Shape... unless the compiler is clever enough to figure out that Shape
> needs setting up first (probably not, even though it is gcc).

[10.13] How do I prevent the "static initialization order fiasco"?
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.13

--
Thomas

==============================================================================
TOPIC: complex struct
http://groups.google.com/group/comp.lang.c++/t/59f0b47ab3f08848?hl=en
==============================================================================

== 1 of 2 ==
Date: Tues, Jan 26 2010 2:53 pm
From: "Larry"


"John H." <oldman_fromthec@yahoo.com> ha scritto nel messaggio
news:c0811d16-94a8-491c-a610-531eb5fac302@c34g2000yqn.googlegroups.com...

> Since you didn't talk much about what you are trying to do, I can only
> speculate, but I am guessing that your design here is not doing what
> you want it to.

This is what I am tring to do: a tiny streaming server to stream to at least
a couple of clients at the same time. (capturing from a given wave in
device, mp3 encoding and streaming) for the moment I am coding the server
part:

#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <process.h>
#include <cstdlib>
#include <ctime>
#include "socket.h"
#include <boost/circular_buffer.hpp>
using namespace std;
using namespace boost;

const string CRLF = "\r\n";
const int numbuff = 3;
const int buflen = 30;

unsigned int __stdcall Consumer(void* sock);
unsigned int __stdcall Producer(void*);

void getDateTime(char * szTime);

struct buffer
{
unsigned char data[1024];
int bytesRecorded;
int user;
buffer(const unsigned char * data_, const int bytesRecorded_, const int
user_) :
bytesRecorded(bytesRecorded_), user(user_)
{
copy(data_, data_ + bytesRecorded_, data);
}
};

struct circular
{
circular_buffer<buffer> cb[numbuff];
circular_buffer<buffer>::const_iterator it;
};

map<int, circular> users;
map<int, circular>::iterator uit;

int main()
{
// Launch Producer
unsigned int prodRet;
_beginthreadex(0,0,Producer,NULL,0,&prodRet);
if(prodRet)
cout << "Launched Producer Thread!" << endl;

// Set up server (port: 8000, maxconn: 10)
SocketServer sockIn(8000, 10);

while(1)
{
// ...wait for incoming connections...
Socket* s = sockIn.Accept();
unsigned int sockRet;
_beginthreadex(0,0,Consumer,s,0,&sockRet);
if(sockRet)
cout << "Spawned a new thread!" << endl;
else
cout << "Thread error!" << endl;
}

sockIn.Close();

system("pause");
return EXIT_SUCCESS;
}

// Consumer
unsigned int __stdcall Consumer(void* sock)
{
Socket* s = (Socket*) sock;

s->SendBytes("Hello World!" + CRLF);

int threadid = (int)GetCurrentThreadId();

// Prepare & add circular buffer to the map
circular c;
c.cb->push_back(buffer(NULL,0,0));
c.cb->push_back(buffer(NULL,0,0));
c.cb->push_back(buffer(NULL,0,0));

users.insert(make_pair(threadid, c));

// TODO:
// Read data from the buffer
// and send it to the client
Sleep(10000);

// Remove buffer from the map
users.erase(threadid);

// Say bye to the client
s->SendBytes("Bye bye!" + CRLF);

// Disconnect client
cout << "Closing thread..." << endl;
s->Close();
delete s;
return 0;
}

// Producer
unsigned int __stdcall Producer(void*)
{
while(1)
{
Sleep(1000);
char szTime[30]; getDateTime(szTime);
for(uit=users.begin(); uit!=users.end(); ++uit)
{
users[uit->first].cb->push_back(buffer((unsigned char*)szTime, 30, 1));
cout << "Producer is writing to: " << uit->first << endl;
}
}
return 0;
}

void getDateTime(char * szTime)
{
time_t rawtime = time(NULL);
struct tm timeinfo;
gmtime_s(&timeinfo, &rawtime);
strftime(szTime, 30, "%a, %d %b %Y %X GMT", &timeinfo);
}

thanks

== 2 of 2 ==
Date: Tues, Jan 26 2010 3:54 pm
From: "Larry"


"John H." <oldman_fromthec@yahoo.com> ha scritto nel messaggio
news:c0811d16-94a8-491c-a610-531eb5fac302@c34g2000yqn.googlegroups.com...

> Since you didn't talk much about what you are trying to do, I can only
> speculate, but I am guessing that your design here is not doing what
> you want it to.

anyway,before I was doing:

struct buffer
{
char data[1024];
int bytesRecorded;
buffer(const char * data_, const int bytesRecorded_) :
bytesRecorded(bytesRecorded_)
{
copy(data_, data_ + (bytesRecorded_ * sizeof(char)), data);
}
};

int main()
{
circular_buffer<buffer> cb(numbuff);

// Insert elements
cout << "Push elements:" << endl;
for(int i = 0; i < 10; i++)
{
char szTime[30]; getDateTime(szTime);

cb.push_back( buffer(szTime, 30) );

cout << szTime << endl;

Sleep(1000);
}

// Show elements:
cout << "Show elements:" << endl;
for(int i = 0; i<(int)cb.size(); i++)
{
cout << &cb[i].data[0] << endl;
}

system("pause");
return EXIT_SUCCESS;
}

that worked great! But now I needed to to something like:

std::map<int, circular_buffer<buffer> cb(numbuff)> users

which is impossible, that's why I thought I'd wrap up into another struct:

struct circular
{
circular_buffer<buffer> cb[numbuff];
};

so that I should do:

std::map<int, circular> users

but that led me to some problems...


==============================================================================
TOPIC: How to copy vector?
http://groups.google.com/group/comp.lang.c++/t/4adcee4457a06858?hl=en
==============================================================================

== 1 of 4 ==
Date: Tues, Jan 26 2010 3:49 pm
From: Immortal Nephi


I create two vector variables. First variable: data is initialized
with integers. Second variable: copyData is empty. Both have same
sizes.
How do I write correct code to copy all elements from data to
copyData? I don't have to go through iterator loop to copy each
element.
I want to know that vector data should be auto storage in the global
function's stack frame. Then, the return type will be vector to copy
all elements.
If result size is different and is more than 100 elements, will
copyData be automatically resized?

vector< int > foo()
{
int numData = 1;
vector< int > result;
result.resize( 100 );

for( vector< int >::iterator it = result.begin();
it != result.end(); ++it )
*it = numData++;

return result;
}

int main()
{
vector< int > copyData;
copyData.resize( 100 );

copyData = foo();

return 0;
}


== 2 of 4 ==
Date: Tues, Jan 26 2010 4:58 pm
From: "Alf P. Steinbach"


* Immortal Nephi:
> I create two vector variables. First variable: data is initialized
> with integers. Second variable: copyData is empty. Both have same
> sizes.

'copyData' contains 100 zeroes.


> How do I write correct code to copy all elements from data to
> copyData?

Just an assignment (for example), as you do below.


> I don't have to go through iterator loop to copy each
> element.
> I want to know that vector data should be auto storage in the global
> function's stack frame. Then, the return type will be vector to copy
> all elements.
> If result size is different and is more than 100 elements, will
> copyData be automatically resized?

Yes.


> vector< int > foo()
> {
> int numData = 1;
> vector< int > result;
> result.resize( 100 );
>
> for( vector< int >::iterator it = result.begin();
> it != result.end(); ++it )
> *it = numData++;
>
> return result;
> }

You could write this more easily as

vector<int> foo()
{
vector<int> result;
for( int i = 1; i <= 100; ++i )
{
result.push_back( i );
}
return result;
}


> int main()
> {
> vector< int > copyData;
> copyData.resize( 100 );

This size specification is not necessary.


> copyData = foo();
>
> return 0;

And this 'return' isn't necessary either. 'main' returns 0 by default. :-)


> }


Cheers & hth.,

- Alf


== 3 of 4 ==
Date: Tues, Jan 26 2010 5:00 pm
From: Victor Bazarov


Immortal Nephi wrote:
> I create two vector variables. First variable: data is initialized
> with integers. Second variable: copyData is empty. Both have same
> sizes.

It is customary to describe what *type* your variables have. 'vector'
(or, rather, 'std::vector') is a template, which has to be instantiated
with a type (at least).

> How do I write correct code to copy all elements from data to
> copyData?

How do you copy a 'double'? You assign it. What about a 'bool'? You
assign it. Why do you think it's different with 'std::vector'? It's
not. You simply assign it.

> I don't have to go through iterator loop to copy each
> element.

No, you don't.

> I want to know that vector data should be auto storage in the global
> function's stack frame.

Huh?

> Then, the return type will be vector to copy
> all elements.
> If result size is different and is more than 100 elements, will
> copyData be automatically resized?

Uh... Assignment takes care of everything, if that's what you're asking.

>
> vector< int > foo()
> {
> int numData = 1;
> vector< int > result;
> result.resize( 100 );
>
> for( vector< int >::iterator it = result.begin();
> it != result.end(); ++it )
> *it = numData++;
>
> return result;
> }

Looks good. Or, you could simply do

int numData = 1;
vector<int> result;
for (int i = 0; i < 100; i++)
result.push_back(numData++);

(or drop 'numData' altogether and push 'i').

>
> int main()
> {
> vector< int > copyData;
> copyData.resize( 100 );

No need to resize.
>
> copyData = foo();

That's just fine. Or, you could simply initialise it with the return
value of 'foo()':

vector<int> copyData = foo();

>
> return 0;
> }

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


== 4 of 4 ==
Date: Tues, Jan 26 2010 6:02 pm
From: Immortal Nephi


On Jan 26, 7:00 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
> Immortal Nephi wrote:
> >    I create two vector variables.  First variable: data is initialized
> > with integers.  Second variable: copyData is empty.  Both have same
> > sizes.
>
> It is customary to describe what *type* your variables have.  'vector'
> (or, rather, 'std::vector') is a template, which has to be instantiated
> with a type (at least).
>
> >    How do I write correct code to copy all elements from data to
> > copyData?
>
> How do you copy a 'double'?  You assign it.  What about a 'bool'?  You
> assign it.  Why do you think it's different with 'std::vector'?  It's
> not.  You simply assign it.
>
>  >  I don't have to go through iterator loop to copy each
>
> > element.
>
> No, you don't.
>
> >    I want to know that vector data should be auto storage in the global
> > function's stack frame.
>
> Huh?
>
>  >  Then, the return type will be vector to copy
>
> > all elements.
> >    If result size is different and is more than 100 elements, will
> > copyData be automatically resized?
>
> Uh...  Assignment takes care of everything, if that's what you're asking.
>
>
>
> > vector< int > foo()
> > {
> >    int numData = 1;
> >    vector< int > result;
> >    result.resize( 100 );
>
> >    for( vector< int >::iterator it = result.begin();
> >            it != result.end(); ++it )
> >            *it = numData++;
>
> >    return result;
> > }
>
> Looks good.  Or, you could simply do
>
>     int numData = 1;
>     vector<int> result;
>     for (int i = 0; i < 100; i++)
>        result.push_back(numData++);
>
> (or drop 'numData' altogether and push 'i').
>
>
>
> > int main()
> > {
> >    vector< int > copyData;
> >    copyData.resize( 100 );
>
> No need to resize.
>
>
>
> >    copyData = foo();
>
> That's just fine.  Or, you could simply initialise it with the return
> value of 'foo()':
>
>      vector<int> copyData = foo();
>
>
>
> >    return 0;
> > }
Victor,

Thank you for your assistance. I have another question. First
variable has 640 elements. Second variable has only 64 elements.
They look like ten 2D images with 64 area of elements.

I can't use assignment to copy one out of ten images. Do I need to
use memory address with offset? Or I have to use three dimension
array?

vector< int > foo()
{
static const int TwoDimensionArray = 10;
static const int Width = 8;
static const int Height = 8;

vector< int > result;
result.resize( TwoDimensionArray * Width * Height );
// or vector< int > result[ TwoDimensionArray ][ Width ][ Height ];

for( int i = 0; i != result.size(); ++i )
result.push_back( i );

return result; // I want to copy only one image with 64 elements with
memory address
// or return result[5][0][0];
}

==============================================================================
TOPIC: How to identify the exe file associated with core dump
http://groups.google.com/group/comp.lang.c++/t/ae385d53872a2543?hl=en
==============================================================================

== 1 of 1 ==
Date: Tues, Jan 26 2010 4:49 pm
From: James Kanze


On Jan 25, 10:27 am, Richard Herring <junk@[127.0.0.1]> wrote:
> In message
> <41bbc3e2-fde8-431d-b065-fc0782b62...@g29g2000yqe.googlegroups.com>,
> mthread <rjk...@gmail.com> writes>Hi,
> >We have multiple applications(C & C++) running in our system.
> >When a core dump is generated we did not know which
> >application caused the core dump. Is there a way to find the
> >application name from the core dump file. Kindly help me on
> >this issue.

> This has nothing to do with C++ (or C): your question would be
> identical if the applications were written in Fortran or
> COBOL.. You're more likely to get a useful response by asking
> in a newsgroup that deals with your particular operating
> system.

That's true, but there's a rather obvious answer (which is valid
for all systems---and all languages): the core dump is from the
program which crashed; i.e. which didn't finish its job.

--
James Kanze

==============================================================================
TOPIC: Support for export keyword ?
http://groups.google.com/group/comp.lang.c++/t/0878ed0c9c1ca584?hl=en
==============================================================================

== 1 of 1 ==
Date: Tues, Jan 26 2010 4:59 pm
From: James Kanze


On Jan 25, 5:14 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
> James Kanze wrote:
> > But it doesn't solve the problem. You've shown that in one
> > simple case it can be made to work. That's not what's required.
> > It has to work in all legal cases.

> That's why I asked for examples of export templates which are
> difficult for compilers to implement. All you have said is
> that export templates are difficult, without giving any actual
> examples.

I mentionned several cases in another posting. All it needs is
for some dependent symbol to be defined elsewhere in the
translation unit. A typical example (simplified to the minimum
necessary to show the problem) might be:

Type.hpp:
class Type {};

TypeIO.hpp:
std::ostream operator<<( std::ostream&, Type const& );

User.cpp:
#include "Type.hpp"
#include "TypeIO.hpp"

void f( std::ostream& dest, std::vector< Type > const& objs )
{
std::copy( objs.begin(), objs.end(),
std::ostream_iterator< Type >(dest) );
}

What does the compiler have to include to compile the
instantiation of std::ostream_iterator< Type > at a later point?

--
James Kanze

==============================================================================
TOPIC: memory leaks
http://groups.google.com/group/comp.lang.c++/t/d9b20823062f2cb3?hl=en
==============================================================================

== 1 of 1 ==
Date: Tues, Jan 26 2010 5:05 pm
From: James Kanze


On Jan 25, 7:42 pm, "Alf P. Steinbach" <al...@start.no> wrote:
> * Larry:
> > "Alf P. Steinbach" <al...@start.no> ha scritto nel messaggio
> >news:hjki9g$rc0$1@news.eternal-september.org...
[...]
> More like

> typedef unsigned char Byte;

> struct Something
> {
> vector<Byte> bytes;
> int userId;
> // Constructor etc.
> };

> > what the difference between:
> > --> vector<unsigned char> vuChar;
> > and
> > --> unsigne char buffer[]

> The declaration

> unsigned char buffer[51];

> says that 'buffer' is a contiguous area of memory consisting
> of 51 elements each of type 'unsigned char'.

> The declaration

> vector<unsigned char> v( 51 );

> says that 'v' is a 'vector' which internally holds a pointer
> to a buffer, and that on construction it should create a
> buffer of 51 elements. This can be resized (if necessary the
> vector will discard the original buffer and copy everything
> over to a and sufficiently larger buffer). And you can assign
> to 'v' and generally copy 'v', and be sure that there is no
> memory leak.

In fact, "vector< unsigned char >" is full-fledged type, which
behaves like any other type, where as "unsigned char buffer[ 51 ]"
creates an object of a second class type, which is fairly
broken, and doesn't behave normally.

Also, vector< unsigned char > will normally do bounds checking,
and other important things to avoid undefined behavior.

There are, of course, cases where something like "unsigned char
buffer[ 51 ]" is justified, but they aren't that common.

--
James Kanze

==============================================================================
TOPIC: Type of elements of std::string
http://groups.google.com/group/comp.lang.c++/t/b6aba4785e69df38?hl=en
==============================================================================

== 1 of 1 ==
Date: Tues, Jan 26 2010 5:18 pm
From: James Kanze


On Jan 26, 2:52 pm, Jerry Coffin <jerryvcof...@yahoo.com> wrote:
> In article <Pine.GHP.4.64.1001251045190.17...@kinga.cyf-kr.edu.pl>,
> nbbie...@cyf-kr.edu.pl says...
> > What is actually the type of elements of std::string?

> char. Specifically, the definition of std::string looks like:
> typedef basic_string<char> string;

> > I am trying to read the elements from a stream, in the following
> > way:

> > std::string str = "";
> > int c;

> > // Read string size
> > int n;
> > is >> n;

> > // Read string
> > for(int i=0; i<n; i++)
> > {
> > c = is.get();
> > str += c;
> > }

> Hmm...I think I'd do this more like:

> int n;
> is >> n;

> std::string str(n, ' ');
> is.read(&str[0], n);

> This should eliminate the warning(s), and if there's a
> difference in efficiency, I'd guess it's more likely to favor
> this version than the other. In theory, this isn't entirely
> portable -- the current standard doesn't guarantee that
> std::string will use contiguous storage for the characters. In
> reality, current implementations do use contiguous storage,
> and the next version of the standard will require it, so
> there's not really much chance of a new implementation that
> uses non-contiguous storage.

What happens if there aren't n characters left to read? (And in
fact, I don't know. I practically never use istream::read, and
I don't have any documentation handy to check. But it's
obviously a case which has to be considered.)

More generally, considering the first algorithm: the
no-argument form of istream::get returns an int in order to
return out of band data, e.g. EOF. Once that data has been
tested for and excluded, the resulting value must be converted
to a char. Formally, a rather complex operation, since the
resulting value is in the range 0...UCHAR_MAX, which might not
fit into a char (and if the results don't fit, the behavior is
implementation defined, and might result in a signal).
Practically, implementations which use signed plain char will
always ensure that this works, given that it is such a standard
idiom (in C, at least). But if you really want to avoid it,
something like:

char ch;

// ...
if ( input.get( ch ) ) {
// succeeded, you can safely use ch...
} else {
// error or end of file, the contents of
// ch are unchanged.
}

--
James Kanze

==============================================================================
TOPIC: generate rand number
http://groups.google.com/group/comp.lang.c++/t/fcb11e63c73e0db8?hl=en
==============================================================================

== 1 of 1 ==
Date: Tues, Jan 26 2010 5:25 pm
From: James Kanze


On Jan 26, 1:54 pm, "Larry" <dontmewit...@got.it> wrote:

> I need to create a tiny function to generate a random number
> ranging from: 1000000 to 9999999. Also, the number should be
> unique even if I call the function 100 times in a second...can
> it actually be done?

So which is it? Do the numbers have to be unique, or should
they be random? (One excludes the other -- if they have to be
unique, then they can't be truely random.)

> All I know for the moment is this: srand(time(0)): rand(); but it is not
> that great :-(

The quality of the random number generated in the standard
library is a quality of implementation issue. Some are fairly
good, but a lot are horrid. It's fairly simple to implement
your own, and even simpler to use Boost's functions.

--
James Kanze


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.c++"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.c++?hl=en

To unsubscribe from this group, send email to comp.lang.c+++unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.c++/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

No comments: