Saturday, September 26, 2015

Digest for comp.lang.c++@googlegroups.com - 22 updates in 7 topics

Rosario19 <Ros@invalid.invalid>: Sep 26 09:13AM +0200

there is difference in cout output from :
 
cout.width(10);
cout.precision(2);
cout<<123.123;
 
and
 
cout.precision(2);
cout.width(10);
cout<<123.123;
?
Barry Schwarz <schwarzb@dqel.com>: Sep 26 01:23AM -0700

On Sat, 26 Sep 2015 09:13:28 +0200, Rosario19 <Ros@invalid.invalid>
wrote:
 
>cout.width(10);
>cout<<123.123;
>?
 
Not on my system. Maybe you should provide the complete function, and
the output your system produces.
 
--
Remove del for email
Rosario19 <Ros@invalid.invalid>: Sep 26 05:44PM +0200

On Sat, 26 Sep 2015 01:23:31 -0700, Barry Schwarz wrote:
>>?
 
>Not on my system. Maybe you should provide the complete function, and
>the output your system produces.
 
here i not find they write different output...
so all ok... ok too this output
even if for me "precision number" is number of the digit afther the
point "." in the right
and not the number of all digits as the C++ seems to say
 
#include <iostream.h>
 
int main(void)
{double b=23.123;
cout<<"1: "<<b<<"\n";
cout.precision(2);
cout.width(10);
cout<<b<<"\n";
cout.width(10);
cout.precision(2);
cout<<b<<"\n";
cout.precision(2);
cout<<b<<"\n";
return 0;
}
 
/*
the output:
1: 23.123
23
23
23
 
*/
red floyd <no.spam.here@its.invalid>: Sep 26 09:44AM -0700

On 9/26/2015 8:44 AM, Rosario19 wrote:
> point "." in the right
> and not the number of all digits as the C++ seems to say
 
> #include <iostream.h>
[redacted]
 
Since <iostream.h> is not a standard header, nobody here can tell
you what the expected behavior is.
 
Why are you still using <iostream.h> instead of <iostream>
17 years after standardization?
Barry Schwarz <schwarzb@dqel.com>: Sep 26 10:49AM -0700

On Sat, 26 Sep 2015 17:44:32 +0200, Rosario19 <Ros@invalid.invalid>
wrote:
 
>even if for me "precision number" is number of the digit afther the
>point "." in the right
>and not the number of all digits as the C++ seems to say
 
You can choose any meaning you like when you use "precision number" in
your prose. However, if you want people to understand your writing,
it would be nice if you chose the already accepted meaning of words.
In mathematics, precision is closely related to significant digits
which does not distinguish between digits before and after the decimal
point.
 
When you use the precision member function in your C++ code, your
chosen meaning is irrelevant. The result of calling the function is
defined by the standard, not by the whims of the programmer.
 
Since you second code sample has almost no relation to your first, are
we still discussing your incorrect assertion that the order of calling
the precision and width functions causes different output?
 
--
Remove del for email
Rosario19 <Ros@invalid.invalid>: Sep 26 08:48PM +0200

On Sat, 26 Sep 2015 10:49:59 -0700, Barry Schwarz wrote:
 
>Since you second code sample has almost no relation to your first, are
>we still discussing your incorrect assertion that the order of calling
>the precision and width functions causes different output?
 
no it is not in discussion, i remembered it wrong etc
 
what could be in discussion coul be: if i need to show the number + 2
digit afther the point... in C i have
printf("%.2f", (double)123.123); -> "123.12"
 
what in C++?
Rosario19 <Ros@invalid.invalid>: Sep 26 08:50PM +0200

On Sat, 26 Sep 2015 09:44:28 -0700, red floyd wrote:
>you what the expected behavior is.
 
>Why are you still using <iostream.h> instead of <iostream>
>17 years after standardization?
 
i like the past time
Jorgen Grahn <grahn+nntp@snipabacken.se>: Sep 26 06:15AM

On Fri, 2015-09-25, Paavo Helde wrote:
 
> The general idea is that a single class should have a single
> "responsibility". Managing the null-or-not-null data pointer seems a
> pretty clear responsibility.
 
Another common example of a class with not a lot of data in it is when
you find a need for a type, and discover that its internal state can
be represented as (for example) just an integer. Same internal state
as an int ... but a very different (and much smaller) set of operations.
 
One of the best habits I picked up over the years is to /resist/ the
temptation to "just use an int" or a typedef, and to write that tiny
class. My code becomes a lot clearer and safer.
 
/Jorgen
 
