vijayan121 1,152 Posting Virtuoso

isnan() is from C99; and is not part of C++98. See http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.15
In C++0x, isnan() is part of TR1.

You could easily roll out isnan() and isinf() on your own, though:

#include <limits>

template< typename T > inline bool isnan( T value )
{ return value != value ; }

template< typename T > inline bool isinf( T value )
{
    return std::numeric_limits<T>::has_infinity &&
           value == std::numeric_limits<T>::infinity() ;
}
vijayan121 1,152 Posting Virtuoso

> I asserted the flag -static-libgcc on compilation of my hello.cpp file (hello world program).
> Apparently this is not enough though. Because there is still a segment in my executable which contains the name/path of the dynamic loader.
> What flags do I use to generate an executable which contains EVERYTHING needed to be run?

The flag to use is -static to link everything statically or -static-libgcc to just link to libgcc statically.

For example, with this hello.c

#include <stdio.h>

int main()
{
    puts( "hello world" ) ;
    return 0 ;
}

This would link to the shared libraries:
gcc -Wall -std=c89 -pedantic -Werror hello.c -o hello && ldd hello
libc.so.7 => /lib/libc.so.7 (0x2808e000)

And this should create a standalone executable:
>gcc -Wall -std=c89 -pedantic -Werror -static hello.c -o hello && ldd hello
ldd: hello: not a dynamic ELF executable

Executable files need some code that initially sets up the process environment for an executable, initializes the C and C++ libraries, in C++, perform dynamic initialization of statics (eg. invoke constructors of global objects); all that needs to be done before entering main(). Then this code calls main, and when main returns does the deinitialization and returns to the kernel via the exit syscall. The actual code is obviously highly platform specific.

In elf executables generated by the gnu toolchain, to set the entry point of the executable, the linker looks for a symbol named _start. This symbol is …

Agni commented: Always learn something from your posts :) +3
vijayan121 1,152 Posting Virtuoso

> as far as i understand the if statment should stop evaluating if the first condition is false
> [as it is an && operation] (ie no player occupies the seat, therefore the pointer is invalid)
> so it should not try to evaluate the player->inRound bit

Your understanding is correct.So it will it be completely safe if isOccupied is set and cleared correctly.

> secondly if this is bad code can you suggest a safer way to do such a thing?

It is not bad code unless it sets isOccupied incorrectly. The only extra safety that can be provided is
a. Make sure that seat[x].player is set to zero whenever the seat is not occupied
b. Provide an extra check to verify that seat[x].player is not a null pointer before you try to access seat[x].player->inRound

vijayan121 1,152 Posting Virtuoso

Use std::getline to read line by line.
Use a std::istringstream to extract the words in the line.

while( std::getline( file, line ) ) // read line by line
{
    if( line == "" ) // just a '\n' in file
    {
        // an empty line, new paragrah logic
    }
    else // split the line into words
    {
        std::istringstream stm(line) ;
        std::string word ;
        int chars_in_line = 0 ;
        enum { MAX_LINE_LENGTH = 80 } ;
        while( stm >> word ) // read word by word
        {
            if( ( chars_in_line + word.size() ) < MAX_LINE_LENGTH )
            {
                // print the word, and then a space
                // add word.size() + 1 to chars_in_line
            }
            else if( ( chars_in_line + word.size() ) == MAX_LINE_LENGTH )
            {
                // the word just fits on the line
                // print the word, and then a newline
                // reset chars_in_line to zero
            }
            else
            {
                // the word doesn't fit on the current line
                // print a newline, then the word, then a space
                // reset chars_in_line to word.size() + 1
            }
        }
    }
}
vijayan121 1,152 Posting Virtuoso

> Why does C++ seem more complicated than Visual Basic?

Because it *is* more complicated than Visual Basic.

But you don't need to be extraordinarily brilliant to learn C++ and to use C++ effectively. Almost all programmers who make a genuine attempt to become good C++ programmers do succeed in their attempts. In a reasonable period of time, which is more than what is required for, say, Visual Basic. The world is complex, some problems are hard, and the tools we use to solve those difficult problems are necessarily more complex.

vijayan121 1,152 Posting Virtuoso

> My operator+= works
> However i cant get the operator+ to work

The problem seems to be in your copy constructor; operator+ needs to make a copy.

First, verify that the copy constructor Str2::Str2( const Str2& ) is working correctly.

vijayan121 1,152 Posting Virtuoso

> how to read input from strings using cin

1. Create a std::stringbuf which gets its input from a std::string.
2.Set this as the std::streambuf used by std::cin

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    std::string input_string = "string containing input 123 45 a 72.45 etc." ;
    std::stringbuf streambuf( input_string, std::ios_base::in ) ;
    std::cin.rdbuf( &streambuf ) ;

    // now use std::cin to read the contents of input_string
}
wisaacs commented: excellent concise iostream example +1
mrnutty commented: Nice, I learned something new. +5
vijayan121 1,152 Posting Virtuoso

Define the static member variables that have been declared.

namespace fun{
        // ...
        class driver{
                // ...
            	static int size;
            	static int eff;
            	static int idnumber;
                static std::vector<int> bmv;
                static std::vector<int> amv;
                static std::vector<int> bbv;
                static std::vector<int> abv;
                // ...
        };
        // ...
}
// ...

int fun::driver::size = 22 ;
int fun::driver::eff = 'F' ;
int fun::driver::idnumber = 77 ;
std::vector<int> fun::driver::bmv ;
std::vector<int> fun::driver::amv( 10U ) ;
std::vector<int> fun::driver::bbv ;
std::vector<int> fun::driver::abv ;

// ...
vijayan121 1,152 Posting Virtuoso

