vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

see: http://www.daniweb.com/forums/thread85114.html
note: cout << "size of file: " << sizeof(parent) << endl; //size of the parent.txt file, for test purpose will not give you the size of the file on disk; sizeof(parent) gives you the amount of memory that the variable parent takes ( as a multiple of sizeof(char) )

vijayan121 1,152 Posting Virtuoso

you do not have to close and then reopen the file; inData.clear() ; inData.seekg(0) ; is more efficient.
> I need the number of lines before I can correctly do the other stuff.
you do not; use a vector instead of a c-style array:

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

int main()
{
   ifstream file( __FILE__ ) ;
   string line ;
   vector<string> lines ;
   while( getline( file, line ) ) lines.push_back( line ) ;
   cout << "#lines: " << lines.size() << '\n' ;
}
SpS commented: Good ~SpS +3
vijayan121 1,152 Posting Virtuoso

...compile and run the program on a more current compiler

runs without any problems on microsoft vc++ 8.0 and gcc 3.4.x (need to change headers iostream.h => iostream etc.)

Also I would value advice on which replacement compiler I should acquire. I would want an IDE and the machine computer interface board and real time limits me to using dos.

if you have to run under dos, this is reported to be a workable solution: http://www.delorie.com/djgpp/doc/ug/intro/what-is-djgpp.html & http://www.delorie.com/djgpp/v2faq/ it supports 32 bit addressing; so array sizes are not an issue if you have sufficient ram. see: http://www.delorie.com/djgpp/doc/ug/basics/32bit.html there is an ide for gjgpp: ttp://www.rhide.com/ djgpp is particularly popular among game programmers.

note: Salem's idea (sending a large array in smaller chunks of <64k) would be a simple and elegant solution; you should not rule it out without investigating the possibility.

Salem commented: Good idea - DJGPP +9
vijayan121 1,152 Posting Virtuoso