--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .
"Chris M. Thomasson" <nospam@nospam.nospam>: Sep 21 02:29PM -0700

Here is some example code using the default random number generator
(std::rand()).
 
I do not have time to explain it, but it can create small differences
between the average
minimum and maximum values of a frequency distribution:
 
http://codepad.org/ZZhBc65N
__________________________________________________________
#include <iostream>
#include <algorithm>
#include <vector>
#include <climits>
#include <cassert>
#include <cstdlib>
#include <cstring>
#define AN (UCHAR_MAX + 1U)
 
 
// crappy little rand...
unsigned int random_byte()
{
double rn = std::rand() / ((double)RAND_MAX);
return (unsigned int)((rn) * (AN - 1U));
}
 
 
// stores byte counts...
struct counts
{
unsigned int m_count[AN];
unsigned int m_total;
 
#define COUNTS_SINIT() { { 0 }, 0 }
 
void inc(unsigned int n)
{
assert(n < AN);
m_count[n] = m_count[n] + 1;
m_total = m_total + 1;
}
 
bool inc_if(unsigned int n, unsigned int nmax, unsigned int tmax)
{
assert(n < AN);
if (m_count[n] >= nmax || m_total >= tmax) return false;
inc(n);
return true;
}
 
void display() const
{
std::cout << m_total << " bytes...\r\n\r\n";
 
unsigned int total = 0;
double avg_total = 0.0;
double avg_min = 999999999999999.0;
double avg_max = 0.0;
 
for (unsigned int i = 0; i < AN; ++i)
{
if (m_count[i])
{
double bavg = m_count[i] / (double)m_total;
 
avg_min = std::min(avg_min, bavg);
avg_max = std::max(avg_max, bavg);
 
avg_total = avg_total + bavg;
total = total + m_count[i];
 
std::cout << "[" << i << "] = " << m_count[i] << ", " <<
bavg << "\r\n";
}
}
 
double avg_diff = avg_max - avg_min;
assert(avg_diff >= 0.0);
 
std::cout << "total = " << total << "\r\n";
std::cout << "avg_min = " << avg_min << "\r\n";
std::cout << "avg_max = " << avg_max << "\r\n";
std::cout << "avg_diff = " << avg_diff << "\r\n";
std::cout << "avg_total = " << avg_total << "\r\n";
}
};
 
 
// crude attempt to get a "flat" frequency distribution...
struct flat_freq
{
counts m_counts;
 
#define FLAT_FREQ_SINIT() { COUNTS_SINIT() }
 
 
void prv_process(unsigned int n, unsigned int nmax, unsigned int tmax)
{
for (unsigned int i = 0; i < n; ++i)
{
// Color Monitor
unsigned int rn = (random_byte() * ((i + 1) * 13)) % AN;
 
if (! m_counts.inc_if(rn, nmax, tmax))
{
//std::cout << "inc_if failed = \t" << rn << " \r";
}
}
}
 
unsigned int process(unsigned int n, unsigned int iter = 150)
{
unsigned int i = 0;
unsigned int ndiv = n / AN;
//unsigned int nmax = (ndiv) ? (ndiv + 1U) : (ndiv + 1U);
unsigned int nmax = (ndiv + 0U);
double nmax_real = 0.0;
 
//unsigned int nrem = ndiv * AN;
//unsigned int nmax = (nrem) ? (ndiv + 1U) : (nrem);
unsigned int iters_total = 0;
while (m_counts.m_total < n)
{
iters_total = iters_total + 1;
 
double tir = m_counts.m_total / (n - 0.0);
 
//nmax_real = nmax_real + 1.681; // large
nmax_real = nmax_real + 0.281; // small
 
for (i = 0; m_counts.m_total < n && i < 128; ++i)
{
 
unsigned int ptotal = m_counts.m_total;
prv_process(iter, (unsigned int)nmax_real, n);
if (ptotal == m_counts.m_total)
{
std::cout << "infinite loop detected at:" << ptotal <<
"! \r";
break;
}
}
}
 
std::cout << "\r\n\r\n";
 
std::cout << "iters_total = " << iters_total << "\r\n";
 
return i;
}
 
void display() const
{
m_counts.display();
}
};
 
 
 
 
int main()
{
{
std::srand(123);
 
flat_freq ffreq = FLAT_FREQ_SINIT();
 
unsigned int i = ffreq.process(10003);
 
std::cout << "i = " << i << "\r\n\r\n";
 
ffreq.display();
}
 
std::cout << "\r\n_________________\r\nComplete!\r\n\r\n";
std::cin.get();
 
return 0;
}
___________________________________________________________
 
 
 
 
I will explain this further very soon. It has to do with encryption.
Rosario19 <Ros@invalid.invalid>: Sep 22 12:19AM +0200