> But how do I go thru A folder and get all the files size's that are inside?

See: http://www.daniweb.com/forums/post342872.html#post342872

That just prints the native_file_string. To get the file size, construct a boost::filesystem::path from iter->native_file_string() and then use boost::filesystem::file_size on it, as in your current code.

vijayan121 1,152 Posting Virtuoso

> After spending more than a year learning C++ , I now realise that
> I still don't know it enough to program safely with that language.

That is almost certainly incorrect. To be able to program well (safely, elegantly, efficiently) in a language does not imply that you have to know 'everything' about the language.

To quote Stroustrup:

What design and programming techniques do we want to emphasize? What subsets of the language do we want to learn first? What subsets of the language do we want to emphasize in real code?

...

Even for the professional programmer, it is impossible to first learn a whole programming language and then try to use it. A programming language is learned in part by trying out its facilities for small examples. Consequently, we always learn a language by mastering a series of subsets. The real question is not ‘‘Should I learn a subset first?’’ but ‘‘Which subset should I learn first?’’

...

The emphasis for both novices and experienced programmers should be concepts and techniques. The syntactic and semantic details of C++ are secondary to an understanding of design and programming techniques that C++ supports.

- from http://www.research.att.com/~bs/new_learning.pdf

> Even more depressing is that EVEN a company like Microsoft with
> billions of dollars of spending in research, easy access to any
> computer scientist in the world, can't figure correctly how C++ works.

Not really. The Microsoft C++ team has known …

vijayan121 1,152 Posting Virtuoso

> Problem! That code WON'T compile in microsoft visual C++ 2008
> issuing specifically the C2327 compiler error:
> "'symbol' : is not a type name, static, or enumerator
> Code within a nested class attempts to access a member of the
> enclosing class that is not a type name, a static member, or an enumerator

Clearly, that is a spurious error message. In that code, there is no nested class is at all, and therefore there is no enclosing class either.

The IS clearly states that:

After the point of declaration of a class member, the member name can be looked up in the scope of its class. [Note: this is true even if the class is an incomplete class.]

It also gives an example (elided for clarity):

class Y;
char Y::* pmc;

declares pmc to be a pointer to a member of Y of type char. The declaration of pmc is well-formed even though Y is an incomplete type.

The code compiles cleanly under various versions of the GNU compiler, the Comeau compiler and other compilers with an EDG front end. AFAIK, the Microsoft C++ compiler which does not compile it is non-conforming for this case.

vijayan121 1,152 Posting Virtuoso

1) The iterator
a) why do you have a last_element member? Why don't you just return NULL for the before first element or after last element? I suspect you might have done that because of reverse iterations but even then I don't see why the much simpler NULL wouldn't work just as well.

The iterator corresponding to end is one which 'point to' a fictitious one past the last element of the sequence. This iterator must be well defined; --end should move the iterator to the last element of the sequence

b) why didn't you just put the insert_into_list and remove_into_list function INSIDE the iterator?

Insert and erase are logically operations on sequences; not operations on an iterator which just identifies one element of a sequence. Of course it is possible to create a pseudo sequence container and put insert and erase and other container operations into it.

2) I would have like you to have your opinion on a possible future revision of C++ to permit the pointer_to_member inside its own class

A pointer to member inside its own class is already allowed. eg.

template< typename T, int T::*PM > struct A {} ;
struct B
{
    int i ;
    A< B, &B::i > a ;
};

3) You seem to confirm that the last suggestion I proposed is the best approach, and you also mentionned "polymorphic call wrappers": I would be delighted to hear more about what that is! Do you mean to replace …

vijayan121 1,152 Posting Virtuoso

> wish list:
> -no additional memory cost for each item
> -keeps double-link list structures (no vectors, etc...)
> -no supplementary indirection cost allowed
> -no more "typing" when using it
> -a solution that is simple, logical and semantically elegant

I have a very large group of items which are linked to each other by different double link lists and trees using members inside each item.

what we really want to have is a sort of "super-iterator" to iterate through the items in different ways

Yes, what we want are ways to access these items as different sequences. A set of polymorphic iterators which can iterate through the same items as different sequences.

there is an additional (invisible) indirection created by the virtual dispatch when you move using the super_iterator.

So we will make them polymorphic at compile-time using the earlier pointer to member idea. The example below is just for the doubly linked list like sequences.

#include <iostream>
#include <iterator>
#include <algorithm>

// iterator over a sequence using pointers to members 
// for next element and prev element
template< typename T, T* T::*NEXT, T* T::*PREV >
struct list_iterator : std::iterator<std::bidirectional_iterator_tag,T*>
{

    list_iterator( T* curr, T* last ) : current(curr), last_element(last) {}

    T*& operator* () { return current ; }

    list_iterator& operator++ ()
    { current = current->*NEXT ; return *this ; }

    list_iterator& operator-- ()
    { current = current ? current->*PREV : last_element ;  return *this ; }

