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

> But, what do you do when T is "list"
> For example: list_base<list>

> You get the annoying recursion problem again!
> Anyother great idea on this?

Perhaps you should first describe the real problem that you are trying to solve. It might, just might, have a much easier solution.

vijayan121 1,152 Posting Virtuoso

See: http://docs.sun.com/source/806-3568/ncg_goldberg.html

You might want to use a library like MPFR (a multiple-precision floating-point computations library with correct rounding). A C++ wrapper would be convenient. There are several, you can find one of them here:
http://beshenov.ru/mpfrcpp/

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

> Is it just a syntax problem to be amended in a future revision of C++
> or is there some underlying theoretically reason that I haven't think about?

There is an underlying theoretical reason, and you have already thought about it.

A pointer to member of a class cannot be introduced before the class is at least declared.

// error: `undeclared_class' has not been declared
int undeclared_class::*pointer_to_member ; 

struct declared_class ;
// fine: `declared_class' has been declared
int declared_class::*pointer_to_member ;

In this case, just to declare the class we need a pointer to member of that class which is not yet declared (which we are trying to declare).

You also have a discovered the solution; split this into two classes.

#include <iostream>

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

    T* member_a ;
    T* member_b ;
    // ...
};

template < typename T, T* list_base<T>::*PTR_MEMBER > 
struct list : list_base<T>
{
    explicit inline list( T* a = 0, T* b = 0 ) 
       : list_base<T>(a,b) {}

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

    // ...
};

template < typename T, T* list_base<T>::*PTR_MEMBER >
inline T* get_it( list<T,PTR_MEMBER>& lst ) 
{ return lst.*PTR_MEMBER ; }

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

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

    std::cout << *lst1.get() << '\t' << *get_it(lst1) << '\n' …
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

Are you looking for something like this?

template< typename T > struct list
{
    T* current ;
};

template< typename T, T* T::*PTRMEMBER >
T* get_next( list<T>& lst ) 
{ 
    lst.current = lst.current->*PTRMEMBER ; 
    return lst.current ;
}

struct A
{
    A* member_one ;
    A* member_two ;
};