On Mon, 21 Sep 2015 19:18:11 +0200, Rosario19 wrote:
 
i think that the win move is
put all possible code not dipend <T> type of the template in the dll
library file
and put all other in the .h file
 
the problem i had possible is one expansion of a macro as
#define ooo cout
....
#define cout thatandthis[0]
etc
Ian Collins <ian-news@hotmail.com>: Sep 22 10:42AM +1200

Rosario19 wrote:
> .....
> #define cout thatandthis[0]
> etc
 
That's an easy fix: don't use pointless macros...
 
--
Ian Collins
Rosario19 <Ros@invalid.invalid>: Sep 21 11:43AM +0200

On Sun, 20 Sep 2015 02:43:15 -0500, Paavo Helde wrote:
 
 
>See also https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
 
>hth
>Paavo
 
thank you
 
but it is possible put only dichiarations [member, functions,
operators etc] of the template class in the header file, and put all
the code of that member functions, operators etc of the template class
in the .dll file [in a way it is possible use that template class from
some other .cpp file]?
Rosario19 <Ros@invalid.invalid>: Sep 21 12:11PM +0200

On Mon, 21 Sep 2015 11:43:18 +0200, Rosario19 wrote:
 
>the code of that member functions, operators etc of the template class
>in the .dll file [in a way it is possible use that template class from
>some other .cpp file]?
 
it seems to me
that this compile for the creation of the .dll
 
but when i want to use the compiler on other .cpp file that call one
instance of that template class...
the compiler says "unrisolved external" even if i put __extern in the
code of that template in the .dll
 
so i would use only the .h file for template....
 
but doing so there could be problem in call functions expecially
input/ output
where their definitions, in the few i understand, are in one other
file header afther, in include, the header where there is the template
class
jt@toerring.de (Jens Thoms Toerring): Sep 21 06:05PM


> >Louis
 
> i think is not possible put code of the class template in the ndll.cpp
> file right?
 
Yes. The compiler must be able to see the templated code for
function to be able to create the "real" code, i.e. with the
occurences of the template parameters replaces by the concrete
type! So if you declare something templated in a header file
to be used from a number of cpp file also the definitions must
be in the header file.
 
Here's a trivial example:
 
foo.h:
=============
 
#include <iostream>
template< typename T >
T foo( T const arg1, T const & arg2 );
=============
 
file1.cpp
=============
#inclue "foo.h"
 
extern void bar( );
 
template< typename T >
T foo( T const & arg1, T const & arg2 ) { return arg1 + arg2; }
 
int main( )
{
std::cout foo( 1.2, -3.9 ) << std::endl;
bar( );
}
=============
 
file2.cpp
=============
#include <string>
#inclue "foo.h"
void bar( )
{
std::cout << foo( std::string( "hello " ), std::string( "world" )
<< std::endl;
}
=============
 
If the compiler sees file1.cpp it can geneterate a foo() function
that accepts two doubles, but there's no reason for it to also
create one that accepts two std::strings (or whatever types that
templated function may ever be used with - there's no way it
could know that!). And when file2.cpp is compiled the compiler
doesn't know how to create the required foo() function that
accepts two std::strings since that's only defined in file1.cpp.
 
So, unless the templated stuff is restricted to a single source
(cpp) file, the definitions also must be in the header file to
tell the compiler how to generate the required code with con-
crete types.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
mark <mark@invalid.invalid>: Sep 21 08:24PM +0200

On 2015-09-21 11:43, Rosario19 wrote:
> the code of that member functions, operators etc of the template class
> in the .dll file [in a way it is possible use that template class from
> some other .cpp file]?
 
This is only possible in a limited way. You need to use explicit
instantiation:
 
<http://en.cppreference.com/w/cpp/language/class_template#Explicit_instantiation>
 
So you need to know which types your template(s) will be used with and
perform explicit instantiations for those. Only the file where you do
those instantiations needs access to the template definitions.
mark <mark@invalid.invalid>: Sep 20 07:37PM +0200

On 2015-09-20 15:15, Sui Huang wrote:
> #3. vector<HasPtr> items = {HasPtr("abc"), HasPtr("def")}; //first call default constructor, then copy constructor
> [...]
> #3. When copy objects to vector, why not call move constructor?
 
Initializer lists don't support move, the elements can only be accessed
as const and thus must be copied.
 
There is a proposal to support move, so this may be possible in C++17.
jt@toerring.de (Jens Thoms Toerring): Sep 19 10:49PM

> to failed attempts to read the file? I think I spot some errors. Clearly
> read4096 should be Read4096. Also I think read4096(readbuf) should be
> Read4096(buf).
 
No, definitely not. There's a large chance that 'buf' has not
enough space left to accept another 4096 bytes at this stage
but just 'remain' bytes. To avoid that you need a buffer that
can accept the full 096 bytes.
 
> I would also make num_copy simply remain instead of
> min(num_read, remain).
 
No, because you just want to append to 'buf' as much as was
requested, not everything that may have been read (which
might be more than still fits into 'buf').
 
Both your proposed changes could result in writing past the
end of 'buf' which must be avoided at all costs! That's the
raw material for buffer-overflow attacks, i.e. it not only
makes your program behave in unpredictable ways but may even
allow the "bad guys" to wreak havoc by carefully crafted files
they may get you (or some user of your progam) to read in.
 
> buf += num_read;
> total += num_read;
> }
 