    list_iterator operator++ …
vijayan121 1,152 Posting Virtuoso

Question posed by josolanes:

I looked at your thread here: http://www.daniweb.com/forums/thread88255.html from a couple years back

And I'm starting to get a grasp of your first post. I understood how to do the factorial struct really quickly, but the _if and _for statements still make me feel uneasy, though I think I understand them. I think a bit more experience with it will help a lot with my confidence

One that I'd like help withis the following example of isPrime:

bool isPrime(int p, int i=2) 
{
    if (i==p)
        return 1; 
    if (p%i == 0)
        return 0;
    return isPrime (p, i+1);
}

I'd like to achieve this in a similar manner as the fibonacci one, with a single set of funcitons and templates (for each "case") if possible.

I've been thinking about it a bit, but my lack of experience with TMP seems to have me somewhat dumbfounded. I assume it's possible to do this in a single struct set, but can't quite figure it out since it has 2 variables, one as an input and the other changing.

I looked online for an isPrime TMP example and found one that uses a combination of about 3 struct sets to perform the above operation http://zwabel.wordpress.com/2008/12/18/c-template-support-in-kdevelop4-another-milestone/

I tried to modify it to work within a single struct set using conditional shorthand but can't quite figure it out

Is there a way to do the above in a single struct set? If so, how would you?

THe is_prime itself …

vijayan121 1,152 Posting Virtuoso

[I want two different instances of the list (one with member_one and the other with member_two) and a single instance of the function. I want it done inside the list class itself (using nested class if necessary) and I want the pointer_to_member to be used as the template argument to create the two different template instances of the class) so that you could instantiate the list class twice like this:

If that is all you want, you do not need the pointer_to_member as a template parameter at all - just pass it to the constructor of the list. Then you could have either a member function or a free function do what you want.

#include <iostream>

template < typename T > struct list
{
    explicit list( T* list::*pm, T* a = 0, T* b = 0 )
        : member_a(a), member_b(b), pointer_to_member(pm) {}

    T* get() { return this->*pointer_to_member ; }

    T* member_a ;
    T* member_b ;
    T* list::*pointer_to_member ;
    // ...
};

template < typename T > T* get_it( list<T>& lst )
{ return lst.*lst.pointer_to_member ; }

int main()
{
    int a = 11111, b = 22222 ;

    list<int> lst1( &list<int>::member_a, &a, &b ) ;
    list<int> lst2( &list<int>::member_b, &a, &b ) ;

    std::cout << *lst1.get() << '\t' << *get_it(lst1) << '\n'
              << *lst2.get() << '\t' << *get_it(lst2) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

Couple of general points: In general use references (instead of pointers) for strings, streams and the like. Use const where ever and whenever possible - it is your friend. Prefer using '\n' to std::endl to send a new line to a stream, unless your intent is to also flush the stream (performance).

Now, re. the code to read and write strings using binary i/o:

To get the number of characters in a string use the size() method. As you are dealing with binary stuff, c_str() is a null terminated string; it will mess you up if the string itself contains null characters.

Use the result of c_str() only immediately after calling it; it cannot be safely used once the string is modified.

The modified code would be something like:

// Writes a string outStr to BIN file ofs
void stringToBINFile( const string& outStr, ostream& os )
{
    int n_chars = outStr.size() ; //Length has to be known when reading
    os.write((char *)&n_chars, sizeof(n_chars));
    if( n_chars > 0 ) os.write( (const char *)&*outStr.begin(), n_chars );
}

// Reads a string inStr from a BIN file ifs
void stringFromBINFile( string& inStr, istream& is )
{
    int n_chars;
    is.read((char *)&n_chars, sizeof(n_chars));
    if( n_chars > 0 )
    {
        inStr = string( n_chars, ' ' ) ;
        is.read( (char *)&*inStr.begin(), n_chars ) ;
    }
    else inStr = "" ;
}

void myWrite( const char* path, const string& outStr)
{
    ofstream ofs (path, ios::binary);
    stringToBINFile(outStr, ofs);
}

void myRead( const char* path, …
vijayan121 1,152 Posting Virtuoso

> What is this thingy that I'm trying to name or whatever?
Well, it is part of the IS, under section 7.1.5.1 'The cv-qualifiers'

A variable of const-qualified integral or enumeration type initialized by an integral constant expression can be used in integral constant expressions - IS 7.1.5.1/2

A pointer or reference to a cv-qualified type need not actually point or refer to a cv-qualified object, but it is treated as if it does; a const-qualified access path cannot be used to modify an object even if the object referenced is a non-const object and can be modified through some other access path. [Note: cv-qualifiers are supported by the type system so that they cannot be subverted without casting] - IS 7.1.5.1/3

Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior. - 7.1.5.1/4

Compilers do implement the optimization allowed by this; for example:

int foobar()
{
    const int c1 = 100 ;
    const int c2 = 25 ;
    const int* p1 = &c1 ;
    const int* p2 = &c2 ;

    return *p1 - *p2 ; // generates code for return 75 ;
}

> g++ -Wall -std=c++98 -O3 -fomit-frame-pointer -S -c foobar.cc
> cat foobar.s

.file "foobar.cc"
.text
.p2align 4,,15
.globl __Z6foobarv
.def __Z6foobarv; .scl 2; .type 32; .endef
__Z6foobarv:
LFB2:
movl …

Dave Sinkula commented: Danke. +13
vijayan121 1,152 Posting Virtuoso

Rewrite void Matrix::Multiply(Matrix b) ; as Matrix Matrix::Multiply( const Matrix& b ) const ; In the implementation, do not modify either of the two Matrix objects involved in the multiply. Construct a new result Matrix object of the appropriate size, populate it and return it.

Ok, I see that Dragon has preempted me.

mrnutty commented: Was thinking the same thing +4
vijayan121 1,152 Posting Virtuoso

> it constructs one object, makes n copies of it,
> then for some reason destroys the original object

That is the way it is expected to work. The relevant constructor is

explicit vector( size_type n, const T& value = T(), 
                 const Allocator& = Allocator() ) ;

For the second argument, a temporary T is default constructed, the n elements in the vector are then copy constructed from this temporary, and the temporary is then destroyed. A clever compiler may save a small bit of time by applying the optimization as allowed in IS 12.8/15.

> when you resize it, it copies the existing objects, destroys the
> original and uses the same procedure to create new objects.

The reason is identical. If you look at the declaration of resize, you can see where the temporary object comes from.

void resize( size_type sz, T c = T() ) ;

> I'm actually scared of vectors now - I think it's probably safer go
> back to using arrays, or maybe write my own vector class.

There is no reason to be scared of vectors. I'm scared of arrays unless I know the size of the array at compile time. Just make sure that the type of the element in a sequence container is copy constructable and assignable.

The problem is with your wrapper class, not with the vector. If you refuse to face it by avoiding use of a vector …

jonsca commented: Nice +2
vijayan121 1,152 Posting Virtuoso

Yes, both Java and C++ support handling of errors by using exceptions, both have keywords throw, try and catch which behave similarly. But this similarity is deceptive, the philosophy behind the exception mechanism is fundamentally different in the two languages.

The Java mechanism requires you to deal with potential errors at the specific places that they might occur. You accomplish this with try...finally blocks; if you open a file, you wrap that and the code that follows in a try...finally construct and close the file in the finally block. Not too bad, but you have to recognize when you need to do it and consciously put it in place. Not fundamentally different from the C technique of checking a return value or a global errno and clean up in the face of errors at or near the point where the error occurred.

It is telling that C++ has no finally. It has something far slicker — RAII (Resource Acquisition Is Initialization). Essentially you use objects that encapsulate resources which have destructors that do the clean up for you if things go wrong. One example of this is the iostream library. fstreambuff destructors release the memory for the file buffer, and fstream destructors close the file. Say, you create a file stream, and open a file for output, and an exception is thrown, the file is automatically closed during the stack unwind. Without the programmer having to do anything special or write any extra code.

void some_function( object …
vijayan121 1,152 Posting Virtuoso

> like i said, the algorithm has to have O(n log n) time complexity

Well, the Boyer and Moore's Voting Algorithm has a lower O(n) time complexity, clearly O(n) is better than O(n log n), isn't it?

Your algorithm has the right idea, it is a classic divide-and-conquer algorithm:

function majority( array A with number_of_elements N )
  if N == 1 : return A[0]
  let AL, AR be the first and second halves of A
  let ML = majority(AL)
  let MR = majority(AR)
  if neither half has a majority: return ‘‘no majority’’
  else:
       check whether either ML or MR is a majority element of A
       if so: return that element
       else: return ‘‘no majority’’

The idea is:
If A has a majority element X, then X appears more than N/2 times in A
Thus X appears more than N/4 times in either AL or AR.
So X must also be a majority element of either one or both of these two arrays.
Running time T(N) = 2 * T(N/2) + O(N) = O(N log N).

Your implementation has a few problems, here are a few hints:

int majorL = majority(A, inL, inD/2-1) ;
    int majorD = majority(A, inD/2+1, inD) ;

This partioning misses out the middle element inD/2, if inD is even

Consider inL == 5, inD == 9
majority(A, inL, inD/2-1) => majority(A, 5, 3) => inD < inL

Consider inL == 0, inD == 3

kal_crazy commented: nice explanation +2
vijayan121 1,152 Posting Virtuoso

> i read somewhere that sockets are full duplex, so initially i tried to build an architecture like this:
a socket is *one* end of a two-way communications link.
a BSD socket maintains a separate send buffer and a receive buffer, and is full-duplex (you can both send and receive data on it).
to send or receive data, you need two sockets (one at either end).
in your first example, you are trying to use the *same* socket at both ends.

create *two* sockets, one for the client and another for the server.
(eg. socketpair does this for UNIX sockets. http://www.freebsd.org/cgi/man.cgi?query=socketpair)
after forking, close the client socket in the server, and the server socket in the client.
and things should be ok.

+---------------+		+---------------+
|		|		|		|
|  peer1	|		|	peer2	|
|		|port1	   port2|		|
|      sock1----|---------------|----sock2	|
|		|		|		|
|		|		|		|
+---------------+		+---------------+

> Could this diversion be "easily" done, by using ncurses
yes.

vijayan121 1,152 Posting Virtuoso
Salem commented: Nice google - shame the OP couldn't have done that +29
vijayan121 1,152 Posting Virtuoso

> declare it as private and just leave an empty implementation?
ideally, declare it as private and do not define it.

> Is this common/useful?
useful, yes. common, not all that much.
if there is a class that you write (for example a window), and want its instances not to have value semantics, you need to suppress any compiler-generated copy constructor and assignment operators.

struct window
{
    // ...
    private:
       window( const window& ) ; // do not define this
       void operator= ( const window& ) ; // do not define this
    // ...
}

see: http://www.boost.org/doc/libs/1_37_0/libs/utility/utility.htm#Class_noncopyable

skatamatic commented: To the point and accurate +3
vijayan121 1,152 Posting Virtuoso

> It keeps saying:
> Failed to connect with the server : Bad file descriptor

that says all that needs to be said, doesn't it?

int websock; // websock is an uninitialized int

webaddress.sin_family = AF_INET;
webaddress.sin_addr.s_addr = inet_addr("http://www.google.com/index.html");
webaddress.sin_port = htons(80);
if(connect(websock, ... // websock is not a file descriptor
              // it still is merely an uninitialized int

why don't you use a library? libcurl http://curl.haxx.se/libcurl/ is the one of choice.
and it's easy to use. eg. to fetch a page and save it to a file (without any error handling),

#include <curl/curl.h>
#include <cstdio>

// link with libcurl. eg.
// g++ -Wall -std=c++98 -pedantic -Werror -lcurl -I /usr/local/include    -L /usr/local/lib

void get_page( const char* url, const char* file_name )
{
  CURL* easyhandle = curl_easy_init() ;

  curl_easy_setopt( easyhandle, CURLOPT_URL, url ) ;

  std::FILE* file = std::fopen( file_name, "w" ) ;
  curl_easy_setopt( easyhandle, CURLOPT_WRITEDATA, file ) ;

  curl_easy_perform( easyhandle );

  curl_easy_cleanup( easyhandle );
}

int main()
{
  get_page( "www.research.att.com/~bs/",
            "/tmp/stroustrup_home_page.html" ) ;
}
Salem commented: So obvious really, if they stopped to think about it for a while. +29
vijayan121 1,152 Posting Virtuoso

this is nothing specific to constructors or passing parameters to functions.
it is just the application of the C++ rules for resolving a call to an overloaded function.

#include <iostream>

void foobar( int& arg )
{ std::cout << "foobar( int& )\n" ; }

void foobar( const int& arg )
{ std::cout << "foobar( const int& )\n" ; }

int main()
{
  int i = 7 ;

  foobar(i) ; // foobar( int& arg ) : exact match
  // foobar( const int& ) : conversion from int& to const int&
  // exact match preferred over conversion

  const int j = 7 ;
  foobar(j) ; // foobar( const int& arg ) : exact match
  // foobar( int& arg ) can't be called at all ( no conversion )

}

in your snippet:

int main ()
{
  MyClass f(4);
  Func (f); // make copy of object f. f is a modifiable lvalue
  // overload resolves to exact match : MyClass::MyClass( MyClass& )
  
  const MyClass& g = f ;
  Func (g); // make copy of object g. g is not a modifiable lvalue
  // call MyClass::MyClass( const MyClass& ) to make the copy
}

the copy constructor that takes a non-const object as argument is used to make copies of non-const objects.
and the copy constructor that takes a const object as argument is used to make copies of const objects.

vijayan121 1,152 Posting Virtuoso

only because the language the OP is using ( MessageBox::Show ) is C++/CLI (not ISO C++).
and purely managed will not give anywhere near native performance.

Alex Edwards commented: Good to know. Thanks =) +4
vijayan121 1,152 Posting Virtuoso

for the predefined streams, it's safe to mix C stdio and C++ iostreams. you can safely use stdin and std::cin in the same program; the C++ Standard guarantees that it will work the way you would expect it to.

if you don't need to mix C stdio and C++ iostreams on the same stream, you can get better performance by turning this feature off std::ios_base::sync_with_stdio(false); however, if you need to open a file with C++ iostreams, and at the same time access that file as a C FILE*, there's nothing in the C++ standard to support that usage by default. however, the library is extensible, and a std::streambuf derived class that supports this is just a couple of dozen lines of code.

Salem commented: Nice answer. +21
vijayan121 1,152 Posting Virtuoso
Derived d;
Base *p = reinterpret_cast< Base*>(&d);

> I found that this is also legal--

it will compile.
it will work correctly if and only if the anonymous base class sub-object is at an offset of zero in the derived class object.

do not get lulled into a false sense of security. a reinterpret_cast is a C++ cast. but that does not mean that it gives you any additional protection regarding correctness compared to a C style cast, or the union technique that you posted in another thread. for a reinterpret_cast too, you need to know precisely what you are doing. and as a programmer, you have to take responsibility for its correctness.

Alex Edwards commented: My apologies for an ignorant response. +3
vijayan121 1,152 Posting Virtuoso

> Is there any real different between using an union between two types and a reinterpret_cast between two types
yes, there are quite a lot of differences.
a union reinterprets the layout of memory (depending on which member is accessed).
a reinterpret_cast is a conversion operator.

the conversions that can be performed using a reinterpret_cast are limited; the permissible ones are specified by the standard.

IS 5.2.10 - Reinterpret cast

-1- The result of the expression reinterpret_cast<T>(v) is the result of converting the expression v to type T.
...
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
-2- The reinterpret_cast operator shall not cast away constness. ...
-3- The mapping performed by reinterpret_cast is implementation-defined. ...

and then it goes on to list the conversions that can be performed explicitly using reinterpret_cast. for example this is what is specified about pointer to integral and integral to pointer conversions:

-4- A pointer can be explicitly converted to any integral type large enough to hold it. The mapping function is implementation-defined.
[Note: it is intended to be unsurprising to those who know the addressing structure of the underlying machine. ]
-5- A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type …

Alex Edwards commented: Thanks for the elaborate explanation! +3
vijayan121 1,152 Posting Virtuoso
Alex Edwards commented: For being the first to recommend this book XP +3
vijayan121 1,152 Posting Virtuoso

to reproduce the white spaces in the original in the reversed sentence:

#include <string>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <ctype.h>

template< typename REV_CHAR_ITER >
void print_reverse( REV_CHAR_ITER rbeg, REV_CHAR_ITER rend )
{
  REV_CHAR_ITER found = std::find_if( rbeg, rend, ::isspace ) ;
  std::copy( found.base(), rbeg.base(),
             std::ostream_iterator<char>(std::cout) ) ;

  if( found != rend )
  {
    std::cout << *found ;
    print_reverse( ++found, rend ) ;
  }
}

int main()
{
  const std::string sentence = "test sentence, containing "
                               "a few  extra     spaces,\t\ttabs" ;
  print_reverse( sentence.rbegin(), sentence.rend() ) ;
  std::cout << '\n' << sentence << '\n' ;
}
Agni commented: as usual, perfect solution... thanks a lot +1
vijayan121 1,152 Posting Virtuoso

> The structs are padded so that no padding occurs when we create an array of them,
> like with a scalar variable because if the compiler padded the struct when it created the
> array it wouldn't be the same behaviour we have when we created an array of integers.
> Is this notion correct?

not merely 'it wouldn't be the same behaviour we have when we created an array of integers'. array subscript and pointer arithmetic would not work otherwise.

> an anyone put it more formally?

the formal exposition is in the legalese in the IS (ISO/IEC 14882).
but this arises out of a few simple requirements:
1. the layout and sizeof an object of a particular compile-time type should be known at compile-time.
2. these have to be independent of the storage duration of the object.
3. these also have to be independent of whether the object is an element of an array, a member of a class, a base class sub-object etc.
4. object types can have alignment requirements.
5. an object should be allocated at an address that meets the alignment requirements of its object type.
6. array subscript and pointer arithmetic should work correctly.
7. the memory model of C++ should be compatible with that of C89.

here is a (poor) attempt at a formal explanation:

struct A
{
   char a ;
   int b ;
   char c …
vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <limits>

// addition can be done using bitwise xor
// with adjustments for carry bits
unsigned int plus( unsigned int first, unsigned int second )
{
  unsigned int carry = first & second ; // the carry bits
  unsigned int result = first ^ second ; // the result bits

  while( carry ) // loop over the carry bits
  {
    carry <<= 1U ; // shift carry to next bit
    unsigned int temp = result ^ carry ;
    carry &= result ;
    result = temp ;
  }

  return result;
}

// to subtract, add the two's complement
unsigned int minus( unsigned int first, unsigned int second )
{
  unsigned int carry = ~second & 1U ;
  unsigned int twos_complement = ~second ^ 1U ;

  while( carry )
  {
    carry <<= 1U ;
    unsigned int temp = twos_complement ^ carry ;
    carry &= twos_complement ;
    twos_complement = temp;
  }

  return plus( first, twos_complement ) ;
}

int main()
{
  enum { RADIX = std::numeric_limits<unsigned int>::radix } ;
  struct check_it { char static_assert[ RADIX == 2 ? 1 : -1 ] ; } ;

  for( int i=0 ; i<10 ; ++i )
  {
    unsigned int a = std::rand()%1000 ;
    // a*7 === ( a*8 - a ) === ( a*4 + a*2 + a )
    std::cout << a << " * 7  = " << minus( a<<3U, a ) << " ("
       << plus( a<<2U, plus( a<<1U, a ) ) << ") (" << a*7 << ")\n" ;
  }
}
Alex Edwards commented: You've got quite a head on your shoulders =P +1
vijayan121 1,152 Posting Virtuoso

> The address of a constructor shall not be taken.
> - I am not getting it.

perhaps this snippet will explain this (and a few other things about constructors):

namespace A
{
  enum COLOUR {} ;
  void foo( COLOUR ) {}
  struct bar { bar( COLOUR ) {} void function( COLOUR ) {} };
}

void fun1( A::COLOUR clr )
{ foo(clr) ; } // ok, function A::foo found via koenig lookup

void fun2( A::COLOUR clr )
{ bar(clr) ; } // error, A::bar found, but it is not a function

int main()
{
  A::COLOUR clr ;
  A::bar object( clr ) ;

  object.function( clr ) ; // ok, call function
  object.A::bar::function( clr ) ; // ok, call function

  object.bar( clr ) ; // error, invalid use of struct A::bar
  object.A::bar::bar( clr ) ; // error, invalid use of struct A::bar

  // ok, pointer to member function A::bar::function
  bool not_null = &A::bar::function ;

  // error, &A::bar::bar is not a legal expression
  // address of a constructor cannot be taken
  not_null = &A::bar::bar ;
}

> What is a leak? How is it caused by that code?
a leak is unintentional resource consumption by a program because the program fails to release resources when they are no longer needed. the most often talked about kind of leak is a memory leak; caused by an error in a program that prevents it from freeing up (dynamically allocated) memory that it no longer can use. Foo foo = (*(new …

Prabakar commented: Thanks:) +1
vijayan121 1,152 Posting Virtuoso

n is made automatically from n.o by running the linker (usually called ld) via the C compiler. The precise command used is ...

This rule does the right thing for a simple program with only one source file. It will also do the right thing if there are multiple object files (presumably coming from various other source files), one of which has a name matching that of the executable file....

In more complicated cases, such as when there is no object file whose name derives from the executable file name, you must write an explicit command for linking.

from http://www.gnu.org/software/make/manual/make.html#Implicit-Rules

vijayan121 1,152 Posting Virtuoso

> What compiler are you using?
the non-conforming code compiles on gcc 4.1 (which is known to be non-conforming with respect to template template parameters).
gcc 4.2 and gcc 4.3 correctly gives errors.
there are several discussions on the web regarding this; here is a succinct one:
http://objectmix.com/c/388843-port-gcc-4-3-template-template-issue.html

vijayan121 1,152 Posting Virtuoso

for a standard container, begin() and end() are overloaded on the const specifier.
on a modifiable container, begin() and end() return container::iterator.
on a const container, begin() and end() returns container::const_iterator.

template< typename CNTR > // CNTR is a standard container
void foo( CNTR& cntr, const CNTR& const_cntr )
{
  typename CNTR::iterator iter = cntr.begin() ;
  typename CNTR::const_iterator const_iter = const_cntr.begin() ;
  typename CNTR::reverse_iterator rev_iter = cntr.rbegin() ;
  typename CNTR::const_reverse_iterator const_rev_iter = const_cntr.rbegin() ;
}

this code will not compile:

#include <vector>

void f( std::vector<int>::const_iterator& i )
{ std::cout << *i << std::endl; }

int main()
{
  std::vector<int> v;
  std::vector<int>::iterator b = v.begin() ;
  f(b);
}

but this will:

template< typename ITERATOR > void f( ITERATOR i )
{  std::cout << *i << std::endl; }

#include <vector>

int main()
{
  std::vector<int> v;
  std::vector<int>::iterator b = v.begin() ;
  f(b);
}

c++09: containers also have:

// ...
  const_iterator cbegin() const;
  const_iterator cend () const;
  const_reverse_iterator crbegin() const;
  const_reverse_iterator crend () const;
// ...

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1674.pdf
so things become a bit more convenient.

note: prefer passing an iterator by value (rather than by modifiable reference);
it is more flexible for iterations to be non-intrusive.

Nick Evan commented: good info! +6
vijayan121 1,152 Posting Virtuoso

to enforce const-correctness (a good idea), use const as required. eg.

#include <cstddef>

struct Piece ;

struct board
{
   enum { N = 8 } ;

   struct the_row 
   { 
     const Piece* operator[] ( std::size_t j ) const
     { return j<board::N && row!=0 ? row[j] : 0 ; }

     private : 
	 const Piece* const* row ;
	 explicit the_row( const Piece* const* r ) : row(r) {}
         friend class board ;
   } ;

   the_row operator[] ( std::size_t i ) const
   { return the_row( i<board::N ? array[i] : 0 ) ; }

   // ... 
   private: 
     Piece* array[N][N] ;
};

> since a pointer to an object of the Board class is returned, I cannot declare any of the
> methods/arguments/return values as const, which seems like bad style.
why can't you? you should return a const pointer.
then you can (and you should) declare selectors as const.

VernonDozier commented: good post +4
vijayan121 1,152 Posting Virtuoso

asynchronous write to a file by aio_write http://www.freebsd.org/cgi/man.cgi?query=aio_write&apropos=0&sektion=2&manpath=FreeBSD+7.0-stable&format=html is POSIX.1, and should work on linux.

vijayan121 1,152 Posting Virtuoso

sortValues is not a template member. you need to modify DO_SORT

#define DO_SORT(varName, a, b, c, d) (*(varName)).sortValues(a, b, c, d)

when you are sorting an array of char , use MySort<char> not MySort<char*>

//...
    MySort<char> *myCharSorter = new MySort<char>();
    DO_SORT(myCharSorter, charPt, 0, 5, sortFunction);
//...

using all these void* (java object?), preprocessor macros and non-standard extensions (__typeof__) is not good C++.
here is your program translated into C++ (with a minor bug fixed).

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

template<class T>
class MySort
{
      private:

      public:
             MySort(){};
             ~MySort(){};
             void sortValues( T* value, int start, int size,
                              void (*functocall)(T*, T*));
             //This method accepts a user-defined function and sorts the value.
             //The pointer is expected to have more than just one value, so it will be an array of some type.

              bool isSorted( const T* value, int start, int size)
              {
                   for(int i = start; i < size-1 ; i++)
                   {
                        if(value[i] > value[i + 1])
                           return false;
                   }

                   return true;
              };
};

template<class T>
void MySort<T>::sortValues( T* value, int start, int size,
                            void (*functocall)(T*, T*))
{
    if(start < size)
    {
       while(!isSorted(value, start, size))
       {
            for(int i = start; i < size-1 ; i++)
            {
               T *left = value+i, *right = value+i+1 ;
               (*functocall)((left), (right));
            }
       }
    }
    else
       std::cerr << "Start point cannot be greater than the size!" ;
}

template< typename T > void sortFunction( T* arg1, T* arg2 )
{
  if( *arg2 < *arg1 )
  {
    T temp = *arg1 …
Salem commented: Much better :) +17
vijayan121 1,152 Posting Virtuoso
for( int i=0 ; i<10 ; ++i )
    numb2[i] = i%2 == 0 ? (i/2)*5 : i ;
vijayan121 1,152 Posting Virtuoso

> ...probably some gcc/g++ extension that was messing things up
> (which is obviously the only real possibility here).
it is not some gcc/g++ extension; it is POSIX man pause http://node1.yo-linux.com/cgi-bin/man2html?cgi_command=pause(2)

John A commented: Thanks for the clarification. +15
vijayan121 1,152 Posting Virtuoso

> i try to avoid copying anything than 2 pointers...
swapping pointers is easy; swap pointers to arrays just like you swap any other pointers.

#include <stdio.h>

void swap( int rows, int cols, float (**after)[rows][cols] , 
           float (**before)[rows][cols] )
{
  float (*temp)[rows][cols] = *after ;
  *after = *before ;
  *before = temp ;
}

int main()
{
  int rows = 3, cols = 4 ;
  float one[rows][cols] ; one[0][0] = 1.1 ;
  float two[rows][cols] ; two[0][0] = 2.2 ;
  float (*p1)[rows][cols] = &one ; 
  float (*p2)[rows][cols] = &two ; 
  printf( "%f\t%f\n", (*p1)[0][0], (*p2)[0][0] ) ; 
  swap( rows, cols, &p1, &p2 ) ;
  printf( "%f\t%f\n", (*p1)[0][0], (*p2)[0][0] ) ; 
}

this means that you will have to write the array_function in terms of pointers to arrays:

void array_function( int rows, int cols, float (*after)[rows][cols],
                     float (*before)[rows][cols] )
{
	//for some iterations	
	for(;;)
	{
		int i, j ;
		//for all the elements int the array
		for (i=1; i<rows; i++)
			for(j=1; j<cols; j++)
				(*after)[i][j] = 4 * (*before)[i][j] ;

		//afterwards prepare for the next iteration
		swap( rows, cols, &after, &before ) ;
	}
}
n.aggel commented: always helpful! +2
vijayan121 1,152 Posting Virtuoso

c++98 has the convenient std::pair<> .
c++09 also has std::tuple<> .

#include <utility>
#include <algorithm>
#include <tuple>

std::pair<int,int> min_n_max( const int* arr, std::size_t N )
{
  // invariant: N > 0
  int low = arr[0] ;
  int high = arr[0] ;
  
  for( std::size_t i=1 ; i<N ; ++i )
  {
    low = std::min( low, arr[i] ) ;
    high = std::max( high, arr[i] ) ;
  }
    
  return std::make_pair(low,high) ;
}

std::tuple<int,int,double> min_max_n_avg( const int* arr, std::size_t N )
{
  // invariant: N > 0
  int low = arr[0] ;
  int high = arr[0] ;
  int sum = arr[0] ;
    
  for( std::size_t i=1 ; i<N ; ++i )
  {
    low = std::min( low, arr[i] ) ;
    high = std::max( high, arr[i] ) ;
    sum += arr[i] ;
  }
    
  return std::make_tuple( low, high, sum/double(N) ) ;
}
vijayan121 1,152 Posting Virtuoso

> Is there anything that 'wraps' pipes?
i do not know of any, but it is very easy to roll out one of our own. eg.

#include <stdio.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include <iostream>
using namespace boost::iostreams ;

struct opipestream : stream< file_descriptor_sink >
{
  typedef stream< file_descriptor_sink > base ;
  explicit opipestream( const char* command )
    : base( fileno( pipe = popen( command, "w" ) ) ) {}
  ~opipestream() { close() ; pclose( pipe ) ; }
  private : FILE* pipe ;
};

int main()
{
  std::cout << "#includes in this file:" << std::flush ;
  std::ifstream fin( __FILE__ ) ;
  opipestream pout( "grep '^#include' | wc -l" ) ;
  pout << fin.rdbuf() ;
}

// link with libboost_iostreams  eg.
// g++ -Wall -std=c++98 -pedantic -I /usr/local/include -L /usr/local/lib -lboost_iostreams myfile.cc
vijayan121 1,152 Posting Virtuoso

the C library clock() does not give the wall clock:

the clock() function determines the amount of processor time used since the invocation of the calling process, measured in CLOCKS_PER_SECs of a second.

just sleeping or waiting for input will work for time() (which gives the wall time), not for clock() ; no processor time is used by the process while it is in a wait state.

Salem commented: Yes, sleeping and I/O doesn't count. +15
vijayan121 1,152 Posting Virtuoso

> I would like to be able to read from pipe in child so I know what parent has sent.
> How to do this ...
the simplest way would be to use read and write on the anonymous pipe.
man read(2) http://www.freebsd.org/cgi/man.cgi?query=read&apropos=0&sektion=2&manpath=FreeBSD+7.0-stable&format=html
man write(2) http://www.freebsd.org/cgi/man.cgi?query=write&apropos=0&sektion=2&manpath=FreeBSD+7.0-stable&format=html

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
  int toChild[2] = {0}, fromChild[2] = {0};
  pid_t pid = -1 ;
  char parent_msg[] = "*** message from parent" ;
  char child_msg[] = "### message from child" ;

  pipe(toChild) ;
  pipe(fromChild) ;
  pid = fork() ;

  if(pid == 0)
  {/* CHILD */
    close(toChild[1]); //child won't write to child... :)
    close(fromChild[0]); //child won't read it's own messages
    char buff[ sizeof(parent_msg) ];
    read( toChild[0], buff, sizeof(parent_msg) ) ;
    pid_t pid = getpid() ;
    printf( "in child (pid %d): read: %s\n", pid, buff ) ;
    write( fromChild[1], child_msg, sizeof(child_msg) ) ;
    close(toChild[0]);
    close(fromChild[1]);
  }
  else
  {/* PARENT */
    close(toChild[0]); //paren't won't read his own messages...
    close(fromChild[1]); //paren't won't write to parent... :)
    write( toChild[1], parent_msg, sizeof(parent_msg) ) ;
    char buff[ sizeof(child_msg) ];
    read( fromChild[0], buff, sizeof(child_msg) ) ;
    pid_t pid = getpid() ;
    printf( "in parent (pid %d): read: %s\n", pid, buff ) ;
    close(toChild[1]);
    close(fromChild[0]);
  }
  return 0;
}
vijayan121 1,152 Posting Virtuoso

> a different program to read from that file BEFORE the first program is finished writing to it.
the output to a file is buffered at many levels: by the fstreambuf of the c++ library and by the operating system (cache manager). to achieve coherence between the two processes' view of the file, consider memory mapping the file.
see: http://msdn2.microsoft.com/en-us/library/aa914748.aspx
and http://msdn2.microsoft.com/en-us/library/aa914405.aspx

vijayan121 1,152 Posting Virtuoso

boost::algorithm::split works like std::strtok . delimiters that are just single characters.
use boost::algorithm::split_regex to split character sequences where delimiters are regular expressions.
for example, to split a string on delimiters which are either sequences of some number of digits or ->

#include <string>
#include <iostream>
#include <iterator>
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <vector>
using namespace std;
using namespace boost;

int main()
{  
  string str = "abc1234def->ijkl->mnop56qrs->tuv7890wxyz" ;
  vector< string > result;
  boost::algorithm::split_regex( result, str, 
                                 regex( "[0-9]+|->" ) ) ;
  copy( result.begin(), result.end(),
        ostream_iterator<string>( cout, "\n" ) ) ;
}

note: you need to link with libboost_regex. eg.

> g++ -Wall -std=c++98 -pedantic -Werror -I /usr/local/include -L /usr/local/lib -lboost_regex myprogram.cc
sjcomp commented: Good alternative, clear example +1