int main()
{
    A one = A() ;
    A two = A() ;
    A three = { &two, &one } ;
    A four = { &three, &two } ;

    list<A> lst = { &four };

    std::cout << get_next< A, &A::member_one >( lst ) 
              << '\t' << &three << '\n' ;

    std::cout << get_next< A, &A::member_two >( lst ) 
              << '\t' << &one << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

> Its printing only the first elements

Well, you have a multimap which contains multimaps :
multimap<string,multimap<string,int> > mymm;

So you need a nested loop to print the contents of the inner multimaps. Something like:

for (itx = mymm.begin(); itx != mymm.end(); ++itx)
{
  cout << "  [" << itx->first << "] " ;
  for( it = itx->second.begin() ; it != itx->second.end() ; ++it )
        cout << it->first << ',' <<  it->second << "   " ;
  cout << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

Export members selectively from your dll:

class my_class
{
    public:
        void foo() ; // not exported
        __declspec(dllexport) void bar() ; // exported
};

void my_class::foo() {}

__declspec(dllexport) void my_class::bar() {}

And import them selectively in places where you want to use it:

class my_class
{
    public:
        void foo() ; // not imported
        __declspec(dllimport) void bar() ; // imported
};

void my_class::foo() {}

see the section 'Selective Member Import/Export' here:
http://msdn.microsoft.com/en-us/library/81h27t8c%28VS.80%29.aspx

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

Use something like std::vector< boost::any >
http://www.boost.org/doc/libs/1_37_0/doc/html/any.html

vijayan121 1,152 Posting Virtuoso

Either of these two is the right way to declare C::foo<> as a friend.

struct C
{
	template < bool B > void foo() ;

	template< bool B > class B
	{
		// ok, the compiler already knows that C::foo 
                // is a template function
		friend void C::foo() ; 

		// more general, tell the compiler explicitly that 
                // we are referring to the template function C::foo
		friend void C::foo <> () ;
	} ;

} ;

template < bool B > void C::foo() {} ;
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

A good implementation of the vector would call the copy constructor when memory is reallocated. Invoking the default constructor first and then the assignment operator has an efficiency issue.
Note: C++0x containers would use move semantics (instead of copy semantics) if they are available on the object.

Modify the code to

int constructor_count=1,destructor_count=1;

class obj{public:
	obj(){
		cout<<"C: "<<constructor_count++<<'\n';
	}	
        
         obj( const obj& ){
		cout<<"C: "<< constructor_count++<<'\n';
	}	
	~obj(){
		cout<<"D: "<<destructor_count++<<'\n';
	}
};

and you would find that calls to constructors and destructors are matched perfectly.

> I was storing handles to window objects in a "wrapper class", and I
> got an error every time I resized the vector so that it needed to
> allocate more memory (ie it was fine if I called reserve(1000);
> at the start), and I've traced it down to this.

Make sure that your wrapper class does have a correct copy constructor and a correct overloaded assignment operator (hint: you need to keep a count of how many handles refer to a window). And the problem will go away.

vijayan121 1,152 Posting Virtuoso

std::transform is perhaps what you are looking for.
http://www.cppreference.com/wiki/stl/algorithm/transform

vijayan121 1,152 Posting Virtuoso

> obj.baseInfo::SlotCount[0] = 5;
> This compiles fun but gives me an error after running it.

It should not compile (though IIRC, microsoft compilers just give a warning that memory would be corrupted and proceed to generate incorrect code that will corrupt the memory - on the stack in this case).

The name of a nested class is local to its enclosing class. To use the name of the nested class outside the enclosing class, qualify it with the name of the enclosing class.

int main()
{

	base obj;
	//obj.baseInfo::SlotCount[0] = 5; // error

	base::baseInfo info_object ;
        info_object.SlotCount[0] = 5 ; // fine

}

Also, declare the constructor as inline if you are going to define it in the header file. Else, you will get a linker error (constructor is multiply defined) if you #include the header in more than one translation unit.

You may also want to search this forum to discover the implications of using system("PAUSE"); in your code.

vijayan121 1,152 Posting Virtuoso

Most, but not all, Boost libraries are header-only libraries; most often, there's nothing to build.

However, a few libraries must be built separately. Boost DateTime has a binary component that is needed if you're using its to_string/from_string or serialization features.

If you do not have the binaries installed, you need to build the boost libraries first to be able to use from_simple_string(). For detailed instructions on how to do this, and the compiler/linker options for linking to the libraries, see:
http://www.boost.org/doc/libs/1_41_0/more/getting_started/unix-variants.html#get-bjam

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

In this specific case (file not found), the what() of the exception may make sense to the user. But more often, for instance, if a std::vector<> throws a std::out_of_range, it is meaningful only to to the code (programmer) and not to the end-user.

It is never a good idea to create your own exception classes which are not related to the <stdexcept> heirarchy. Standard exceptions like std::bad_aloc, std::bad_cast and std::bad_exception are thrown by the implementation and the standard library components throw exceptions like std::out_of_range. It makes error handling easier if you do not have to have two separate catch expressions every time; a single catch( const std::runtime_error& ) should be able to catch all run time errors.

There are two ways to address your specific problem.

The first, and much simpler one (which I prefer) is to right a function to convert the what() of an exception to a wide character string.

std::wstring what2wstr( const std::exception& ex )
{
    // convert ex.what() to a wide character string and return it
    // trivially done here, ok for US-ASCII in UTF-8 => UNICODE
    std::string str( ex.what() ) ;
    std::wstring wstr( str.size(), ' ' ) ;
    std::copy( str.begin(), str.end(), wstr.begin() ) ;
    return wstr ;
}

The second is to create an exception base class with a wwhat() that returns a wide character string, and then multiply inherit your exceptions from this and one of the standard exception classes.

struct wchar_exception
{
    virtual const wchar_t* wwhat() const { …
vijayan121 1,152 Posting Virtuoso

In general, if you're displaying error messages to the user based on what() of an exception that was thrown, you are probably doing something wrong.

The code that throws an exception is very unlikely to be able to compose a relevant and user-comprehensible error message at the point an exception is thrown. Exceptions are for communicating errors between sections of code and are not designed to be for user-consumption. They are not designed to be localizable (why would they be? An exception could be thrown by code very far away from the user). The code that catches the exception should inspect it to find out what it is about, and display the error message accordingly.

You can always define your own class derived from std::exception which stores std::wstring inside it, and use that for all your exceptions. But it would perhaps be the wrong error handling idiom to use.

The Boost error handling guidelines covers this aspect well:

Don't worry too much about the what() message. It's nice to have a message that a programmer stands a chance of figuring out, but you're very unlikely to be able to compose a relevant and user-comprehensible error message at the point an exception is thrown. Certainly, internationalization is beyond the scope of the exception class author. Peter Dimov makes an excellent argument that the proper use of a what() string is to serve as a key into a table of error message formatters.

from http://www.boost.org/community/error_handling.html

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

You could do this in linear time; see Boyer and Moore's Voting Algorithm
http://www.cs.utexas.edu/users/moore/best-ideas/mjrty/index.html

#include <iostream>

int candidate_element( const int *array, int N )
{
    int count = 1 ;
    int curr_candidate = 0 ;

    for( int i = 1 ; i < N ; ++i )
    {
        if( array[i] == array[curr_candidate] ) ++count ;
        else --count ;

        if( count == 0 )
        {
            curr_candidate = i ;
            count = 1 ;
        }

    }
    return array[curr_candidate] ;
}

bool is_majority_element( const int *array, int N, int candidate )
{
  int cnt = 0 ;
  for( int i = 0 ; i < N ; ++i )
      if( array[i] == candidate ) ++cnt ;
  return cnt > N/2 ;
}


int main()
{
    int array[] = {2,3,2,2,4,2,2,2,4,4,4,4,4,4,2,2,2} ;
    enum { N = sizeof(array)/sizeof(*array) } ;

    int candidate = candidate_element( array, N ) ;

    if( is_majority_element( array, N, candidate ) )
        std::cout << "majority element: " << candidate << '\n' ;
    else
        std::cout << "there is no majority element\n" ;
}
vijayan121 1,152 Posting Virtuoso

a string which can be used ala std::string, preserves case, but comparisons are not case sensitive.

vijayan121 1,152 Posting Virtuoso

choose a random element from a sequence when
a. you do not know how many elements are there before hand
b. you want to make one single pass through the sequence
c. you do not want to use auxiliary storage

vijayan121 1,152 Posting Virtuoso

> what is the relation between a socket and a port.
> I mean a socket is a special kind of file descriptor
> when i use file descriptors i don't use ports
> why we have to use ports when we use a socket?

a socket has no relation to a port.

a socket is created with the socket function has no name. this is no different from other file descriptors. a file descriptor also has no name. for example, stdin, stdout, stderr are file descriptors.
you use the open function to create a descriptor, the name that you give is the name of a file in the filesystem (which has an existence independant of file descriptors).

a remote process has no way to refer to a socket until a name (an address) is bound to it. an address is given to a socket via the bind function call. the address serves as a unique name using which a socket can be referred to.

In the UNIX domain, an address is simply a filesystem path. eg.

sockaddr_un addr;
 ...
std::strcpy( addr.sun_path, "/tmp/my_socket" ) ;
addr.sun_family = AF_UNIX ;
bind ( ... (sockaddr*) &addr, .... ) ;

The file name referred to is created as a socket in the system file name space. (write permission in the directory is required). these can be deleted with unlink().

in the Internet domain, the name is a tuple consisting of the IP address …

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

> can u pass template class objects as parameters to friend functions of the same class??

obviously, you can. but you need to let the compiler know that they are templates.

#include <iostream>

// declare things first
template< typename T > class array ;

template< typename T >
std::istream& operator>> ( std::istream& din, array<T>& b ) ;

template< typename T >
std::ostream& operator<< ( std::ostream &dout, const array<T> &b) ;

// define them now
template< typename T > class array
{
  T a[10] ;  // concept: T is default_constructible
  int n ;

  // <> tells the compiler that the friend is a template.
  // http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16
  friend std::istream& operator>> <> ( std::istream&, array<T>& ) ;
  friend std::ostream& operator<< <> ( std::ostream&,
                                       const array<T>& ) ;
  //...
};

template< typename T >
std::istream& operator>> ( std::istream& din, array<T>& b )
{
  din >> b.n ; // what happens if the user enters a value > 10 ?
  for( int i=0; i<b.n; ++i ) din >> b.a[i] ;
  return din ;
}

template< typename T >
std::ostream& operator<< ( std::ostream &dout, const array<T> &b)
{
  dout << b.n << '\n' ;
  for( int i=0 ; i<b.n ; i++) dout<<b.a[i] << " " ;
  return dout << '\n' ;
}

int main()
{
  array<int> iarray ;
  std::cin >> iarray ;
  std::cout << iarray ;
}
vijayan121 1,152 Posting Virtuoso

First, is this the "best" way to tackle the chat problem?

no. it is unlikely that someone would want to set up a chat between two processes on the same machine, sharing stdin and stdout between them. write two separate programs; the server and the client. which can be run on different machines.


> each time i try to send something from app1 to app2.
> app2 never receives the msg... but instead app1 does! why?

i've only had a cursory look, but:
the forked child process has its own copy of the parent's descriptors.
but these descriptors reference the same underlying objects as the parent.
both the parent and child processes are using the same socket, same stdin etc.

vijayan121 1,152 Posting Virtuoso

you need to enable RTTI. (use compiler switches for this.)
either you have turned it off by using the switch /GR-
or you are using a fairly old version of the microsoft compiler.
turn it on with the compiler switch /GR
http://msdn.microsoft.com/en-us/library/we6hfdy0.aspx

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

> man mmap <Enter>
at the command prompt on your system. it should give you all the information that you require.you would see something like this: http://www.freebsd.org/cgi/man.cgi?query=mmap&apropos=0&sektion=0&manpath=FreeBSD+7.0-stable&format=html

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
struct base
{
  virtual std::ostream& write( std::ostream& stm ) const = 0 ;
  // ...
};

inline  std::ostream& operator<< ( std::ostream& stm, const base& object )
{
  return object.write( stm ) ; // polymorphic
}

// ----------------------------------------------------------------------------------------------------

struct derived : base
{
  // override
  virtual std::ostream& write( std::ostream& stm ) const
  {
    // write object out to stream
    return stm ;
  }
  // ...
};
vijayan121 1,152 Posting Virtuoso
template <typename C>
typename C::iterator SlowFind(C& c, const typename C::value_type& v)
{
    typename C::iterator i;
    for (i = c.begin(); i != c.end() && *i != v; ++i)
        ;
    return i;
}

this is broken when C is a const container.
c.begin() and c.end() returns objects of type C::const_iterator.

in C++98 you would have to do something like

template < typename CNTR > struct container_traits
{  typedef typename CNTR::iterator iterator ;  } ;

template < typename CNTR > struct container_traits< const CNTR >
{ typedef typename CNTR::const_iterator iterator ; } ;

template < typename CNTR >
typename container_traits<CNTR>::iterator SlowFind( CNTR& cntr, 
                                const typename CNTR::value_type& value )
{   return std::find( cntr.begin(), cntr.end(), value )  ;  }

C++09 makes it a lot easier:

template < typename CNTR >
auto SlowFind( CNTR& cntr, const typename CNTR::value_type& value 
             ) -> decltype( cntr.begin() ) 
{   return std::find( cntr.begin(), cntr.end(), value )  ;  }
vijayan121 1,152 Posting Virtuoso

have a look at the standard header <utility>. it defines std::pair and std::make_pair.

template <typename First, typename Second>
struct Pair 
{  
  First f;
  Second s;
  Pair( const First& ff, const Second& ss ) :  f(ff), s(ss) {}
  // etc
};

template <typename First, typename Second> inline 
Pair<First,Second>   makePair( const First& f, const Second& s )
{ return   Pair<First,Second>( f, s ) ; }
vijayan121 1,152 Posting Virtuoso

bulk rename of all the .wav files in one go and updating the text in all the .phr files at another time can leave you in a messy state in the event of a crash (you would have to restart all over again after restoring from backups). you could consider renaming the .wav file and updating its text in the .phr file in one go.

perhaps, using a single map would be easier than having two different vectors. maybe something like this:

a. have a std::map<std::string,std::string> with the original/modified file names as the key and data.

b. recurse the directory (tree) for .wav files and insert the original/modified filenames in the map.

c. i. recurse the directory (tree) for .phr files, open each, and search each line for an instance of the filename text. ii. lookup the file name in the map, if found, rename the .wav file and replace filename text in the .phr file.

d. iterate through the map and rename any remaining .wav files. (which had no entries in the .phr files).

could be a lot easier to do it in python/perl/ruby instead of C++.

vijayan121 1,152 Posting Virtuoso

the general knapsack problem and the subset sum problem are NP-hard, but not NP-incomplete. so there are no polynomial-time algorithms. but it is one of the easy NP-complete problems to solve.

it can be solved (in pseudo-polynomial time) using dynamic programming.

AFAIK, using a Branch and bound algorithm http://en.wikipedia.org/wiki/Branch_and_bound should yield a faster solution. perhaps, you should use a recursive (rather than iterative) Branch and bound. iteration won't give you any significant improvement in performance here.

knuth volume 4 http://www.amazon.com/Art-Computer-Programming-Fascicle-Combinatorial/dp/0321534964 would be the definitive reference.

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

> #pragma - what does it mean
to understand what #pragma is see: http://msdn.microsoft.com/en-us/library/d9x1s805(vs.71).aspx
for the specific #pragma directives that are in your code, refer to your compiler docs.

> what does word __fastcall mean
__fastcall is an implementation-defined keyword in microsoft and several other compilers. it specifies a particular calling convention for a function.
http://msdn.microsoft.com/en-us/library/6xa169sk(VS.71).aspx

> what does expression: k = 1 << i; mean?.
> (maskIO & 0x08) what does it mean?.
these are C/C++ bitwise operators. http://www.cprogramming.com/tutorial/bitwise_operators.html

vijayan121 1,152 Posting Virtuoso

have each of the two stacks to store a reference to a std::deque.
initialize them to refer to the same std::deque.
write a wrapper class to hold the two stacks.

template< typename T > struct dual_stack
{

  struct first_stack
  {
    explicit first_stack( std::deque<T>& seq ) : sequence(seq) {}
    // implement stack members
    // push/pop => sequence.push/pop_front()
    private : std::deque<T>& sequence ;
  };

  struct second_stack
  {
    explicit second_stack( std::deque<T>& seq ) : sequence(seq) {}
    // implement stack members
    // push/pop => sequence.push/pop_back()
    private : std::deque<T>& sequence ;
  };


  dual_stack() : _first_stack(sequence), _second_stack(sequence) {}

  first_stack& first() { return _first_stack ; }
  second_stack& second() { return _second_stack ; }
  // const versions of the above, other members.

  private: 
    std::deque<T> sequence ;

    first_stack _first_stack ;
    second_stack _second_stack ;
};
vijayan121 1,152 Posting Virtuoso

writing a convert function (with construction and destruction of a stringstream each time it is called) would give more maintainable code. even in this case, the performance seems to be acceptable:

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include <math.h>

#pragma unmanaged
void double_to_string()
{
  std::clock_t start = std::clock() ;
  for(int i = 0; i < 200000; i++)
  {			
    double Number1 = 8.12;
    static std::string Num ;
    std::ostringstream v1 ;
    v1 << Number1 ;
    Num = v1.str() ;
  }
  std::clock_t end = std::clock() ;
  std::cout << "double_to_string: "
    << double( end-start ) / CLOCKS_PER_SEC << '\n' ;
}
#pragma managed

#pragma unmanaged  // generate native code
void string_to_double()
{
  std::clock_t start = std::clock() ;
  for(int i = 0; i < 2000000; i++)
  {			
    double Number1 ;
    static std::string Num = "8.12" ;
    std::istringstream v1(Num);
    v1 >> Number1 ;
  }
  std::clock_t end = std::clock() ;
  std::cout << "string_to_double: " 
    << double( end-start ) / CLOCKS_PER_SEC << '\n' ;
}
#pragma managed

#pragma unmanaged
void cstrng_to_double()
{
  std::clock_t start = std::clock() ;
  for(int i = 0; i < 2000000; i++)
  {	
    double Number1 ;
    const char* Num = "8.12";
    Number1 = std::atof(Num);
  }
  std::clock_t end = std::clock() ;
  std::cout << "cstrng_to_double: " 
    << double( end-start ) / CLOCKS_PER_SEC << '\n' ;
}
#pragma managed

int main( array< System::String^ >^ args )
{
  for( int i=0 ; i<4 ; ++i )
  {
    double_to_string() ;
    string_to_double() ;
    cstrng_to_double() ;
    std::cout << '\n' ;
  }
}
double_to_string: 1.186 …
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

in adition, change int size = 100; to const int size = 100; size of an array must be a constant known at compile time.

vijayan121 1,152 Posting Virtuoso

> What I look for now is a fast way to convert from double to char*
> I have a problem to find this conversion.

a. compile C++ source to generate native code, not IL that is interpreted at run-time.
b. enable optimizations.

with these two, this is what i get:

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include <math.h>

#pragma unmanaged   // generate native code
void double_to_string()
{
  std::clock_t start = std::clock() ;
  for(int i = 0; i < 2000000; i++)
  {			
    double Number1 = 8.12;
    static std::string Num;
    static std::stringstream v1;
	  v1 << Number1;
	  v1 >> Num;
  }
  std::clock_t end = std::clock() ;
  std::cout << "double_to_string: "
    << double( end-start ) / CLOCKS_PER_SEC << '\n' ;
}
#pragma managed

#pragma unmanaged   // generate native code
void string_to_double()
{
  std::clock_t start = std::clock() ;
  for(int i = 0; i < 2000000; i++)
  {			
    double Number1 ;
    static std::string Num = "8.12" ;
    static std::stringstream v1;
	  v1 << Num;
	  v1 >> Number1;
  }
  std::clock_t end = std::clock() ;
  std::cout << "string_to_double: " 
    << double( end-start ) / CLOCKS_PER_SEC << '\n' ;
}
#pragma managed

#pragma unmanaged   // generate native code
void cstrng_to_double()
{
  std::clock_t start = std::clock() ;
  for(int i = 0; i < 2000000; i++)
  {	
    double Number1 ;
    const char* Num = "8.12";
    Number1 = std::atof(Num);
  }
  std::clock_t end = std::clock() ;
  std::cout << "cstrng_to_double: " 
    << double( end-start ) / CLOCKS_PER_SEC << '\n' ;
}
#pragma managed …
vijayan121 1,152 Posting Virtuoso

consider using the std::tr1 polymorphic function wrappers. this would allow using free functions, member functions and function objects in a polymorphic way.

if your compiler does not ship with tr1, you can use boost::function in the interim.
http://www.boost.org/doc/libs/1_36_0/doc/html/function/tutorial.html#id2903300

#include <iostream>
#include <string>
#include <map>
#include <vector>

// tr1: #include <functional>
#include <boost/function.hpp>

using std::map;
using std::string;
using std::vector;
using std::cout;
using std::cin;
using std::endl;

class Console
{
	// Private variables
  int finished, success;
  string input;

public:
	// The Base structure of the console and resposible for automation.

  // tr1: typedef std::tr1::function< int(Console*) > function_type ; 
  typedef boost::function< int(Console*) > function_type ;
  struct Action
  {
    string help;     		// Action documentation
    function_type call;	// Function to call
  };
  map<string,Action> action_index;

  // Functions
  int quit()
  {
    finished = 1;
    return 0;
  }

  void report_error(string error_kind)
  {
    if (error_kind == "com")
    {
      cout << "Invalid command. Type \"help\" for a list of commands." << endl;
    }
  }

  int help()
  {
   	cout << "Action:\t\t\tDescription:" << endl;
  	// For each element in the action_list, print it's name and description
   	for (map<string,Action>::iterator counter = action_index.begin(); counter != action_index.end(); counter++)	
   	{
   		cout
    		// Print command's name
					<< counter->first
					<< "\t\t\t"
    		// Print command's description
					<< counter->second.help
					<< endl;
   	}
    	return 0;
   }

	void read()
	{
		// Asks for input, and reads it
		while (finished != 1)
		{
			success = 0;
			cout << ">>>"; getline(cin,input);
			for (map<string,Action>::iterator counter = action_index.begin(); counter != action_index.end(); counter++)
			{
				if (input == counter->first)
				{
					success = 1;
					counter->second.call(this);
					break; …
vijayan121 1,152 Posting Virtuoso

> But I still find it ackward, that there are no possibility to do it.
> I can handle special cases when, I have different INPARS as long as the method is void.
> But it's not possible to do it when you have a return type.

you can get the effect of overloading on the return type by using a meta-function (array_divide_result_traits in the following snippet) to deduce the return type.

template<typename T> class Array ;

template< typename T > struct array_divide_result_traits
{
  typedef T element_type ;
  typedef Array<T> result_type ;
};

template<> struct array_divide_result_traits<int>
{
  typedef double element_type ;
  typedef Array<double> result_type ;
};

template<typename T>
class Array {
 public:
  // ...
  Array(int length):x_(length),data_(new T[length]){}

  template< typename U > Array( const Array<U>& that ) 
    : x_(that.x_), data_(new T[that.x_])
  { for( int i=0 ; i<x_ ; ++i ) data_[i] = T( that.data_[i] ) ; }
  // ...

  typedef typename array_divide_result_traits<T> divide_traits ;
  typename divide_traits::result_type operator/ (const double &other);

private:
  int x_;
  T*  data_;
  int numOnes_;
  template< typename U > friend class Array ;
};

template<typename T> 
typename Array<T>::divide_traits::result_type 
  Array<T>::operator/ ( double const & other )
{
  if(other==0){ /* error */ }

  typedef typename Array<T>::divide_traits::result_type result_type ;
  typedef typename Array<T>::divide_traits::element_type element_type ;

  result_type tmp = result_type(x_);

  for(int i=0;i<x_;i++) 
    tmp.data_[i] = element_type( data_[i] ) / other;

  return tmp;
}

int main()
{
  Array<int> a(10);
  Array<double> b = a / 2;
  Array<int> c = b ;
}

note 1: the templated copy constructor is there to make line …

vijayan121 1,152 Posting Virtuoso

a std::tr1::shared_ptr cannot correctly hold a pointer to a dynamically allocated array. AFAIK, there is no such smart pointer in tr1.
you could use boost::shared_array (tr2) instead. http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_array.htm std::tr1::shared_ptr to a std::vector is a far more flexible alternative.