This tries to read as many 4096-byte chunks as can be
read from the file (modulo some typing errors like
'read4096' versus 'Read4096').
 
> if ( total != n - remain )
> return total;
 
Here things start to get a bit strange. If 'n' is an integer
multiple of 4096 (thus 'remain' is 0 ) and everything went
well one probably should also stop here and not attempt
to read anymore from the file. The code only seems to catch
cases of read errors (or less in the file than requested).
But that could be fixed easily by using '<=' instead of '!='
in the if condition.
 
The case that 'n' is smaller than 4096 though is handled
correctly - in that case the loop never gets run, thus
'total' is still 0 and so is 'n-remain' - thus the fol-
lowing code will get executed.
 
> int num_copy = min( num_read, remain );
> copy( readbuf, readbuf + num_copy, buf );
> total += num_copy;
 
I don't see anything broken here (assuming that somewhere
before there was a line with 'using std;').
 
> return total;
> }
 
What's missing from the specifications is if it should
be possible to call this function several times. The
way it's written it can only be called once - or data
from the file may get lost. If it's to be called again
and again (e.g. with small values of 'n' for a large
file) the stuff read into 'readbuf' would have to be
stored (e.g. by making 'readbuf' a static variable) and
it would also have to be recorded in another static va-
riable how much from the last read in the last call has
not yet been returned to caller, and dealing with that on
entry into the function.
 
Since Read4096() is obviously meant to be called several
times to read in a file in chunks of that size I would
tend to assume that the same is also intended with this
function. But that won't work when bytes read from the
file but not yet returned to the caller are simply dis-
carded. So the function, as it is, satisfies the requi-
rements by the letter, but probably isn't what was ex-
pected.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Kalle Olavi Niemitalo <kon@iki.fi>: Sep 20 12:04PM +0300

> char readbuf[ 4096 ];
> int num_read = Read4096( readbuf );
> However, it seems (to me) to read from an array of uninitialized chars.
 
That code does not read from the array.
The expression Read4096(readbuf) means the same thing as
Read4096(&readbuf[0]); the array "decays" to a pointer that
points to the first element of the array.
Only that pointer is passed to the function Read4096,
which then uses it to write to the array.
The same thing would happen in fread(readbuf, 1, 4096, file).
 
> Why not the code below?
 
Consider what happens if someone calls it like this, and the file
actually is 50 bytes long;
 
char smallbuf[10];
int got = read(smallbuf, 10);
 
The intended effect is that the first 10 bytes of the file
should be read to smallbuf.
 
> int read(char* buf, int n){
> int num_it = n / 4096;
> int total = 0;
 
This would set num_it = 0 and total = 0.
 
> for(int i = num_it; num_it >= 0; --num_it){
 
This would set i = 0 and enter the loop body.
 
> int num_read = read4096(buf);
 
This would try to read 4096 bytes to buf, which points to
smallbuf. Because the file is 50 bytes long, read4096 would read
only 50 bytes to smallbuf. But smallbuf only has room for 10
bytes, so read4096 would write past the end of smallbuf
and likely corrupt some other object.
jt@toerring.de (Jens Thoms Toerring): Sep 20 10:13AM


> However, it seems (to me) to read from an array of uninitialized chars.
> That's why I wanted to read from buf rather than from the uninitialized
> array.
 
As Kalle has already pointed out, this doesn't read from
'readbuf' - the Read4096() function reads from a file (up
to 4096 bytes) and puts them into the buffer you call it
with. So it will write what it read into 'readbuf'.
 
> }
> return total;
> }
 
