vijayan121 1,152 Posting Virtuoso

> what is the problem
the problem is that string b; creates an empty string. b[j]=a[i]; is incorrect; there are no characters in b.

> i want the first character on string a to be the last char on string b
> up until the last on a is the first on b
this would suffice.

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

int main()
{
  string a;
  cout<< "enter string" <<endl;
  cin>> a;

  string b( a.rbegin(), a.rend() ) ;
  cout<< b <<endl;
}
vijayan121 1,152 Posting Virtuoso

if you want to iterate through a sequence container erasing elements as you go along, you must use the return value of container::erase . the return value is a vald iterator that designates the first element remaining beyond element(s) erased, or end if no such element exists. for example, the following will erase all even numbers from the vector.

std::vector<int> vec(100) ;
  for( int i=0 ; i<vec.size() ; ++i ) vec[i] = i ;
  std::vector<int>::iterator iter = vec.begin() ; 
  while( iter != vec.end()  )
  {
    if( ( *iter % 2 ) == 0 ) iter = vec.erase( iter ) ;
    else ++iter ;
  }

to remove duplicate elements that are adjacent to each other in a specified range, you can use the algorithm std::unique . for example, this will erase adjacent duplicate elements from the vector.

std::vector<int> vec(100) ;
  for( int i=0 ; i<vec.size() ; ++i ) vec[i] = i/10 ;
  vec.erase( std::unique( vec.begin(), vec.end() ), vec.end() ) ;
Ancient Dragon commented: Gread explaination -- I learned something too today :) +25
vijayan121 1,152 Posting Virtuoso

> ... but it doesn't really pose a problem here ...

this

ofstream newOccupant;

if(AuthorizeEntry(IDcard,lot))
{
  cout<<"Lot Accessed." <<endl;
  
  if(lot == 'A')
    ofstream newOccupant("lot_A.txt", ios::out);
  if(lot == 'B')
    ofstream newOccupant("lot_B.txt",  ios::out);
  if(lot == 'C')
    ofstream newOccupant("lot_C.txt",  ios::out);
  if(lot == 'D')
    ofstream newOccupant("lot_D.txt",  ios::out);
  if(lot == 'E')
    ofstream newOccupant("lot_E.txt",  ios::out);
  
  if(!newOccupant)
  // ...

is equivalent to this

ofstream newOccupant;

if(AuthorizeEntry(IDcard,lot))
{
  cout<<"Lot Accessed." <<endl;
  
  if(lot == 'A')
  {
    ofstream newOccupant("lot_A.txt", ios::out);
  }
  if(lot == 'B')
  {
    ofstream newOccupant("lot_B.txt",  ios::out);
  }
  if(lot == 'C')
  {
    ofstream newOccupant("lot_C.txt",  ios::out);
  }
  if(lot == 'D')
  {
    ofstream newOccupant("lot_D.txt",  ios::out);
  }
  if(lot == 'E')
  {
    ofstream newOccupant("lot_E.txt",  ios::out);
  }
  
  if(!newOccupant)
  // ...

> ... as the only use of newOccupant occurs within that if block ..
the only thing that happens in the each of the if blocks are that an ofstream is constructed and immediately destroyed. these ofstreams are not visible and do not exist at the place where an ofstream is used. the ofstream that is used is the one in the outer scope, to which a file has never been associated.

6.4 - Selection statements [stmt.select]
.... If the substatement in a selection-statement is a single statement and not a ompound-statement, it is as if it was rewritten to be a compound-statement containing the original substatement. [Example:
if (x)
int i;
can be equivalently rewritten as
if (x) {
int i;
}
Thus after the if statement, i is no …

vmanes commented: Good catch on subtle aspect +3
vijayan121 1,152 Posting Virtuoso

> I was creating the derived class method definitions in a cpp file
> and couldn't get the project to progressively compile correctly.
> At my first method definition, a default constructor,
> the compiler kept spitting out this error message:

this is perhaps the most obscure error message that gcc (actually the linker) spits out, but the reason is simple:

the compiler has to put the (one and only one) vtable for a class into some object file or the other. it puts it into the object file for the translation unit where the definition of the first non-pure-virtual out-of-line virtual member function is present. if there is no such definition, you get this rather unhelpful linker error message.

you would be able to progressively compile the code even if a non-pure virtual function is not defined, but to be able to link without errors, every such function must have a definition (at least a stub). and to prevent the non-creation of a v-table by the compiler, at least one of the non-pure virtual functions will have to be defined out-of-line.

gcc has a faq about this: http://gcc.gnu.org/faq.html#vtables


> Am I to assume that the example in the book, as regards the inline feature
> of a derived class destructor, is in error.
i think it is not a particularly good book, but in this case neither the book nor the compiler is in error.

superjacent commented: To the point and relevant advice, thank you. +1
vijayan121 1,152 Posting Virtuoso

even if you do not have a store for all primes < 100 (you do need an array or vector for that), you can use the knowledge that even numbers greater than 2 are not prime. and cut the number of times through the loop by roughly half:

bool prime (int n)
  {
      if( n < 2 ) return false ; // all versions need this 
      if( n == 2 ) return true ;
      if( n%2 == 0 ) return false ;
      int root = sqrt( double(n) ) + 1 ;

      for ( int z = 3 ; z<= root; z += 2 )
          if( n%z == 0 ) return false;

      return true;
}
Moporho commented: Brilliant! +1
vijayan121 1,152 Posting Virtuoso

you are encountering the strange behaviour because of this function (ideally it should not have compiled at all):

bool validity_check(int level,int n, int current[])
{
        for(int i=0;i<level;i++)
        {
                if(current[i]==n) return false;
        }
        //Level 0 has always full validity.
        if((level>0)&&(level<order-1))
        {
                if((current[level-1]==n)|(current[level+1]==n)) return false;
        }
        if(level==order-1)
        {
                if(current[level-1]==n) return false;
        }
        // warning: control reaches end of non-void function
        //return true ; // add this and the strange behaviour will dissappear
}

at the place where the function is called,

while(true)
        {
                //cout<<"Entered the while loop"<<endl; //This is the line which can change the whole output when uncommented
                for(int i=nextjump[level];i<order;i++)
                {
                        if(validity_check(level,i,position))
                        // the contents of the eax register at this 
                        // point determines wheateher the result 
                        // is true or false
                        // since the function does not return a value
                        // what eax will be on return is influenced 
                        // the state of the registers before the call
                        // apparently, the cout << ... 
                        // causes eax to be non-zero on 
                        // exit from the function. 
                        // cout << ... returns a reference to cout (in eax)
                        // non-zero; the if condition evaluates to true
                        // without the cout << ... eax is zero 
                        // and the if condition evaluates to false.

                        {
                            // ...

moral of the story: compile with standard conformance and all warnings enabled. and pay attention to the warnings.
use something like: > g++ -Wall -std=c++98 -pedantic -Werror myprogram.cc (g++ is really bad if you just settle for the defaults.)

note: this …

agrawalashishku commented: Very Very helpful. I am grateful +2
vijayan121 1,152 Posting Virtuoso

were you looking for a standard library function?
like std::accumulate ( in header <numeric> )

// vec is a std::vector<int> and N <= vec.size()
int sum = std::accumulate( vec.begin(), vec.begin()+N, 0 ) ;
// average == sum / double(N)
VernonDozier commented: Useful function. +1
hammerhead commented: nice one +2
vijayan121 1,152 Posting Virtuoso

ok. here is what you need to do.
download the following files:
http://www.agentpp.com/snmp++v3.2.23.tar.gz
http://www.agentpp.com/libdes-l-4.01a.tar.gz
http://www.agentpp.com/msvc7.zip
extract all three into the same directory (say C:\snmp_files)
your diectory structure now should be

snmp_files
         |
-------------------
|         |       |    
libdes   msvc    snmp++

open C:\snmp_files\msvc\static\snmp++\snmp++.vcproj in visual c++ ide
the project will need conversion (if you are using vc++ 2005 0r 2008),
let the ide convert it.

either add C:\snmp_files\libdes to your include path or
in C:\snmp_files\snmp++\src\auth_priv.cpp modify line 59
from #include <des.h> to #include "..\libdes\des.h" rebuild all.

the static library snmp++.lib would be created in
C:\snmp_files\msvc\static\debug (debug build)
C:\snmp_files\msvc\static\release (release build).

build other libraries in a similar fashion.

lAmoebal commented: Very Helpful +1
vijayan121 1,152 Posting Virtuoso

it is impossible to say just by looking at the fragments you posted. this one seems interesting.
> since this following code runs flawlessly while moving the snake around, there must not be a dangling pointer.

else if (next) // Runs only if it is has a proceeding  and succeeding segment, meaning 3 or more
    {
        lastx = x;
        lasty = y;
        x = previous->lastx;
        y = previous->lasty;
        dir = previous->dir;
        next->move();
    }

are you absolutely certain that this will never be called after SnakeSeg::kill has been called? you would be able to move the snake around flawlessly (kill has not been called); but by the time you reach the destructor things might have got out of hand.

in any case, do yourself a favour:
except in the destructor where you are deleting a member, never write delete ptr ; without also writing ptr = 0 ; immediately after that.
better still: completely avoid using c-style pointers whenever possible . prefer things like std::vector<>, std::auto_ptr<>, std::string, std::tr1::shared_pointer<> etc.

Joatmon commented: Solved my problem, thanks for the help +1
vijayan121 1,152 Posting Virtuoso

yes. something like

int max_so_far = array[0] ;
for( int i=1 ; i<num_elements ; ++i )
{
  // if the element in question is greater than max_so_far, make 
  // max_so_far equal to that element
}
// max_so_far now contains the value of the largest element in the array
henpecked1 commented: V was very patient and very helpful +1
vijayan121 1,152 Posting Virtuoso

> I heard something that boost's preprocessor library can do that.
> didn't get to try it out : http://boost.org/libs/preprocessor/doc/ref/repeat.html.
BOOST_PP_REPEAT gives a fast horizontal repetition from 0 to N-1
since you need a repetition starting at 1, using BOOST_PP_REPEAT_FROM_TO would be easier.

#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <iostream>

#define DEFUN( z, N, arg ) int BOOST_PP_CAT( arg, N )() \
{ return N * N ; }

#define DEFINE_FUNC(N) \
BOOST_PP_REPEAT_FROM_TO( 1, N, DEFUN, square_of_ )

DEFINE_FUNC(15)
 
int main()
{
  std::cout << square_of_11() << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

The definition void main() { /* ... */ } is not and never has been C++, nor has it even been C. See the ISO C++ standard 3.6.1[2] or the ISO C standard 5.1.2.2.1. A conforming implementation accepts int main() { /* ... */ } and int main(int argc, char* argv[]) { /* ... */ } A conforming implementation may provide more versions of main(), but they must all have return type int.

The int returned by main() is a way for a program to return a value to "the system" that invokes it. On systems that doesn't provide such a facility the return value is ignored, but that doesn't make "void main()" legal C++ or legal C. Even if your compiler accepts "void main()" avoid it, or risk being considered ignorant by C and C++ programmers.

vijayan121 1,152 Posting Virtuoso

or use a union

int main()
{
   typedef unsigned char byte ;
   union
   {
     byte buffer[ sizeof(long) ] ;
     long key ;
   };
   // ...
}
SpS commented: Nice +4
vijayan121 1,152 Posting Virtuoso
Move Move::add( const Move &m ) const 
{
   return Move( x + m.x, y + m.y ) ;
}
superjacent commented: Concise, to the point, very helpful. +1
vijayan121 1,152 Posting Virtuoso
struct A
{
  A( int i ) throw(char,int,double) : value(i) {}
  int value ;
};

struct B : A
{
  B() throw(char,int,double) ;
};

B::B() throw(char,int,double) : A(20) {}
Nick Evan commented: Nice +3
vijayan121 1,152 Posting Virtuoso

change cout << os ; to cout << os.str() ;
os.str() gets the string from the stringstream.
cout << os ; is equivalent to cout << (const void*)os ; prints the pointer value.

vijayan121 1,152 Posting Virtuoso
Salem commented: good answer +15
vijayan121 1,152 Posting Virtuoso

check this library out. http://code.jellycan.com/simpleini/
i've not used it; but the reports that i've come across are good.
and the license is non-viral (MIT)

jaepi commented: uh huh! +2
vijayan121 1,152 Posting Virtuoso

you still use RegQueryValueEx.

LONG WINAPI RegQueryValueEx( HKEY hKey, LPCTSTR lpValueName, 
            LPDWORD lpReserved,
            LPDWORD lpType, // will be set to the type of data 
                  // (eg. REG_BINARY if value was binary) 
            LPBYTE lpData, LPDWORD lpcbData );

see http://msdn2.microsoft.com/en-us/library/ms724884.aspx for the registry value types.

Ramy Mahrous commented: well done +7
vijayan121 1,152 Posting Virtuoso

you could write a custom allocator that tracks calls to allocate and deallocate.

#include <map>

template< typename T > struct myallocator : public std::allocator<T>
{
  typedef std::allocator<T> base ;
  typedef typename base::size_type size_type;
  typedef typename base::difference_type  difference_type;
  typedef typename base::pointer pointer;
  typedef typename base::const_pointer const_pointer;
  typedef typename base::reference reference;
  typedef typename base::const_reference const_reference;
  typedef typename base::value_type value_type;
  myallocator() throw() {}
  myallocator( const myallocator& a ) throw() : base(a) {}
  template <typename X> myallocator(
             const myallocator<X>& ) throw() {}
  ~myallocator() throw() {}

  template <typename X> struct rebind
  { typedef myallocator<X> other; };

  pointer allocate( size_type sz, const void* hint = 0 )
  {
    // record alloc request eg. ++num_allocs ;
    return base::allocate(sz,hint) ;
  }
  void deallocate( pointer p, size_type n )
  {
    // record dealloc request eg. --num_allocs ;
    return base::deallocate(p,n) ;
  }
};

template<typename T> inline bool operator==(
               const myallocator<T>&, const myallocator<T>& )
{ return true; }

template<typename T> inline bool operator!=(
               const myallocator<T>&, const myallocator<T>& )
{ return false; }

int main()
{
  std::map< int, float, std::less<int>, 
                myallocator<int> > testmap;
  for ( int i = 0; i < 1000000; i++ )
  {
    testmap[i] = (float)i;
  }
  testmap.clear();
}
Rashakil Fol commented: n/a +6
vijayan121 1,152 Posting Virtuoso

mostUsed is a const. use a const_iterator. also a prefix increment instead of a postfix (efficiency)

for ( map<string,int>::const_iterator word = mostUsed.begin() ;
		word != mostUsed.end() ; ++word ) { /*...*/
FireSBurnsmuP commented: Impressive advise, Glad I got your help. +2
vijayan121 1,152 Posting Virtuoso

no. i really meant even without gcc 4.3
i would use something like a std::vector< boost::any >
or a std::list< boost::variant<int,double,std::string> >
both of which are typesafe. and i would get the same functionality.
i also would not write functions that took several dozens of arguments; so even the overloaded template technique would be quite adequate for my limited needs.

Ancient Dragon commented: great solution +20
vijayan121 1,152 Posting Virtuoso
ithelp commented: thanks. it help +2
vijayan121 1,152 Posting Virtuoso
template <class T, int SIZE>
class Graph 
{
  bool AddVertex(T Data) ; 
  // ...
};

template <class T, int SIZE>
bool Graph<T, SIZE>::AddVertex(T Data)
{
  // ...
}
Ratte commented: Very helpful. +1
vijayan121 1,152 Posting Virtuoso

> intl were using floatl floatl members were using intl how to solve this !
to declare the floatl members using intl, a declaration of intl would suffice.
to define them, a definition of intl is required.

so do things in this order:
a. declare the classes first.
b. define the classes (which have declarations of their members)
c. define the members.
for example:

//********* header b.h ***************
#ifndef _B_H_INCLUDED_
#define _B_H_INCLUDED_
struct A ;
// A has been declared; we can now declare (not yet define) functions using A
struct B
{
  inline int b_fun( const A& a ) ;
  int bm ;
  A* a ;
  friend inline int b_friend( B& b, const A& a ) ;
};
#endif // _B_H_INCLUDED_
//////////////////////////////////////////////////////////////////

//********* header a.h ***************
#ifndef _A_H_INCLUDED_
#define _A_H_INCLUDED_
struct B ;

struct A
{
  inline int a_fun( const B& b ) ;
  int am ;
  friend inline int a_friend( A& a, const B& b ) ;
};
#endif // _A_H_INCLUDED_
/////////////////////////////////////////////////////////////////////

//********* header anything_else.h ***************
#ifndef _ANYTHING_ELSE_H_INCLUDED_
#define _ANYTHING_ELSE_H_INCLUDED_

#include "a.h"
#include "b.h"
// A and B have been defined; we can now define functions using A and B

int A::a_fun( const B& b ) { return am += b.bm ; }
int B::b_fun( const A& a ) { return bm += a.am ; }
int a_friend( A& a, const B& b ) { return a.am += b.bm ; }
int b_friend( B& b, const A& a ) { …
tnvkrishna commented: it's done with some kind of patience .i judge him based upon his previous replys.there was knowledge and patience in every one of them +1
vijayan121 1,152 Posting Virtuoso

> when you say trampoline you mean this, right?
yes, except for the java and ojective-c usage of the term.

perhaps the use of trampolines that you would be most familiar with is that in a thread function. the compiler would compile the code for a thread function like any other function; you *can* safely call it like a normal function if you want. when a return is executed from a thread function (other than the one which executes main), an implicit call needs to be made to the system call (pthread_exit, ExitThread) which ends a thread with proper cleanup. this cleanup code would call cleanup/cancellation handlers, destroy any thread specific data, release the stack(s) etc. this is achieved by placing a trampoline on the thread stack (where the return address is expected).

another common example of trampoline use is in implementing tail recursion (eg. in languages of the lisp family). almost all the implementations of compilers/interpreters are in C. generating code for tail recursion in C (without growing the stack) is achieved by a number of trampoline bounces.

trampolines are also used to implement closures in C/C++. for example, in the (non-standard) implementation of nested functions in gcc. http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

posted by salem:

$ gcc -S -O2 foo.c && cat foo.s
_foo:
        pushl   %ebp
        movl    %esp, %ebp
        popl    %ebp
        ret
# The optimiser realises the results are never used, and the code is gone.

if we use the -fomit-frame-pointer switch, no frame …

vijayan121 1,152 Posting Virtuoso

> How can i see the assembly produced by the compiler{if it is possible}?
gcc: to generate assembly pseudo code, use the -S switch. eg. g++ -O2 -S -c whatever.cc to see the C code together with the assembly it was converted to: g++ -c -g -O2 -Wa,-a,-ad whatever.cc > whatever.asm microsoft: use one of /FA, /FAc, /FAs, /FAu compiler switches

> > From your experience where do you need to employ assembly while programming a real life project.
a. to implement something like the macros in <cstdarg> ( va_start, va_arg, va_end ) assembly may be required on some platforms.
b. defining things like sig_atomic_t, atomic_add etc. on some platforms.
c. to implement thunks and trampolines on some platforms.

n.aggel commented: helpful as always! +1
vijayan121 1,152 Posting Virtuoso

> while(fin) is running endlessly ..
in general, when reading an entire file, it is a good idea to embed the input statement inside the while loop's condition. this would eliminate a lot of subtle errors. and the loop will exit once eof is reached. eg.

#include <fstream>
int main()
{
  std::ifstream in( "in.txt" ) ;
  std::ofstream out( "out.txt" ) ;
  char ch ; 
  bool last_was_space = false ;
  while( in.get(ch ) )
  {
    if( ch != ' ' )
    {
      out.put(ch) ;
      last_was_space = false ;
    }
    else if( !last_was_space )
    {
       last_was_space = true ;
       out.put(ch) ;
    }
  }
}

note: this will remove extra spaces; but will not take care of tab characters.

vijayan121 1,152 Posting Virtuoso

(most) windows programs are written to run against an environment subsystem. the subsystem is specified in the PE header of the executable image and is placed there by the linker.
currently, your program is being linked with the linker switch /SUBSYSTEM:WINDOWS. this implies that your program does not require a console, probably because it creates its own windows for interaction with the user. if you do not specify an entry point for your executable (where the program should start executing) by using the /ENTRY linker switch, the linker inserts a suitable default. for /SUBSYSTEM:WINDOWS, this is WinMainCRTStartup (or wWinMainCRTStartup) which after initializing the C runtime library will call WinMain (or wWinMain).
since you are writing a console based program, you need to change the linker switch to /SUBSYSTEM:CONSOLE. this specifies that your program is a Win32 character-mode application and needs to be given given a console on startup. the defaul;t entry point would now be mainCRTStartup (or wmainCRTStartup) which after initializing the C runtime library will call main (or wmain).
to modify this linker option in the vc++8 ide: Project->Properties->Linker->System->Subsystem
for more information: http://msdn2.microsoft.com/en-us/library/fcc1zstk(vs.71).aspx
http://msdn2.microsoft.com/en-us/library/f9t8842e(VS.71).aspx
note: this is really not a c++ question, c++ only talks about main,

vijayan121 1,152 Posting Virtuoso
// ...
TwoD m1 ( d1 , d2 ) ;
// ...
cin >> m1 ( k , j ) ;
// ...

for this to work, the class TwoD should provide an overloaded function call operator that can take k and j as args. and would return a reference to the 2d array element at k,j as a modifiable l-value. eg.

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

class TwoD
{
  public:
        // ...
        TwoD ( int nrows, int ncols ) : d1(nrows), d2(ncols)
        {
          assert( d1>0 && d2>0 ) ;
          m = new int[ d1 * d2 ] ;
        }
        int operator() ( int i, int j ) const
        { assert( i<d1 && j<d2 ) ; return ( m + i*d2 )[j] ; }
        int& operator() ( int i, int j )
        {  assert( i<d1 && j<d2 ) ; return ( m + i*d2 )[j] ; }
        // ...
  private:
        int *m ;
        int d1 ;
        int d2 ;
};

using a function call operator to access array elements would not be intuitive to most c++ programmers; overloading the array subscript operator would make the use of TwoD easier. eg.

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

class TwoD
{
  public:
        // ... ;
        TwoD ( int nrows, int ncols ) : d1(nrows), d2(ncols)
        {
          assert( d1>0 && d2>0 ) ;
          m = new int[ d1 * d2 ] ;
        }
        struct row ;
        const row operator[] ( int i ) const
        { …
ndeniche commented: precise!!! :D +3
vijayan121 1,152 Posting Virtuoso

>> what function which is similar to stat that asks for a FILE* fildes rather than int fildes?
the function [B]int fileno(FILE *stream);[/B] is part of both posix and single unix specifications. http://www.opengroup.org/onlinepubs/009695399/functions/fileno.html
this would give the file descriptor using which you can call fstat() which also conforms to posix.

jaepi commented: Exactly what I need. +2
vijayan121 1,152 Posting Virtuoso

perhaps this would clarify (not different, but the types involved are simpler and therefore the example is easier to follow).

void foobar( int a, int b ) {}

int main()
{
  int a = 78 ;
  int foo( int(a) ) ; // is this the declaration (of a function foo)
                      // or the definition of an int foo?
  int(*pfn)(int) = &foo ; // it is a declaration!

  int bar( (int(a)) ) ; // can't be the declaration (of a function bar)
  int* pi = &bar ; // so, must be the definition of an int bar
  // reason (int(a)) is an expression because of parantheses; 

  // for example
  foobar( a, bar ) ; // ok
  // foobar( (a, bar) ) ; // error, too few arguments to function foobar
                       // because (a,bar) is *a single* expression
}

int foo( int(a) )
{
  return a+6 ;
}

there are several threads in comp.std.c++ which discuss why the language rules are framed this way, what would have been the alternatives etc. here is one of them http://groups.google.com/group/comp.std.c++/browse_thread/thread/57b52b0a1a40a9ad

n.aggel commented: thanks for the example +1
vijayan121 1,152 Posting Virtuoso
template< typename T >
class A
{
  // ...
    template< typename SEARCH, typename STAT >
      inline void search_s( SEARCH srch, STAT stat )
      {
        // implement here (inline)
        // some compilers complain otherwise.
        // can use the argument srch and stat here
        // ...
      }
  // ...
};
Dave Sinkula commented: I have been lax on giving you the reputation points have deserve. +11
vijayan121 1,152 Posting Virtuoso

a. if second is not an object oriented type, using value semantics would be simpler:

#include "second.h"
class first
{
    private:
        second mySecond;
};

b. if pointer semantics are required, you would have to decide: is the pointer an *owning* pointer? if is is, what would happen if an object of type first is copied? one option is to disable copy and assignment.

#include "second.h"
class first
{
    public:
        first() : mySecond( new second ) {}
        ~first() { delete mySecond ; }
    private:
        second *mySecond;
        // disable copy and assignment; do not define these!
        first( const first& ) ;
        void operator= ( const first& ) ;
};

another would be to use the semantics of transfer of ownership on copy or assignment

#include "second.h"
 class first
 {
    public:
        first() : mySecond( new second ) {}
    private:
        std::auto_ptr<second> mySecond;
};

in c++0x, you could also implement shared ownership easily. (in c++98, you could use boost::shared_ptr<>for this)

#include "second.h"
class first
{
    public:
        first() : mySecond( new second ) {}
    private:
        std::shared_ptr<second> mySecond; // c++0x
};
vijayan121 1,152 Posting Virtuoso
// ...
// ...
///using the extern to modify the linkage
// *** correct
extern const char this_is_ok[] = "no_error" ;

int this_too_is_ok = 100 ;    ///it is ok because it is an integral value correct?
// *** not correct
///it doesn't have anything to do with the linkage, correct?
// *** not correct
// *** the default linkage for modifiable values is external.
// *** this_too_is_ok cannot be used as a template parameter; 
// ***                    it is not a constant known at compile time.
// *** &this_too_is_ok can be used as a template parameter; 
// ***       it is the address of an object with external linkage.
// *** compare with:
// *** const int NUM = 7 ; // constants have internal linkage by default.
// *** NUM can be used as a template parameter; constant known at compile time
// *** &NUM cannot be used as a template parameter; NUM has internal linkage
// *** extern const int VAL = 78 ; // force external linkage on VAL.
// *** VAL can be used as a template parameter; constant known at compile time
// *** &VAL can also be used as a template parameter; VAL has external linkage


template< typename T, int N > void function( T (&a)[N] ) {} ///This notation is for passing be reference the pointer to the array?
// *** in T(&a)[N] 'a' is a reference to the array
// *** typedef T(*ptr_array_type)[N] ; // type 'ptr_array_type' is a pointer to the array …
n.aggel commented: thanks for helping! +1
vijayan121 1,152 Posting Virtuoso

>> ... in the end LD equals g++, right?...
usually yes, for C++ programmers. g++ invokes ld (unless invoked with the -c switch). but this may not always be what you require. for example, you may want to use g++ to compile your code on a solaris machine, but want to link with the native solaris (unix) ld instead of the gnu ld. defining LD seperately would aid portability. also, if the linker is invoked via a compiler-driver, passing switches to the linker is somewhat awkward: eg. g++ -std=c++98 -Wall -Wl, --print-map -Wl, --cref foo.cc bar.cc >> the makefile above doesn't work.... i get this error...
the makefile is written with the assumption that source files have a .c suffix. the source files you use have a .cpp suffix. the substitution (.c to .h) is failing.

>> i can't fix it because, i don't understand .. automatic variables
play around with the following toy makefile; that should give you a basic understanding of using variables in makefiles.

PROGRAM := zoo

SOURCE_SUFFIX ?= .cpp
HEADER_SUFFIX ?= .h
OBJECT_SUFFIX := .o
PRECOMPILED_SUFFIX := $(HEADER_SUFFIX).gch

ANIMALS = puma tiger meercat zebra
MAIN := main
ANIMAL_SOURCES = $(foreach ANIMAL,$(ANIMALS),$(ANIMAL)$(SOURCE_SUFFIX))
SOURCES = $(ANIMAL_SOURCES) $(MAIN)$(SOURCE_SUFFIX)
HEADERS = $(ANIMAL_SOURCES:$(SOURCE_SUFFIX)=$(HEADER_SUFFIX))
ANIMAL_OBJECTS = $(ANIMAL_SOURCES:$(SOURCE_SUFFIX)=$(OBJECT_SUFFIX))
OBJECTS = $(SOURCES:$(SOURCE_SUFFIX)=$(OBJECT_SUFFIX))
PRECOMPILED = $(HEADERS:$(HEADER_SUFFIX)=$(PRECOMPILED_SUFFIX))

CC = g++
PROCESSOR ?= pentium4
OPTIMIZE ?= -O3
override CFLAGS += -Wall -std=c++98 $(OPTIMIZE) -march=$(PROCESSOR)

the_target : one two three four three two
    @echo
    @echo automatic variables
    @echo -------------------
    @echo rule  \'$@ : …
vijayan121 1,152 Posting Virtuoso

ok. did a few more investigations. the memory allocation for the vector and that of boost::pool<> appear to interract unfavourably with each other, resulting in heap fragmentation. to avoid this, the following change was also made in main.cpp (in addition to the earlier change: call destructor/constructor sequence of node_pool to deallocate all memory).

//For vector randomization
vector<int> vec ;
vec.reserve(HOW_MANY_ELEMENTS) ;
generate_n( back_inserter(vec), size_t(HOW_MANY_ELEMENTS), generator ) ;

changed to

static vector<int> vec(HOW_MANY_ELEMENTS) ;
generate_n( vec.begin(), size_t(HOW_MANY_ELEMENTS), generator ) ;

and the problems disappeared. i ran it with 1 million elements for 128 iterations. as would be expected, the performance improved marginally (because of better cache locality) after the first few iterations and then remained steady. here is an extract of the results. complete results are in the attached tar.bz2 file.

>g++ -std=c++98 -Wall -I/usr/local/include -O3 -funroll-loops -march=pentium4 main.cpp LeftistHeap.cpp && ./a.out

#############################################
Start of Data-Structure Testing
Priority Queue
# elements: 1000000
#############################################
Initialize 0... end of init 0 time taken: 101.562 ms
Initialize 1... end of init 1 time taken: 101.562 ms
Initialize 2... end of init 2 time taken: 101.562 ms
Initialize 3... end of init 3 time taken: 93.750 ms
Initialize 4... end of init 4 time taken: 93.750 ms
Initialize 5... end of init 5 time taken: 93.750 ms
Initialize 6... end of init 6 time taken: 85.937 ms
Initialize 7... end of init 7 time taken: 93.750 ms
Initialize 8... end of init 8 time taken: 93.750 ms
Initialize 9... end of init …
n.aggel commented: just wow...he solved it again...:) +1
vijayan121 1,152 Posting Virtuoso

using libcurl would be a portable way. http://curl.haxx.se/libcurl
source or binaries for a number of platforms are available http://curl.haxx.se/download.html

libcurl can be used directly from c++. curlpp gives a c++ wrapper that uses stl, is exception and type safe; so you may want to use it.
http://rrette.com/textpattern/index.php?s=cURLpp
http://rrette.com/textpattern/index.php?s=file_download&id=35

you could also use curl from the command line.
to retriev a number of web pages (eg. to mirror a complete website), use wget
http://www.gnu.org/software/wget/
for windows: http://www.christopherlewis.com/WGet/WGetFiles.htm

n.aggel commented: nice post!{i didn't know about libcurl} +1
vijayan121 1,152 Posting Virtuoso

>> How are an object’s data members initialized if a class has only an implicitly defined default constructor?
if every non-static member variable of a class has default initialization and no programmer defined constructor is specified, a default constructor is deemed to be declared.

if the initialization of all the non-static member variables are trivial, then the default constructor is also trivial and will not be synthesized by the implementation. for example,

struct A 
{ 
   int i ; 
   double d ; 
   char* ptr ; 
} ;

a default constructor is deemed to be declared, but no constructor is defined and no initialization is performed.

if there are non-static member variables with non-trivial default initialization, then a default constructor is synthesized by the implementation. for example,

struct B 
{ 
   std::string str ; 
   std::vector<int> container ; 
   int i ; 
};

a default constructor is defined by the implementation. the synthesized default constructor will initialize the members str and container by calling their default constructors, for member i, no initialization is performed.

for

struct C
{ 
   const int i ; 
   double d ; 
   char* ptr ; 
} ;

no default constructor is deemed to be declared. (member i has no default initialization.)

note: a. whatever was said of non-static member variables also applies to non-virtual base classes.
b. for classes with virtual functions and/or virtual base classes, the hidden vtable pointer and vbase pointer members have non-trivial initialization.
c. the non-programmer defined default …

Ancient Dragon commented: good compilete answer +18
vijayan121 1,152 Posting Virtuoso

>> Why the calls to new/delete harm the performance more than using by value passing?
this copy constructor does nothing more than the trivial bitwise copy that the compiler would have generated.

LeftistHeap::LeftistHeap(const LeftistHeap & rhs )
{
            root = NULL;
            *this = rhs;
}

as you have not declared an operator=, *this = rhs does a trivial bitwise assignment. (you can safely comment this constructor out; the inline bitwise copy that the compiler would generate would be faster than your out-of-line implementation and will do the same thing.) the same observation also holds for the do nothing destructor that you have.
since you are not using deep copy semantics, copying a LeftistHeap copies a pointer and an integer; destroying it would do nothing at all. new LeftistHeap on the other hand requires a call to operator new to allocate dynamic memory and delete LeftistHeap a call to operator delete to release the memory. these would typically require several dozen instructions to be executed. and you are doing this a very large number (several millions) of times.

>> ...so if i pop one, it will also be deleted so how can i ...
create a temporary copy (we have seen that this is inexpensive). and to avoid even this, try to use the object before popping it if possible. eg.

// note: added const to the input parameter to make it const-correct.
void LeftistHeap::initializeHeap( const std::vector<int>& vec )
{
      queue<LeftistHeap> q;
      for( int i=0; …
n.aggel commented: very helpfull post! +1
vijayan121 1,152 Posting Virtuoso

fixed a couple of bugs (brute force version).

#include <iostream>
#include <cmath>
#include <cassert>
#include <iomanip>
using namespace std;

void print_with_comma( double value )
{
  assert( value >= 0.0 ) ;
  double intp ;
  double fracp = modf( value, & intp ) ;
  if( fracp >= 0.995 ) { fracp = 0.0 ; intp += 1.0 ; }
  int before_decimal = int( intp + 0.5 ) ;
  int millions = before_decimal / 1000000 ;
  int thousands = ( before_decimal / 1000 ) % 1000 ;
  int units = before_decimal % 1000 ;
  bool started = millions > 0 ;
  if(started) cout << millions << ',' ;
  if( started || thousands>0  )
  {
    cout << setw( started ? 3 : 0 ) << setfill('0') << thousands << ',' ;
    started = true ;
  }
  cout << setw( started ? 3 : 0 ) << setfill('0') << units << '.' ;
  cout << setw(2) << setfill('0') << int( fracp*100 + 0.5 ) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

c provides escape sequences '\n' and '\r'. contrary to popular belief, these are not required to be equivalent to specific control characters. the c standard guarantees that 1. each of these escape sequences maps to a unique implementation-defined number that can be stored in a single char. 2. when writing a file in text mode, '\n' is transparently translated to the native newline sequence on the the system (which may be longer than one character). when reading in text mode, the native newline sequence is translated back to '\n'. (in binary i/o mode, no such translation is performed.) c++ also provides L'\n' and L'\r'; these are the wchar_t equivalents.

so, looking for '\n' is correct if the char_type of the stream is a char. to also handle other char_types (eg. wchar_t), basic_ios<char_type,traits_types>::widen('\n') could be used.

Salem commented: Good answer regarding character translations. +9
vijayan121 1,152 Posting Virtuoso

using boost.assign http://www.boost.org/libs/assign/doc/index.html is the easiest way to fill containers; and it also works with containers other than vector<>.

#include <vector>
#include <list>
#include <map>
#include <string>
#include <boost/assign.hpp>
using namespace std;
using namespace boost::assign;

int main()
{
  vector<string> strings = list_of("abcd")("efg").repeat(5,"hi")("jkl") ;
  // "abcd" "efg" "hi" "hi" "hi" "hi" "hi" "jkl"
  strings += "mnop", "qrs", "tuvwx", "yz" ;
  // "abcd" "efg" "hi" "hi" "hi" "hi" "hi" "jkl" "mnop" "qrs" "tuvwx" "yz"
  
  list<int> numbers = list_of(100).repeat(7,22)(75)(80)(85)(90)(83) ;
  numbers += 555, 666, 1, 2, 3, repeat(4,99), 56, 75, 80 ;
  
  map<string,int> pbook = map_list_of("abcd",100)("efg",75)("hi",83) ;
  insert(pbook)("mnop",555)("qrs",4)("tuvwx",999)("yz",56) ;
}

where is narue? even if daniweb does not miss her, the c++ forum does.

vijayan121 1,152 Posting Virtuoso

>> but why? i thaught that with this line the queue queue<LeftistHeap *> q; would be made responsible for desposing the elements....

the queue owns pointers to LeftistHeaps, not the LeftistHeaps themselves. so it would release what it owns, ie. the pointer, not the pointed object. the behaviour would have been different for a queue<LeftistHeap>.

>> why the size of leftistheap is just sizeof(pointer) + sizeof(int)??I also have three pointers in the leftistheap class...

the size of an object would include the size of its non-static member variables ( + a vptr if there are virtual functions + one vbaseptr for each virtual base class + any padding; however for yourLeftistHeap none of these apply). the only non-static member variables of a LeftistHeap are myNode *root; int emptyFlag; >> here is what i did... if the queue isn't responsible then i am, so i did something like this:
>> .....
>> doesn't work afterwards...as i would expect...
>> how can i deallocate something that i a not in control, because when i push the pointer in the queue i lose all control on that memory....

the queue will safely keep (a copy of) anything that you push into it. and give it back to you on demand.
do something like this instead.

void LeftistHeap::initializeHeap(std::vector<int> & vec)
{
   //prey to work!!!     
   queue<LeftistHeap *> q;


   for(int i=0; i<vec.size(); ++i)
   {
         q.push(new LeftistHeap(vec[i]) );
   }

   LeftistHeap *temp;

   while ( q.size()!=1)
     {
           temp = q.front(); …
n.aggel commented: great helper! +1
vijayan121 1,152 Posting Virtuoso

>> ...I don't think I'm smart enough to understand template metaprogramming....

it is not as difficult as you make it out to be. strange? yes, initially. hard to understand? not really. a lisper would feel quite at home with this kind of programming. and it would look somewhat eerie to someone with only a c (read classical c++, C#, java) background

>> ...made me wonder if it was practical. All of the examples that look useful to me are too complicated to understand. All of the examples I can grok are kind of pointless

ok, let us try again. here is a useful example. we want to write a (generic, meta) function which copies one sequence to another like std::copy. however, if the source and destination sequences are c-style arrays which can be correctly copied using a memcpy, we want to call memcpy. otherwise, we would iterate and copy element by element. compilers (icc, vc++ 7 or later, gcc 4.1 or later) recognize a call to memcpy and can generate mmx/sse instructions for a fast block copy; we do not want to lose this advantage. but we do not want to break our code if the implementation of the sequence we are copying is modified at some time in the future. we just recompile, safe in the knowledge that our metaprogram will generate either a call to memcpy or do an element by element copy depending on what we are copying.
the code is fairly elaborately …

vijayan121 1,152 Posting Virtuoso

>> looks cool, but is it really practical?

you have already seen one practical use for it; perhaps you have forgotten about it. see thread http://www.daniweb.com/forums/thread82213.html posts #7 and #10 where a trivial metafunction (rebind) was used to solve a genuine programming problem.

though the idea of using c++ as a metalanguage is faily old (see http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html - originally published in1994) and there has been high excitement among C++ experts about these capabilities of the language, it is true enough that it has not reached the c++ community at large.

here are some references to help you get started
http://safari.oreilly.com/0201704315
http://safari.oreilly.com/0321227255
http://en.wikipedia.org/wiki/Loki_(C++)
http://en.wikipedia.org/wiki/Boost_C++_Libraries
http://www.oonumerics.org/blitz/whatis.html
and something that (astonishingly; this certainly is not comp.lang.c++.moderated) turned up in daniweb yesterday): http://www.daniweb.com/forums/thread88328.html

vijayan121 1,152 Posting Virtuoso

there seems to be nothing much happening in the c++ forum today. so here is something to chew on for programmers who are relatively new to templates: c++ can also be used as a metalanguage.

#include <iostream>
using namespace std ;

// compile-time computation of fibonacci numbers
template < int N > struct fibonacci
{
   char error_negetive_N[ N + 1 ] ; // c++0x => use static_assert
   enum { value = fibonacci<N-1>::value + fibonacci<N-2>::value } ;
   char error_integer_overflow[ value ] ; // c++0x => use static_assert
};
template<> struct fibonacci<0> { enum { value = 0 } ; } ;
template<> struct fibonacci<1> { enum { value = 1 } ; } ;

// compile-time if statement
template<bool> struct _if { static inline void new_line() {} };
template<> struct _if<true> 
{ static inline void new_line() { cout << '\n' ; } };

// compile-time for loop
template< int N, int MAX, size_t N_PER_LINE > struct _for
{
  static inline void print_fibonacci_number()
  {
      cout << fibonacci<N>::value << '\t' ;
      _if< N%N_PER_LINE == (N_PER_LINE-1) >::new_line() ;
      _for< N+1, MAX, N_PER_LINE >::print_fibonacci_number() ;
  }
};
template< int MAX, size_t N_PER_LINE > struct _for<MAX,MAX,N_PER_LINE>
{
   static inline void print_fibonacci_number()
   { _if< MAX%N_PER_LINE >::new_line() ; }
} ;

int main()
{
   enum { FROM = 0, TILL = 32, LINE_SZ = 8 } ;
   _for< FROM, TILL, LINE_SZ >::print_fibonacci_number() ;
}
// to see generated assembly along with c++ source code (gcc):
// c++ -c -g -Wa,-a,-ad -Wall -std=c++98 -O3 fib.cpp > fib.asm
/** …
josolanes commented: great thread idea...working through it now to get a better understanding of TMP now +1
vijayan121 1,152 Posting Virtuoso

and here are some books.
1. Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (Addison-Wesley Professional)
2. Design Patterns Explained: A New Perspective on Object-Oriented Design (2nd Edition) by Alan Shalloway, James Trott (Addison-Wesley Professional)
3. Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts (Addison-Wesley Professional )
4. Head First Design Patterns by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra (O'Reilly Media)
5. Refactoring to Patterns by Joshua Kerievsky (Addison-Wesley Professional )
6. Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu (Addison-Wesley Professional )
7. Pattern-Oriented Software Architecture, Volume 1: A System of Patterns by Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, Michael Stal (John Wiley & Sons)
8. Pattern-Oriented Software Architecture, Volume 2, Patterns for Concurrent and Networked Objects by Douglas Schmidt, Michael Stal, Hans Rohnert, Frank Buschmann (John Wiley & Sons)
9. Pattern-Oriented Software Architecture, Volume 3, Patterns for Resource Management by Michael Kircher, Prashant Jain (John Wiley & Sons)
10. Pattern-Oriented Analysis and Design: Composing Patterns to Design Software Systems by Sherif M. Yacoub, Hany H. Ammar (Addison-Wesley Professional)

Dave Sinkula commented: Nice list. +11
vijayan121 1,152 Posting Virtuoso

you would be better off using icc for processor-specific optimizations. even without processor-specific optimizations, icc generates better optimized code than vc++ 8; and it blows gcc away. http://www.intel.com/cd/software/products/asmo-na/eng/276615.htm

SpS commented: Right suggestion +4
vijayan121 1,152 Posting Virtuoso

>> ...my mind still hasn't grasped how this number system works, is there some place I can read about it...
http://en.wikipedia.org/wiki/Signed_number_representations
http://en.wikipedia.org/wiki/Two%27s_complement

the c++ standard library header <limits> has a class template numeric_limits<> with specializations for each builtin numeric type. for integral types, the interesting members of std::numeric_limits<> are:

static const bool is_specialized; // will be true for integers
   static T min() throw(); // minimum value
   static T max() throw(); // maximum value
   static const int radix ; // the base of the representation; almost always 2
   static const int digits; // for integers, # value bits
   static const int digits10; // max number of decimal digits
   static const bool is_signed; //
   static const bool is_integer; // will be true for integers

for most uses, these are sufficient. here is an example of using numeric_limits<>.

#include <limits>
#include <iostream>
#include <bitset>
#include <cassert>
using namespace std ;

template< typename NUMERIC_TYPE > void show_info( NUMERIC_TYPE n )
{
   typedef numeric_limits<NUMERIC_TYPE> limits_type ;
   const int radix = limits_type::radix ;
   assert( radix == 2 ) ; // two's complement
   const int digits = limits_type::digits ;
   const int nbits = limits_type::is_signed ? digits+1 : digits ;
   cout << "radix: " << radix << "  digits: " << digits
        << "  nbits: " << nbits << '\n' ;
   NUMERIC_TYPE min_v = limits_type::min() ;
   NUMERIC_TYPE max_v = limits_type::max() ;
   cout << hex << showbase << "min value: " << min_v
        << "  max value: " << max_v << " …
SpS commented: Helpful +4