...why it's wrong to write a main function that doesn't return a value(void mainer's are doomed...) ? And if I make it return a value,where does that value arrive?

see: http://www.research.att.com/~bs/bs_faq2.html#void-main
also have a look at: http://www.research.att.com/~bs/bs_faq2.html#int-to-string
http://www.research.att.com/~bs/new_learning.pdf

vijayan121 1,152 Posting Virtuoso

...I would be interested if you have successfully run the program with the pointer declared as huge...

no, i have not run the program. what i posted was based on (somewhat foggy) memory of the days when intel tortured programmers with segented addressing and memory models. i do not have the compiler; so i cannot test it.

the following suggestions are also based on guesswork:
a. verify that you are using a library which returns *huge* pointers for things like operator new / malloc. perhaps, the compiler ships with different libraries; one for each memory model. one way to check this is verify that for the huge pointer you try to use (of the form segment:offset) segment is non-zero and not equal to youir DS
b. try an malloc/free instead of a new/delete.
c. try using an array (declared as huge) with a static storage duration.

do you really have to use this compiler? (the real question is: do you really have to execute your code under the segmented addressing mode of intel?)

vijayan121 1,152 Posting Virtuoso
printf((char *)&num);

is clearly an error; you are casting a double* to a char* (which is incorrect). unpleasant consequences would be the norm if you do such things. in C, to print out a double value, use

printf( "%f", num ) ;

instead.
atof is to be shunned; it has many problems. you would be much better off (and less likely to make errors) if you use C++ facilities where they are available. eg.

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

/*void*/ int main()
{
  double num = 310.589 ;
  /* char buffer [10]; */ string buffer ;
  /* sprintf(buffer,"%f",num); */ 
 { ostringstream stm ; stm << num ; buffer = stm.str() ; }
  // buffer[7] = *NULL;
  /*
  printf("using &num=\n");
  printf((char *)&num);
  printf("\nbuffer=\n");
  printf(buffer);
  printf("\nfragment of buffer=\n");
  printf((char *)&buffer[3]);
  */
  cout << "using &num= " << &num << "\nbuffer= " << buffer
       <<  "\nfragment of buffer= " << &( buffer.c_str()[3] ) << '\n' ;
  /* scanf("%s",buffer); */ cin >> buffer ;
  /* num=atof(buffer); */
  {
    istringstream stm(buffer) ;
    stm >> num ;
    if( !stm ) cerr << "conversion failed\n" ;
  }
  num/=2;
  /* printf("\n%lf",num); */ cout << num << '\n' ;
  /* _getch(); */ char ch ; cin >> ch ;
}

if you are preparing yourself for c++0x (you really should; final draft should be out in a few months), you could write

#include <string>
#include <iostream>
#include <sstream>
#include <boost/lexical_cast.hpp>
using namespace std ;
using namespace boost ;

int …
Salem commented: Good stuff +9
vijayan121 1,152 Posting Virtuoso

using far pointers you are still limited by 64K memory regions; its just that, that region can be outside your current CS or DS, and you can have many such regions. pointer arithmetic on far pointers do not modify the segment portion of the pointer, only its offset (modulo 64K arithmetic).

huge pointers are normalized every time they are modified; pointer arithmetic is *very* slow, but arrays of size >64k can be safely accessed. changing line 18 to

char huge* I ;

should work.

vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <string>
using namespace std ;

int main()
{
  string str ;
  getline( cin, str ) ;
  cout << str << '\n' ;
  
  cout << oct << showbase ;
  for( size_t i=0 ; i<str.size() ; ++i ) cout << int( str[i] ) << ' ' ;
  cout << '\n' ;

  cout << hex << showbase ;
  for( size_t i=0 ; i<str.size() ; ++i ) cout << int( str[i] ) << ' ' ;
  cout << '\n' ;
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

n.aggel> where can i find: mt19937
the one i have used is from the boost libraries. http://www.boost.org/index.htm

n.aggel> ... can a profiler help me? If yes, can you suggest me an easy-to-learn one....
n.aggel> .. is it possible to see how much space is consumed? ...
Salem>> Which OS / Compiler / type of machine?
if you had given that information, Salem would have given you an answer.

vijayan121 1,152 Posting Virtuoso

the time taken to call clock() would be much lower than the resolution of the clock provided by the library.

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

int main()
{
  const double res = 1000.0 / CLOCKS_PER_SEC ;
  cout << "resolution of libc clock: " << res << " millisecs\n" ;
  int ncalls = 0 ;
  enum { NTESTS = 1024 } ;
  for( int i=0 ; i<NTESTS ; ++i )
  {
    clock_t t1 = clock(), t2 = t1+1 ;
    while( clock() == t1 ) ;
    while( clock() == t2 ) ++ncalls ;
  }
  cout << "time taken to call clock: " << NTESTS * res / ncalls << " millisecs\n" ;
}
/*
>g++ -O3 -march=pentium4 -Wall -std=c++98 clock_time.cpp && ./a.out
resolution of libc clock: 7.8125 millisecs
time taken to call clock: 0.00506795 millisecs
*/

since the clock ticks are at discrete intervals, there can be an error of upto one clock tick in a single measurement. for example,
|--------|S+++++++|++++++++|++++++++|++++++++|++++++++|+++++++E|--------|--------| 5 ticks
|--------|-------S|++++++++|++++++++|++++++++|++++++++|++++++++|+++++E--|--------| 6 ticks
we can clearly make this out in the difference between the min and max times posted earlier. to minimize the statistical expectation of error
a. the time measured should be an order of magnitude higher than the resolution of the clock.
b. run the test several times; the average should then give a better indication
the time taken to call clock one or two times would be negigible in comparison.

if you are attempting to …

vijayan121 1,152 Posting Virtuoso
#include <algorithm>
#include <vector>
#include <iostream>
#include <ctime>
#include <iterator>
#include <boost/random.hpp>
#include <limits>
using namespace std ;
using namespace boost ;

inline double elapsed_msecs( clock_t start, clock_t end )
{ return double( end - start ) * 1000.0 / CLOCKS_PER_SEC ; }

int main()
{
  // choose a reasonably good random number generator
  // and a distribution that mirrors the intended use of the heap
  mt19937 engine ; // mersene twister; fast with acceptable quality.
  uniform_int<> distribution( 1, 1024*1024 ) ; // just as an example
  variate_generator< mt19937&, uniform_int<> > 
                                   generator( engine, distribution ) ;

  // measure performance for a your implementation and 
  // a reference implementation. this example measures 
  // performance of the reference implementation in libstdc++
  // for two operations: make_heap O(N) and sort_heap O(N log N)
  enum { HEAP_SIZE = 2*1024*1024, ITERATIONS = 32 };
  double make_heap_total = 0.0 ;
  double make_heap_min = numeric_limits<double>::max() ;
  double make_heap_max = 0.0 ;
  double sort_heap_total = 0.0 ; 
  double sort_heap_min = numeric_limits<double>::max() ;
  double sort_heap_max = 0.0 ;

  // run the test several times
  for( int i=0 ; i<ITERATIONS ; ++i )
  {
    vector<int> vec ; vec.reserve(HEAP_SIZE) ;
    generate_n( back_inserter(vec), size_t(HEAP_SIZE), generator ) ;
    
    clock_t start = clock() ;
    make_heap( vec.begin(), vec.end() ) ;
    clock_t end = clock() ;
    double duration = elapsed_msecs( start, end ) ;
    make_heap_total += duration ;
    make_heap_min = min( make_heap_min, duration ) ;
    make_heap_max = max( make_heap_max, duration ) ;
    
    start = clock() ;
    sort_heap( vec.begin(), vec.end() ) ;
    end = clock() ; …
vijayan121 1,152 Posting Virtuoso

...I thought of doing like,
1. get the file size
2. create a char* and allocate the size of file size
3. copying the entire file into a string buffer using Readfile() API...
but I think this is not ideal, so is there any other way to do it better..

unless you have a very special reason (eg. the file size is larger than what is supported by the implementation of libstdc++ that you have), you should use the standard c++ library.
if you do have to use the win32 api, mapping a section object into the virtual address space of the process would be much more efficient (for large files).
for your simple requirement, the win32 CopyFile function would suffice.

#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cassert>
#include <windows.h>
using namespace std ;

int main()
{

  // portable C++ - copy text file to stdout
  {
    ifstream file( __FILE__ ) ; 
    assert(file) ;
    file >> noskipws ;
    istream_iterator<char> begin(file), end ;
    copy( begin, end, ostream_iterator<char>(cout) ) ;
  }

  // win32 api  - copy text file to stdout
  {
    HANDLE file = CreateFileA( __FILE__, FILE_READ_DATA, 0, 0,
                           OPEN_EXISTING, 0, 0 ) ;
    assert( file != HANDLE(-1) ) ;
    HANDLE map = CreateFileMapping( file, 0, PAGE_READONLY, 0, 0, 0 );
    const char* cstr = static_cast<const char*>( 
                         MapViewOfFile( map, FILE_MAP_READ, 0, 0, 0 ) ) ;
    DWORD nb = 0 ;
    WriteFile( GetStdHandle(STD_OUTPUT_HANDLE), cstr, strlen(cstr), &nb, 0 );
    UnmapViewOfFile(cstr) ;
    CloseHandle(map) ; …
vijayan121 1,152 Posting Virtuoso

the xor swap algorithm fails if you try to swap a variable with itself.
other swap algorithms using arithmetic operators fail if overflow or underflow occurs.
the correct way to swap two variables a and b of any type is std::swap(a,b). we would expect std::swap to be correct and to have the most efficient implementation possible for that type.
to me, std::swap is the coolest of the lot.

vijayan121 1,152 Posting Virtuoso

dynamic scoping is almost never used these days. with dynamic scoping, a variable reference is bound to the most recent instance of that variable on the call stack. for example:

#ifdef this_should_not_compile
void b() ; void c() ;
void a()
{
  int x = 24 ;
  int y = 32 ;
  int z = 0 ;
  b() ;
  assert( z == 132 ) ;
}

void b()
{
  int x = 100 ;
  c() ;
}

void c()
{
   z = x + y ; // would mean a()::z = b()::x + a()::y   
}

#endif // this_should_not_compile

// most C/C++ implementations use "context parameters" to simulate this
// for example, these are some Xlib functions:
//  
// int XDrawLine( Display* display, Drawable d, GC gc,
//                int x1, int y1, int x2, int y2 ) ;
// int XDrawArc( Display* display, Drawable d, GC gc,
//               unsigned int width, unsigned int height,
//               int angle1, int angle2 ) ;
//
// the parameters Display*, Drawable ang GC are the "context parameters"
// 
// with dynamic scoping, we could simply write
//
// int XDrawLine( int x1, int y1, int x2, int y2 ) ;
// int XDrawArc( unsigned int width, unsigned int height,
//               int angle1, int angle2 ) ;
//
// and the functions could pick up the caller's Display* display, 
// Drawable d, and GC gc from the stack frame

there are reasons why dynamic scoping has mostly disappeared from programming languages.
1. though it makes …

Salem commented: Ah yes, closures - a lot easier in some other languages. +9
vijayan121 1,152 Posting Virtuoso

you cannot apply a dynamic_cast on a void* to get a non void pointer.
except in a trivial case, in dynamic_cast<T>(v), v should be a pointer to or an lvalue of a polymorphic type.
if T is a (cv qualified) void* , and v is a pointer to a polymorphic type, the result is a (cv qualified) void* pointer which points to the 'most derived object' pointed to by v.
here is an example:

#include <typeinfo>
#include <iostream>
using std::cout ;

struct A { virtual ~A() {} int a ; } ;
struct B : virtual A { int b ; } ; struct C : virtual A { int c ; } ;
struct D : virtual A, virtual B, virtual C
{
   D() { cout << "D::constructor - " ; foo() ; }
   ~D() { cout << "D::destructor - " ; foo() ; }
   void foo() { cout << dynamic_cast<void*>(this) << '\n' ; }
   int d ;
} ;
struct E : virtual A, virtual B, virtual C, virtual D { int e ; } ;

int main()
{
  E object ;
  E* pe = &object ;
  D* pd = pe ;
  C* pc = pe ;
  B* pb = pd ;
  A* pa = pc ;
  void* pv = &object ;

  cout << pv << '\n'
       << dynamic_cast<void*>(pa) << '\t' << pa << '\n'
       << dynamic_cast<void*>(pb) << '\t' << pb << '\n'
       << dynamic_cast<void*>(pc) << '\t' << pc << '\n'
       << dynamic_cast<void*>(pd) << …
vijayan121 1,152 Posting Virtuoso

> it is not working.
two reasons:
a. strcat(buffer,"\\root1\\root2\\test.dll") ; causes a buffer overflow
b. LoadLibrary((LPTSTR)buffer) ; casting is not the way to convert narrow char strings to wide char strings.

wchar_t wbuffer[ MAX_PATH ] ;
wchar_t* result = _wgetcwd( wbuffer, MAX_PATH ) ;
assert( result ) ;
wcscat( wbuffer, L"\\root1\\root2\\test.dll" ) ;
result = LoadLibrary( wbuffer ) ;
vijayan121 1,152 Posting Virtuoso
// ....
while(! infile.eof())
    {

    infile>>sentense;
        continue;
        count+=letter;
        cout<<"The letter a repeated"<<count<<"times(s)"<<endl;
    }
// ...

the continue does nothing (other than perhaps satisfy your teacher) and the statements following it in the loop would be silently ignored by the compiler during code generation. you should change it to
if( ! (infile>>sentense) ) break ; // or continue as you are checking in the while again!
count += letter is incorrect; should be ++count.
you have also omitted to check if the char you read == the letter you are looking for; read a char instead of a string and make a check: is it what you are looking for

you do not need two differerent programs; finding the first occurance and counting the number of occurrances can be done in one pass.

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

int main()
{
  const char* const file_name = "input.txt" ;
  ifstream infile( file_name );
  if( !infile )
  {
    cerr << "cannot open the input file." << endl;
    return 1;
  }

  infile >> noskipws ;
  char letter, ch ;
  cout << "Enter the character:"; cin >> letter;
  int first = -1, nfound = 0 ;

  for( int pos = 0 ; infile >> ch ; ++pos )
    if( ch == letter )
    {
      ++nfound ;
      if( first < 0 ) first = pos ;
    }

  if( nfound>0 )
    cout << "first at: " << first << " total: " << nfound << '\n' ;
  else
    cout << …
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

QDialog is a header file (header files in qt 4.3 do not have a .h extension; they are like headers in libstdc++ ( <iostream>, <QDialog> ).

the easiest way to build a qt applicatiom is to create a Makefile using qmake.
here is a link to a simple tutorial to get you started: http://doc.trolltech.com/4.3/qmake-tutorial.html#starting-off-simple

then just run make (unix) from the same directory where you created the Makefile [ or gmake (linux) or nmake (microsoft) ]. qmake would have created a Makefile which sets up the build enviroinment (compiler switches, library paths etc.) for qt correctly. that is all you would require for this simple example.

vijayan121 1,152 Posting Virtuoso

ZN10FindDialogC2EP7QWidget is the result of the c++ compiler embedding type/namespace information in names (this is called name decoration or name mangling) . see: http://en.wikipedia.org/wiki/Name_mangling#Complex_example for an example.

you have probably inherited virtual functions from the base class QDialog

and i think you are not linking to the library that contains the (compiled) code for QDialog.
the c++ compiler would have demangled the name for you in a diagnostic; the error is from ld
check it out by first just compiling your cpp file ( -c ); it should compile ok if your headers are right

vijayan121 1,152 Posting Virtuoso

Dragon's suggestion of SystemTimeToVariantTime is the easiest way, but might give you inaccurate resuts if you need sub-second resolution for time. see: http://support.microsoft.com/kb/297463
if you need millisecond resolution, more work is required

inline unsigned __int64 to_integral( const SYSTEMTIME& st )
{
   FILETIME ft ;
   SystemTimeToFileTime( &st, &ft ) ;
   ULARGE_INTEGER integer ;
   integer.LowPart = ft.dwLowDateTime ;
   integer.HighPart = ft.dwHighDateTime ;
   return integer.QuadPart ;
}

inline bool operator== ( const SYSTEMTIME& a, const SYSTEMTIME& b )
{ return to_integral(a) == to_integral(b) ; }
inline bool operator< ( const SYSTEMTIME& a, const SYSTEMTIME& b )
{ return to_integral(a) < to_integral(b) ; }
inline bool operator<= ( const SYSTEMTIME& a, const SYSTEMTIME& b )
{ return to_integral(a) <= to_integral(b) ; }
inline bool operator!= ( const SYSTEMTIME& a, const SYSTEMTIME& b ) 
{ return !( a==b ) ; }
inline bool operator> ( const SYSTEMTIME& a, const SYSTEMTIME& b ) 
{ return !( a<=b ) ; }
inline bool operator>= ( const SYSTEMTIME& a, const SYSTEMTIME& b ) 
{ return !( a<b ) ; }
vijayan121 1,152 Posting Virtuoso

define a struct to hold the data/operations for your window

struct my_window_stuff
{
// functions          // ...
// data                     // Texture
// Window
// Map
// whatever else
};

In main/WinMain:
1. initialize a my_window_stuff structure.
2. pass its address (pointer) in the LPARAM argument of CreateWindow/CreateWindowEx

in the window procedure:
case WM_CREATE: store the pointer received (in CREATESTRUCT::lpCreateParams) in the window data
using SetWindowLong/SetWindowLongPtr with WL_USERDATA/GWLP_USERDATA as index.

subsequent messages: retrieve the pointer through GetWindowLong/GetWindowLongPtr,
cast it to my_window_stuff* and use it.

note: if the my_window_stuff needs to be allocated using new (for instance if CreateWindow/CreateWindowEx needs to be called from somewhere other than main/WinMain),
case WM_DESTROY: retrieve the pointer, cast and delete

vijayan121 1,152 Posting Virtuoso

if it is c++, using boost.tokenizer would be the easiest way.

#include <iostream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <string>
#include <vector>
#include <iterator>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;

struct abc
{
  explicit abc( const string& line ) ;
  string x ;
  string y ;
  int z ;
  double w ;
};

abc::abc( const string& line )
{
   typedef tokenizer< escaped_list_separator<char> > tokenizer ;
   tokenizer toker(line);
   tokenizer::iterator iterator = toker.begin() ;
   x = *iterator++ ;
   y = *iterator++ ;
   z = lexical_cast<int>( *iterator++ ) ;
   w = lexical_cast<double>( *iterator ) ;
}

int main()
{
  const char* const file_name = "csv.txt" ;
  // assumes file has data for one abc per line:
  // string x, string y, integer z, double w (seperated by commas)
  // if x or y contain embedded commas, they would be quoted strings (' or ")
  ifstream file( file_name ) ;
  vector<abc> elements ;
  string line ;
  while( getline( file, line ) )
    elements.push_back( abc(line) ) ; // will throw if there are errors
}
vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <limits>
using namespace std ;

inline double get_double()
{
  double value ;
  if( cin >> value ) return value ;
  
  cout << "you have to enter a number!\n" ;
  cin.clear() ;
  cin.ignore( numeric_limits<streamsize>::max(), '\n' ) ;
  return get_double() ;
}
vijayan121 1,152 Posting Virtuoso
// ISO/IEC 10646:2003(E) is available for free download from http://standards.iso.org/ittf/PubliclyAvailableStandards/c039921_ISO_IEC_10646_2003(E).zip
// unicode 5.0 has the same character repertoire as 
// ISO/IEC 10646:2003 with Amendments 1 and 2 applied.
// in g++ and microsoft c++, wchar_t is unicode 5.0. using either,

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

int main()
{
  wstring name ;
  wcout << L"name: " ;
  getline( wcin, name ) ;
  wcout << L"name is: (hex) " << showbase << hex ;
  for( size_t i=0 ; i<name.size() ; ++i ) wcout << int(name[i]) << L' ' ;
  wcout << L" (oct) " << showbase << oct ;
  for( size_t i=0 ; i<name.size() ; ++i ) wcout << int(name[i]) << L' ' ;
  wcout << L" (" << name << L")\n" ;
}
vijayan121 1,152 Posting Virtuoso

... when I run the program, it returns a memory address. I want it to return the value for the array.

array names 'decay' into pointers (addresses); this is fundamental to their use in C and C++. to return an array by value, you could either wrap a structure around the array and return the structure ( ok for pod types, you know the size at compile time) or return std library containers (which support value semantics).

#include <cstddef>
#include <vector>

template< typename T, size_t M, size_t N > struct array2d
{
  T a[M][N] ; // T must have a default constructor
};

array2d<int,10,5> foo()
{
  array2d<int,10,5> array ;
  for( size_t i=0 ; i<10 ; ++i )
    for( size_t j=0 ; j<5 ; ++j )
      array.a[i][j] = i*j ;
  return array ;
}

std::vector< std::vector<int> > bar( size_t M, size_t N )
{
  std::vector< std::vector<int> > array( M, std::vector<int>(N) ) ;
  for( size_t i=0 ; i<M ; ++i )
    for( size_t j=0 ; j<N ; ++j )
      array[i][j] = i*j ;
  return array ;
};

caveat: returning large objects by value can be inefficient

vijayan121 1,152 Posting Virtuoso

... my answer wasn't helpful because ...

on the contrary, your answer was very helpful; the fundamental difference between C and C++ memory management is that in C++, we have variables that may require non-trivial initialization/deinitialization (construction/destruction) and your answer helped bring that difference into clear focus.

vijayan121 1,152 Posting Virtuoso

Should I not be trying to help? ... and I'll shut up until I'm more of an expert. ...

you should definitely try to help to the best of your ability. that is how you can enrich the community. and please do not treat a technical comment on a post you made as a personal attack. i'm sorry if it upset you; that was not my intention at all. so please continue contributing to the forum as you have been doing; you will be doing no harm, but a lot of good. to others and to yourselves.

vijayan121 1,152 Posting Virtuoso

> Can i use realloc to deallocate the memory allocated using new operator
you should not. see http://www.research.att.com/~bs/bs_faq2.html#realloc
as suggested, using a vector is the simplest solution.

hamrick's idea has some potential problems:

T *dst = new T[newSize];

will only work if T has accessible default initialization (a trivial constructor or a public default constructor)

while ( --oldSize >= 0 ) { dst[oldSize] = src[oldSize]; }

wil work only if T has an accessible assignment operator

even if both are available for T, constructing by default and then assigning may not be efficient.

instead you could use malloc/free/realloc with calls to placement new (or or std::uninitialized_copy) and direct calls of destructor. using a std::allocator<T>::allocate/construct/destroy/deallocate would also work, but that is what a std library container (like vector) does in any case.

and since you have asked this question, that is not something you should attempt at this stage. just use a std::vector for now.

vijayan121 1,152 Posting Virtuoso

yeah turbo c++ is ancient, nonstandard and unstable

completely incorrect. the current version of turbo c++ (the free version is now called 'Turbo C++ Explorer') does support standard ANSI C and ISO/IEC C++ languages and libaries. it includes the Dinkumware C++ runtime libraries and supports the Boost library. download from one of the locations listed on http://www.turboexplorer.com/downloads
you may also find this helpful: http://cplus.about.com/od/learnc/ss/tcsharpins.htm
note: the free version does not have a command line compiler though; you will have to compile and build from the ide.

vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std ;
 
const char* const ranks = "A23456789TJQK ATJQK" ; 
struct on_rank 
{ 
 bool operator() ( char a, char b ) const
 { return strchr(ranks,a) < strchr(ranks,b) ; }
};
 
int main()
{
 enum { NCARDS = 5 };
 char cards[NCARDS+1] = {0} ;
 for( int i=0 ; i<NCARDS ; ++i ) 
  { cin >> cards[i] ; cards[i] = toupper(cards[i]) ; }
 sort( cards, cards+NCARDS, on_rank() ) ;
 cout << "straight? " << boolalpha 
        << ( strstr( ranks, cards ) != 0 ) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

...you might check the boost libraries to see if it contains anything usefule.

yes, boost.iostreams could be used.

#include <iostream>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <fcntl.h> // posix open
#include <cassert>
#include <iterator>
#include <stdlib.h> // system
using namespace std ;
using namespace boost::iostreams ;

int main()
{
  int fdin = open( "/usr/local/include/boost/iostreams/stream.hpp", 
                                    O_RDONLY|O_SHLOCK ) ;
  int fdout = open( "/tmp/copy_of_stream.hpp", O_WRONLY|O_CREAT|O_TRUNC ) ;
  assert( ( fdin != -1 ) && ( fdout != -1 ) ) ;

  {
    file_descriptor_source srce( fdin ) ;
    file_descriptor_sink sink( fdout ) ;
    stream<file_descriptor_source> input_file( srce ) ; 
    input_file >> noskipws ;
    stream<file_descriptor_sink> output_file( sink ) ;
  
    istream_iterator<char> begin(input_file), end ;
    copy( begin, end, ostream_iterator<char>(output_file) ) ;
  }

  close(fdin) ;
  close(fdout) ;
  assert( system( "diff /usr/local/include/boost/iostreams/stream.hpp"
                       " /tmp/copy_of_stream.hpp" ) == 0 ) ;
}

unlike most of boost (source only, just include the headers), constructing streams from posix file_descriptors or windows file handles requires linking to the library libboost_iostreams. eg. build with
> g++ -Wall -std=c++98 -I/usr/local/include -lboost_iostreams -L/usr/local/lib mystreams.cpp && ./a.out

vijayan121 1,152 Posting Virtuoso
// and here is an example of operating on function objects
// where f1 and f2 are unary function objects;
// we define an operation fnew = f1 & f2 
// fnew is a new function equivalent to f1(f2(T))
// see "Ruminations on C++" - andy koenig & barbara moo 
// pp. 241-261 for a full discussion

#include <algorithm>
#include <iostream>
#include <functional>
#include <boost/function.hpp>
#include <math.h>
#include <float.h>
using namespace std ;
using namespace boost ;

template < typename FN1, typename FN2 > struct chain_t 
 : unary_function< typename FN2::argument_type, typename FN1::result_type >
{
  chain_t( FN1 f1, FN2 f2 ) : fn1(f1), fn2(f2) {}
  typename FN1::result_type operator() ( 
                                 typename FN2::argument_type arg ) const
  { return fn1( fn2( arg ) ) ; }
  FN1 fn1 ;
  FN2 fn2 ;
};

template < typename FN1, typename FN2 > inline chain_t<FN1,FN2>  
operator& ( FN1 fn1, FN2 fn2 ) { return chain_t<FN1,FN2>(fn1,fn2) ; }

int main()
{
  typedef function<double(double)> fun_type ;

  fun_type new_fun = bind2nd( plus<double>(), 10.4 ) & 
                     bind2nd( multiplies<double>(), 2.3 ) ;
  cout << "(5.6*2.3)+10.4 == " << new_fun(5.6) << '\n' ;

  fun_type another_fun = ptr_fun(sqrt) & new_fun ;
  cout << "sqrt( (5.6*2.3)+10.4 ) == " << another_fun(5.6) << '\n' ;

  fun_type a_third_fun = ptr_fun(ceil) & another_fun ;
  cout << "ceil( sqrt( (5.6*2.3)+10.4 ) ) == " << a_third_fun(5.6) << '\n' ;
}

> g++ -std=c++98 -Wall -I/usr/local/include functor_chain.cpp && ./a.out
(5.6*2.3)+10.4 == 23.28
sqrt( (5.6*2.3)+10.4 ) == 4.82494
ceil( sqrt( (5.6*2.3)+10.4 ) ) == 5

vijayan121 1,152 Posting Virtuoso
**&p == *(*&p) == *p
*&*&*&x == *&*&x == *&x == x

unary & is the addressof operator; unary * is the dereference operator. so

&x

== address of x (pointer to x)

*&x

is dereference of the pointer to x ie. dereference address of x (== x itself).

vijayan121 1,152 Posting Virtuoso

the total store of c++ functions is fixed. these are the functions which were written when the code was compiled; there is simply no way to create new functions at run time. what differentiates function objects from functions is that they are objects (variables). in principle we can do everything with them that we can do with any other kind of variable. among other things, thay can hold state, they can be modified at run time and they can be created at run time. simply put, function objects give us a means to bundle a function call with implicit arguments to pass to that function. this allows us to build up complicated expressions using surprisingly simple syntax.

perhaps an example would help. we want to sort a sequence of integers; the sort criteria is a single digit of the integer at a position N (digit 0 being the least significant one). the value of N is known only at run time.
here is a version using c library qsort which requires a pointer to a comparison function (we avoid global variables for all the usual reasons - they encourage tight coupling, are a recipe for disaster in the presence of concurrency etc.):

#include <cstdlib>
#include <vector>
#include <iostream>
#include <boost/random.hpp>
#include <iterator>
#include <cassert>
using namespace std ;
using namespace boost ;

int compare_digit( int first, int second, int digit )
{
  int div = 1 ;
  for( int i=0 ; i<digit ; ++i ) div *= …
shouvik.d commented: You are the best to explain...Cheers to you +1
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
#include <fstream>
#include <string>
#include <vector>
#include <cassert>
using namespace std ;

int main()
{
  const char DELIM = '>' ;
  const char* const file_name = "whatever" ;
  ifstream file( file_name ) ; assert(file) ;
  vector<string> names, sequences ;
  string line ; 

  // skip lines till we get one starting with DELIM
  while( getline(file, line) ) 
    if( !line.empty() && line[0]==DELIM ) break ;

  names.push_back( line.substr(1) ) ;
  string charseq ;
  while( getline(file, line) )
  {
    if( !line.empty() && line[0] == DELIM )
    {
      sequences.push_back(charseq) ;
      charseq.clear() ;
      names.push_back( line.substr(1) ) ;
    }
    else
     charseq += line + '\n' ;
  }
  sequences.push_back(charseq) ;
}
iamthwee commented: short n sweet +11
vijayan121 1,152 Posting Virtuoso
enum { ROWS = 3, COLS = 5 };
   const int array[ROWS][COLS] = { /* ... */ } ;

   int max_in_row[ROWS] = { /* ... */ }, min_in_row[ROWS] = { /* ... */ },
         max_in_col[COLS] = { /* ... */ }, min_in_col[COLS] = {/* ... */ };

   for( int row=0 ; row<ROWS ; ++row )
     for( int col=0 ; col<COLS ; ++col )
     {
         // ...
     }
    // this is the only loop that iterates thru the elements (once).
   // at this point you should have arrays max_in_row,  min_in_row, 
   // max_in_col, min_in_col filled with the right values
vijayan121 1,152 Posting Virtuoso

now that you have solved it, can you make it more efficient? ie. find the max for each row and each col by making one single pass through the elements of the array.

vijayan121 1,152 Posting Virtuoso

1. g++ -DHAVE_CONFIG -Wall -std=c++98 -o myprogram
2. ,/myprogram hello world

in 1., the command line args are used by the c preprocessor, some are forwarded to the compiler and linker

in 2., the command line args are passed to myprogram and are available as parameters passed to main

vijayan121 1,152 Posting Virtuoso

it is a standard component of the library in c++0x see http://www.open-std.org/jtc1/sc22/wg21/ libstdc++ (gcc 4.30) and dinkumware std c++ library implement this natively; boost.tr1 library could be used if you have an older compiler and boost.

#include <iostream>
#include <functional>

int main( int argc, char** argv )
{
  //using libstdc++ TR1 implementation (g++43 -std=c++0x)
  std::cout << std::hash<char*>()( argv[0] ) << '\n' ;

  //using boost.tr1 library ( #include <boost/tr1/functional.hpp> )
  //std::cout << std::tr1::hash<char*>()( argv[0] ) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

>> ... How does main know that unit_test is going to test sorting ints? What if unit_test tests bubble_sort on five types instead of just one? I want to tell unit_test to use bubble_sort, but let unit_test pick the type.

>>> i would suggest that you leave this problem for the present...

ok, that was some two weeks back. if you have been exploring generic programming during this time, you should be able to figure out the following solution by now.

#include <algorithm> 
#include <iostream>  
#include <cstdlib>  
#include <string>

using namespace std;

template <typename Iterator>
void content_display( Iterator first, Iterator last )
{
  while ( first != last ) 
    cout<< *first++ <<" ";
  cout<<endl;
}

namespace hamrick 
{
  // note: bubble_sort is now a function object 
 // (always preferred over - more flexible than - functioins).
  template <typename Iterator> struct bubble_sort
  {
    // trivial meta function gives the bubble_sort type to be used
    template <typename another_iterator> struct rebind
    { typedef bubble_sort<another_iterator> type ; };
  
    void operator()( Iterator first, Iterator last ) const
    {
      Iterator current = first;
      while ( current != last )
      {
        content_display( first, last );
        Iterator from = last ;
        bubble_up( --from, current );
        ++current;
      }
    }
  
    void bubble_up( Iterator from, Iterator downto ) const 
    {
      while ( from != downto )
      {
        Iterator temp = from ;
        if ( *from < *--temp )
                  swap( *from, *temp );
        --from;
      }
    }
  };
}

template <typename T>
bool issorted( T array[], const int size ) …
vijayan121 1,152 Posting Virtuoso

How does main know that unit_test is going to test sorting ints? What if unit_test tests bubble_sort on five types instead of just one? I want to tell unit_test to use bubble_sort, but let unit_test pick the type.

for that we need to program with types at compile time rather than with variables at run time. this is called template metaprogramming and involves compile-time algorithms, sequences and metafunctions. i would suggest that you leave this problem for the present (until you have mastered things like partial specialization of templates). if you are curious, have a look at http://www.boost.org/libs/mpl/doc/tutorial/tutorial-metafunctions.html
for now; but come back later to tackle such problems.

vijayan121 1,152 Posting Virtuoso
/*
  sorting test

  Class based sorting
    by Kimberly Hamrick
*/
#include <algorithm> // for C+'s sort
#include <iostream>  // for C++ I/O
#include <stdlib.h>  // for random numbers

using namespace std;

template <typename Iterator>
void content_display( Iterator first, Iterator last ) {
  while ( first /*<*/ != last ) // more flexible
    cout<< *first++ <<" ";
  cout<<endl;
}

namespace hamrick {
  template <typename Iterator>
  void bubble_sort( Iterator first, /*const*/ Iterator last ) {
    Iterator current = first;

    // bubble up each element of the array
    while ( current /*<*/ != last ) {
      content_display( first, last );
      Iterator from = last ;
      bubble_up( /*last - 1*/ --from, current );
      ++current;
    }
  }

  template <typename Iterator>
  void bubble_up( Iterator from,  /*const*/ Iterator downto ) {
    // bubble up to the last sorted element
    while ( from /*>*/ != downto ) {
      Iterator temp = from ;
      if ( *from < *( /*from - 1*/ --temp) )
                swap( *from, */*(from - 1)*/temp );
      --from;
    }
  }
}

// Check that an array of T is sorted
template <typename T>
bool issorted( T array[], const int size ) {
  bool sorted = true;

  // it's sorted if the previous element is smaller
  // than the current element for all elements
  for ( int i = 1; i < size; i++ ) {
    if ( array[i - 1] > array[i] ) {
      sorted = false;
      break;
    }
  }

  return sorted;
}

template <typename FN, typename ITERATOR >
void call_function( FN func, ITERATOR begin, …
vijayan121 1,152 Posting Virtuoso

The first one works if I know what type T is. If I don't, it doesn't work. The second one doesn't work at all.

there was a typo in the second one (corrected now). if we also want to call the function with some arg, here is a modified version of the two functions.

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

template < typename T > void template_function( T arg ) 
 { cout << "template_function< " << typeid(T).name() << " >\n" ; }

template< typename T >struct functor
{
  bool operator() ( const T& arg ) const 
  { return cout << "function_object\n" ; }
};

template < typename T > 
void function( void (*func)(T), T arg ) { func(arg) ; }

template <typename FN, typename T > 
void better_function( FN func, T arg ) { func(arg) ; }

int main()
{
  function( template_function< int >, 23 ) ;
  better_function( template_function< int >, 23 ) ;
  // function( strlen, "hello" ) ; // error
  better_function( strlen, "hello" ) ; // ok
  // function( functor< double >(), 5 ) ; // error
  better_function( functor< double >(), 5 ) ; // ok
}
vijayan121 1,152 Posting Virtuoso
template <typename T> void template_function( T arg ) ;

template <typename T>
void function( void (*func)(T) )
 { /* ... */ }

// this is better, would also accept compatible functions 
// and function objects
template <typename FN>
void better_function( FN arg )
 { /* ... */ }
vijayan121 1,152 Posting Virtuoso

How is it awkward? And if you use a reference instead is it still awkward?

void foobar( int array[], int size, const sort_base<int>& ref,
                         const sort_base<int>* ptr )
{
   ref( array, size ) ; // reference, not awkward
   ptr->operator() ( array, size ) ; // pointer, awkward
   (*ptr)( array, size ) ; // pointer, still awkward
 }

by awkword, i mean a. impairs rather than enhances readability b. is also not an elegant construct to write.

Why not? I think that would be useful.

this again requires a long answer (sigh)
let us say that in translation unit a.cpp, we have

struct base_class 
{
  template<typename T> virtual void template_member( const T& v ) const = 0;
};

and we compile this and put the resultant object file into a library.
i use this library and in my code (say my.cpp) write

struct my_class : A 
{
  template< typename T > virtual void template_member( const T& v ) const
      { /* what ever */ }
};
void use_base_class( base_class* pbc ) ;
void my_fun()
{
  int i = 23 ;
  string str = "this is going to be difficult" ;
  my_class* mc = new my_class ;
  mc.template_member(i) ;
  mc.template_member(str) ;
  mc.template_member(cout) ;
  mc.template_member(my_fun) ;
  use_base_class( mc ) ;
}

class my_class has now four(!) virtual functions my_class::template_member<int>, my_class::template_member<string> etc.
and i now define use_base_class this way

void use_base_class( base_class* pbc )
{
  int i = 23 ;
  string str = "this is going to …
vijayan121 1,152 Posting Virtuoso

it is fine if your idea is just test out your understanding of templates, functors and inheritance. however, functors (aka function objects) are usually not implemented as object oriented types for a variety of reasons.

template <typename T> struct sort_base
 {
    virtual void operator()( T array[], const int size ) const = 0;
 };
void foobar( int array[], int size, const sort_base<int>& ref,
                         const sort_base<int>* ptr )
{
   ref( array, size ) ; 
   ptr->operator() ( array, size ) ; 
   (*ptr)( array, size ) ;
}

a. overloaded operators look natural and enhances readability when used with values (or references). object oriented types are usually accessed through pointers; using overloded operators with pointers is awkward. so we do not normally find object oriented types with overloaded operators.
b. void operator()( T array[], const int size ) const has a hardcoded assumption that we are sorting a C style array; we can make it somewhat more flexible by writing <template typename C> void operator()( C& array, const int size ) const . this would allow us to also sort a vector<> etc.

<template typename ITERATOR> 
  void operator()( ITERATOR begin, ITERATOR end ) const

would be even more generally applicable.
however, template member functions cannot be virtual.
c. this does not mean that we can not use the sort functors polymorphically. instead of

template <int size>
    void unit_test( const hamrick::sort_base<int>& sorter )

we could write this

template <int size, typename SORT_FUNCTOR>
   void unit_test( const SORT_FUNCTOR& sorter …