The problem is the buffer the caller passes to the function.
The user isn't supposed to know how the function works in-
ternally. So it's reasonable for him to assume that the
buffer he or she passes to the function doesn't have to be
larger than the number of bytes he requests. And for that
reason alone the function may never try to write more than
as many bytes as the user requested into the buffer supplied
by him (or her).
 
Consider an attempt by the user to read the file character
by character, similar to fgetc(). So he might do
 
char c;
while ( read( &c, 1 ) == 1 )
do_something_with_the_character( c )
 
The user expects to get exactly one character (or nothing
when the end of the file has been reached). But your ver-
sion of the function would try to stuff up to 4096 bytes
into the location of 'c' where there's room for just a single
character (thus writing over the memory following it, pos-
sibly destroying other important data, smashing the stack
etc.) and would return a number between 0 and 4096, depen-
ding on how much was still available in the file. But the
user had no reason to expect that the function would return
anything but 1 or 0.
 
This type of use case is also why I would consider the
function you originally posted to be deficient. While it
at least doesn't write past the end of the user supplied
buffer and never has a return value larger than the num-
ber of characters the user requested, it discards all
the characters it read in from the file but could not
return to the user. If used in the way shown above, i.
e. in an attempt to read in the file character by cha-
racter, it would return just every 4096th character
from the file, which probably isn't what any user of it
would expect.
 
To use it properly the user would have to be aware that,
to get everything from the file, it must be called with a
buffer with a length that's an integer multiple of 4096.
And then it probably would be simpler to use Read4096()
directly;-)
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Christian Gollwitzer <auriocus@gmx.de>: Sep 20 02:08PM +0200

Am 19.09.15 um 22:56 schrieb Paul:
 
> Todo: Use above API to Implement API
> "int Read(char* buf, int n)" which reads any number of chars from the file.
 
> Below is a solution offered by someone posting at that site. I have questions about this as follows.
 
Others have already pointed out where this solution is insufficient. I'd
like to add:
 
this solution tries to optimize away copying by calling read4096
directly into the output bufer, if possible.
For sure this can be done, and it'll be a little more efficient than
copying - but it would be far easier to get it correct with a "static
char readbuf[4096]" and a "static size_t readbufindex" that points to
the first byte not-yet retrieved and a "static char buflength", pointing
to the end of the data in readbuf. You then always only fill the buffer
if the request cannot be fulfilled from the remaining content.
Sure, this will waste a few bytes and make it a bit slower due to
copying - but first you should try to implement a correct version,
profile, and then maybe optimize. If the read4096 takes lots of time to
get the data from the external device, copying might be negligible.
 
Christian
ram@zedat.fu-berlin.de (Stefan Ram): Sep 21 10:29PM

>Here is some example code using the default random number generator
>(std::rand()).
 
This was the default in C. For tutorials, never for
applications where random numbers matter!
 
In 2015, in C++, we have several pseudo-random number
generation engines and adaptors (see at the end).
 
The standard defines /the interfaces/
 
int rand(void);
 
. When you create
 
>small differences between the average minimum and maximum values
 
, you are using /an implementation/ of the interface
 
int rand(void);
 
. Use another implementation of the same interface
 
int rand(void);
 
and get another result!
 
The strength and weaknesses of the widespread implementation with
 
next = next * 1103515245 + 12345;
 
are already well-documented. Check this out:
 
#include <iostream>
#include <ostream>
#include <random>
 
struct rng0
{ ::std::random_device rd;
::std::mt19937 rng;
::std::uniform_int_distribution< int >uni;
rng0(): rd(), rng( rd() ), uni( 0, 11 ) {}
int rnd(){ return uni( rng ); }};
 
int main ()
{ rng0 rng0;
for( int i = 0; i < 9; ++i )
::std::cout << rng0.rnd() << '\n'; }
 
. I don't say that this is »better« than »::std::rand()«,
but a C++ programmer should know about the new classes for
random-number generation, and - when it matters - about
the most important third-party libraries.
ram@zedat.fu-berlin.de (Stefan Ram): Sep 21 10:31PM

>/* here some values might be put into the map */
>for( const ::std::pair< ::std::string, int > & pair : map )
>/* assume a statement here that might use the pair */
 
Yes, the correct answers were given in this thread,
and it's correct that I got both ideas from the same book.
You received this digest because you're subscribed to updates for this group. You can change your settings on the group membership page.
To unsubscribe from this group and stop receiving emails from it send an email to comp.lang.c+++unsubscribe@googlegroups.com.

No comments: