vijayan121 1,152 Posting Virtuoso

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

#include <stdio.h>

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

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

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

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

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

> Shouldn't "this" inside CMeasurement::getSumMethodName have the same value as &meas?
not necessarily. if getSumMethodName is a function inherited from a base class (in a multiple inheritance scenario) and the base class is at a non-zero offset, the this pointer in the function should point to the base class sub-object (and not &meas).

#include <iostream>

struct A
{
  void foo() { std::cout << "A* A::foo::this: " << this << '\n' ; } 
  char filler[1234] ;
};

struct B 
{
  void bar() { std::cout << "B* B::bar::this: " << this << '\n' ; } 
  char filler[1234] ;
};

struct C : A, B
{
};

int main()
{
  C c ;
  C* pc = &c ;
  B* pb = pc ;
  std::cout << "C* pc: " << pc << '\n' ;
  std::cout << "B* pb: " << pb << '\n' ;
  c.foo() ;
  c.bar() ;
}
vijayan121 1,152 Posting Virtuoso

> is it possible to declare a windows CRITICAL_SECTION object as a member of a base class
> that will not be created for each derived class?
yes

> Does this look like a reasonable way to implement CRITICAL_SECTION
yes, this is the normal way when you want to synchronize access to instances. though, in c++ code, use of RAII is canonical. http://jrdodds.blogs.com/blog/2004/08/raii_in_c.html

> I want to implement an instance counter that is threadsafe
if the only thing that you want to synchronize is a variable having an integral value, a critical section is an overkill. using InterlockedIncrement /InterlockedDecrement would be simpler and more efficient. http://msdn.microsoft.com/en-us/library/ms684122(VS.85).aspx

vijayan121 1,152 Posting Virtuoso

> ... the program works!!
it should not even compile. a conforming compiler will give you an error for this:

void bwt_encode(byte *buf_in, byte *buf_out, int size, int *primary_index)
{
  // error: size is not a constant known at compile-time
  int indices[ size ];
  // ...
}

> ... microsoft error box. Could it due to my txt file is too big?
no. your file is very small.
the problem is here:

// ...
//Print out encode/decode results: 
printf("Input  : <%.*s>\n", size, buf1);
printf("Encoded: <%.*s>\n", size, buf2);
printf("Decoded: <%.*s>\n", size, buf3); 
// ...

printf (with %s) can only handle c-style strings (char arrays which are null-terminated).
buf1, buf2, buf3 are char arrays alright; but they do not have a null character at the end.

vijayan121 1,152 Posting Virtuoso

> maybe the book Java Concurrency in Practice addresses this thing
no, it doesn't. it is a good book on concurrency issues in general, but discusses only java.

> where do you stand vijayan121
closer to Knuth than to Sutter. my experience has been that the extra synchronization overhead very often cancels out quite a bit of the performance gains. not to mention exponentially greater complexity of the software. it is much cheaper to just buy more machines than hire more (good) programmers.

> But how you would solve others like i.e examining a 2d matrix?
high performance mathematical/graphics/engineering computing would remain a niche area. again, i tend to agree with Knuth:

I know that important applications for parallelism exist—rendering graphics, breaking codes, scanning images, simulating physical and biological processes, etc. But all these applications require dedicated code and special-purpose techniques, which will need to be changed substantially every few years.

> can you point to any articles concerning the concurrency in the kernel?
freebsd:
not too many articles exist. to be current, you need to look at the source code. and the freebsd-hackers mailing list. http://lists.freebsd.org/mailman/listinfo/freebsd-hackers
a somewhat dated reference is the book 'The Design and Implementation of the FreeBSD Operating System' http://www.informit.com/store/product.aspx?isbn=0201702452
some other documents/papers that i'm aware of:
http://people.freebsd.org/~kris/scaling/7.0%20Preview.pdf
http://www.onlamp.com/pub/a/bsd/2008/02/26/whats-new-in-freebsd-70.html?page=4
http://ieeexplore.ieee.org/Xplore/login.jsp?url=/iel5/4215472/4215473/04215520.pdf
http://portal.acm.org/citation.cfm?id=1251976.1252627&coll=GUIDE&dl=GUIDE
http://www.watson.org/~robert/freebsd/2005eurobsdcon/eurobsdcon2005-netperf.pdf

solaris:
book: 'Solaris Internals: Solaris 10 and OpenSolaris Kernel …

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
#include <string>
#include <vector>
#include <fstream>

typedef unsigned char byte ;

void bwt_encode( byte* buf_in, byte* buf_out, int size, 
                 int* primary_index ) ;
void bwt_decode( byte* buf_in, byte* buf_out, int size, 
                 int primary_index ) ;

int main()
{
  std::ifstream fin("Dec of Ind.txt") ;
  std::string word ;

  while( std::getline(fin,word) )
  {
    std::vector<byte> vec1( word.begin(), word.end() ) ;
    std::vector<byte> vec2( vec1.size() ), vec3( vec1.size() ) ;
    int primary_index = 0 ;
    byte* buf1 = &vec1.front() ;
    byte* buf2 = &vec2.front() ;
    byte* buf3 = &vec3.front() ;
    int size = vec1.size() ;
    
    bwt_encode( buf1, buf2, size, &primary_index ) ;
    bwt_decode( buf2, buf3, size, primary_index ) ;

    // etc
  }
  // ...  
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> Is there any standard function to test the endianess of the system?

inline bool little_endian()
{
  union
  {
    long i ;
    char c[ sizeof(long) ] ;
  };
  i = 1 ;
  return c[0] == 1 ;
}
vijayan121 1,152 Posting Virtuoso

> is there any way to use threads in c++

the ISO standards committee (c++09) has voted voted in a number of concurrency extensions into the working draft (memory model, atomics library, basic threads, locks, and condition variables). an asynchronous future<T> type would be added later, but features like thread pools are deferred.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2320.html

the Boost.Thread library has been rewritten to align with c++09 proposals.
http://www.boost.org/doc/libs/1_35_0/doc/html/thread.html

> Is it common for "everyday" applications (in todays multicore platforms) to use threads?

in windows, probably yes. threads have been widely used over the years.
in unix, probably no. fork is very efficient.
most of the push towards concurrency seems to be in the kernel (solaris, bsd), filesystems (zfs) and libc ( bsd's gemalloc, google's tcmalloc) right now.

opinion seems to be divided; here are two extremes:

I won’t be surprised at all if the whole multithreading idea turns out to be a flop, worse than the "Itanium" approach that was supposed to be so terrific—until it turned out that the wished-for compilers were basically impossible to write.
Let me put it this way: During the past 50 years, I’ve written well over a thousand programs, many of which have substantial size. I can’t think of even five of those programs that would have been enhanced noticeably by parallelism or multithreading. - Donald Knuth

http://www.informit.com/articles/article.aspx?p=1193856

Concurrency is the next major revolution in how we write software
Applications …

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

> how to link classes with each other?
classes are types. are you looking for how to implement a typelist?
a tutorial introduction to typelists: http://www.ddj.com/cpp/184403813?_requestid=1305388
you might then want to read Alexandrescu's Modern C++ Design (Addison-Wesley Longman, 2001).
and look up Boost.MPL http://www.boost.org/doc/libs/1_35_0/libs/mpl/doc/index.html which has a ready made framework for template metaprogramming. eg.

#include <boost/mpl/vector.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/replace.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/assert.hpp>

class A{} ; class B{} ; class C{} ; class D{} ; class E{} ;

int main()
{
  using namespace boost ;

  typedef mpl::vector<A,B> seq_ab ;
  typedef mpl::push_front< seq_ab, C >::type seq_cab ;
  typedef mpl::push_back< seq_cab, D >::type seq_cabd ;
  typedef mpl::replace< seq_cabd, B, E >::type seq_caed ;

  BOOST_MPL_ASSERT(
   ( mpl::is_same< mpl::at< seq_caed, mpl::int_<2> >, E > ) ) ;
}
vijayan121 1,152 Posting Virtuoso

modify the signature of these two functions:

double Value_Of_Num( const string &Expr ) ;
double Value_Of_Expr( const string &Expr ) ;

or a comforming compiler will give you errors.
you can't initialize a reference to a modifiable value with an anonymous temporary (deemed to be a constant).

> The problem i am having is that it cannot compute the expression if i input
> a negative number. like if i input ((5+3)/-2)*5 or ((5+3)/2)*-5
hint: it also baulks at positive numbers with a unary +.
eg. ((5+3)/+2)*5 or ((5+3)/2)*+5

vijayan121 1,152 Posting Virtuoso
for(it = aMap.begin(); it != aMap.end(); it++){
  //some processing
  if(//some condition){
    //some processing
    aMap.erase(key);
    // this is undefined behaviour
    // the iterator is invalid after the erase
    it--;
  }
}

this will work on conforming implementations:

it = aMap.begin() ;
while(  it != aMap.end() )
{
  //some processing
  if(some_condition)
  {
    //some processing
    aMap.erase( it++ ); // postfix required
    continue; // don't increment again
  }
  ++it ; // not erased, increment
}

note: with user defined types, prefer prefix increment/decrement over postfix.

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

> .. I have a large quantity of values...
if the values are in a file, pass the file (istream) to the minmax function. in the function, read the values one by one and check for min/max.
if the values are programmatically generated, pass the generator function (or function object) to the minmax function.

vijayan121 1,152 Posting Virtuoso

with

class Rectangle
{
  //...
  public:
  //...
     Rectangle operator +(Rectangle);
  //...
};

// a, b, c are Rectangles a = b + c ; evaluates to a = b.operator+(c) ; since c is passed by value, a copy of c is made (and destroyed later).
the return value is an anonymous temporary, which is constructed on return (and destroyed).
if you got a third construct/destroy, the (perhaps old?) compiler you are using is not doing any NRV optimization (in the implementation, temporary Rectangle tmp is constructed and destroyed on return).

to avoid the copy, and to make the code const-correct, write

class Rectangle
{
  //...
  public:
  //...
     Rectangle operator+ ( const Rectangle& ) const ;
  //...
};

note: adding rectangles does not seem to be intuitive.

vijayan121 1,152 Posting Virtuoso

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

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

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

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

sort before inserting the string into the multimap?

void fill_mmap( std::multimap< std::string, int >& mmap,
                std::ifstream& file )
{
  std::string line ;
  for( int line_num = 1 ; std::getline( file, line ) ; ++line_num )
  {
    std::sort( line.begin(), line.end() ) ;
    mmap.insert( std::make_pair( line, line_num ) ) ;
  }
}
vijayan121 1,152 Posting Virtuoso

> so i guess i must modify this somehow to add vertice weights. Am i correct ?

yes, i think that should work.
you must be aware that Bellman-Ford does not scale well to large graphs and can result in infinite loops on an ill-formed graph (with unreachable nodes).
so you may want to do a sanity check first.

vijayan121 1,152 Posting Virtuoso

> Do you know how you would go about finding the length of an array?
the array 'decays' into to a pointer when you pass it to a function.
also pass the size of the array (as a second parameter) to the function:

void clearCharArray( char arrayToClear[], std::size_t size )
// ...
testVar.clearCharArray( testVar.harvest, sizeof(testVar.harvest) );

why not you use a std::vector<char> instead?

vijayan121 1,152 Posting Virtuoso

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

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

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

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

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

> Should i just take Dijkstra or Kruskal that i have already coded and add the vertice weights into the game ?

that would not work. Kruskal does something like this
create a set containing all the edges in the graph
... remove an edge with minimum weight from the set
etc.

if you also need vertice weights to be taken into consideration, directly using Kruskal (with the vertice weights added) would add the weight of each intermediate vertex in the path twice. the algorithm has to be modified to correct for this.

vijayan121 1,152 Posting Virtuoso
void clearCharArray( char arrayToClear[] )
{
  int arrayLength = 0;

  // Get the length of the array passed
  // this will not give you the length of the array passed
  arrayLength = sizeof( arrayToClear );
  // equivalent to arrayLength = sizeof( char* ) ;

  for( int i = 0; i < arrayLength; i++ )
  {
    if( arrayToClear[i] != 0 )
    {
        arrayToClear[i] = 0;
    }
  }
}
vijayan121 1,152 Posting Virtuoso

> Are you talking about a class that only has static members and doesn't have a public constructor?
>> yes

that is the java style of programming. in C++, using a namespace for this purpose is canonical.

class foo
{
  foo() ;
  public:
   static int f() ;
   static double value ;
};
namespace foo
{
   int f() ;
   extern double value ;
}
vijayan121 1,152 Posting Virtuoso

> ets say that i have a double number = .3 . When I multiply this by 10, the result should be 3.
> Then, when taking the integer version of this using int(number), the result should be 3, correct?

not necessarily. see

http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

The Art of Computer Programming, Volume 2: Seminumerical Algorithms, Third Edition. by Donald Knuth (Addison-Wesley, 1997). Section 4.2: Floating Point Arithmetic, pages.214–264.

vijayan121 1,152 Posting Virtuoso

one way to extract the digits from a number is to convert the number to a string and then convert the characters in the string to digits.

#include <sstream>
#include <vector>
#include <functional>

template< typename NUMERIC_TYPE >
std::vector<int> get_digits( const NUMERIC_TYPE& number )
{
  // invariant: number is non-negetive
  std::ostringstream stm ;
  stm.precision(0) ;
  stm << std::fixed << number ;
  const std::string& str = stm.str() ;
  std::vector<int> digits( str.begin(), str.end() ) ;
  std::transform( digits.begin(), digits.end(), digits.begin(),
            std::bind2nd( std::minus<int>(), stm.widen('0') ) ) ;
  return digits ;
}

int main()
{
  double value = 1234567890123457024.0 ;
  std::vector<int> digits = get_digits(value) ;
}

as Dozier pointed out, if what you really want is an integral value with a large number of digits, using a double is not a good idea. here are two C++ classes you could use:
class ZZ from NTL http://www.shoup.net/ntl/doc/tour-ex1.html
class bigint from LiDIA http://www.cdc.informatik.tu-darmstadt.de/TI/LiDIA/

vijayan121 1,152 Posting Virtuoso

stupid error in earlier code, corrected here:

// sort indices (tags)
  for( size_t i=0 ; i<tags.size() ; ++i )
    for( size_t j=i+1 ; j<tags.size() ; ++j )
      if( lastnames[ tags[j] ] < lastnames[ tags[i] ] )
         std::swap( tags[j], tags[i] ) ;
vijayan121 1,152 Posting Virtuoso

another way is to use a "tag sort". ie. create an index into the vectors and then sort the indices, rather than the three vectors.
note: this is usually done for efficiency reasons (swap a pair of integers instead of swap three pairs of strings).

// ...
  std::vector<std::string> lastnames;
  std::vector<std::string> firstnames;
  std::vector<int> score;
  std::vector<std::size_t> tags ;

  // fill up lastnames, firstnames, score
  
  for( size_t i=0 ; i<lastnames.size() ; ++i ) tags.push_back(i) ;

  // sort indices (tags)
  for( size_t i=0 ; i<tags.size() ; ++i )
    for( size_t j=i+1 ; j<tags.size() ; ++j )
      if( lastnames[j] < lastnames[i] )
         std::swap( tags[j], tags[i] ) ;

  // print in sorted tag order
  for( size_t i=0 ; i<tags.size() ; ++i )
  {
    std::size_t pos = tags[i] ;
    std::cout << lastnames[pos] << ", " << firstnames[pos]
             << ": " << score[pos] << '\n' ;
  }
// ...

> you might want to use to sort descending rather than ascending.
> To do that you can use not2 in the sort call:
> std::sort(students.begin(), students.end(), not2(OrderByFirstName())); not really. std::sort requires the binary predicate used for comparisons to define a "strict weak ordering". http://www.sgi.com/tech/stl/StrictWeakOrdering.html >= is neither irreflexive nor antisymmetric.

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
#include <vector>

template< typename T > 
void magnify( std::vector< std::vector<T> >& vec, size_t BY = 2 )
{
  std::vector< std::vector<T> > temp(vec) ;
  vec.clear() ;

  for( size_t i=0 ; i<temp.size() ; ++i )
  {
    std::vector<T> row ;
    for( size_t j=0 ; j<temp[i].size() ; ++j )
      row.resize( row.size()+BY, temp[i][j] ) ;
    vec.resize( vec.size()+BY, row ) ;
  }
  // TODO: inefficient; too many temporary vectors.
  // TODO: rewrite to get an efficient version.
}
vijayan121 1,152 Posting Virtuoso
#include <algorithm>

class LakeDataClass
{
  public:
    char DTG[13];
    float DepthOfMeasurements;
    char WaveDirectionStrength[5];
    char Weather[9];
    float DissolvedOxygen;
    float pH;
    float AirTempCelsius;
    float WaterTempCelsius;
    float WaterTempFahrenheit;
    float AirTempFahrenheit;
    float SunLight;
    float BarPress;
};

bool compare_on_descending_value( const LakeDataClass& first,
                                  const LakeDataClass& second);

// can't modify const things! remove the const specifier
void sort_on_descending_value( /*const*/ LakeDataClass* array, int N );


int main()
{
  const int MAXSZ = 1000 ;
  LakeDataClass LakeDataArray[MAXSZ] ;
  int ObjectReadCount = 0 ;

  // fill up array here
  // increment ObjectReadCount for each object read

  // to sort the array:
  sort_on_descending_value( LakeDataArray, ObjectReadCount ) ;
  // use sorted array
}

bool compare_on_descending_value( const LakeDataClass& first,
                                  const LakeDataClass& second )
{
  return first.pH > second.pH;
}


void sort_on_descending_value( /*const*/ LakeDataClass* array, int N )
{
   std::sort ( array, array+N, compare_on_descending_value );
}

> attempts to sort on the character array DTG failed .,..
write the comparison function this way:

#include <cstring>
bool compare_on_asscending_value( const LakeDataClass& first,
                                  const LakeDataClass& second )
{
  return std::strcmp( first.DTG, second.DTG ) < 0 ;
}
vijayan121 1,152 Posting Virtuoso

verify that the element is present first:

void student::drop_course(int d) 
{
  vector<int>::iterator f = find(c_id.begin(), c_id.end(), d);
  if( f != c_id.end() )
  {
    c_id.erase(f);
    cout << "You have deleted course number " << d << endl;
  }
}

if there are duplicate values in the vector, you need to put this in a loop.

vijayan121 1,152 Posting Virtuoso

dragon: > You might also be able to do this with templates
yes, if there are a lot of members, templates would provide a generic mechanism.
didn't post this earlier because i didn't want to scare away the OP (having spent some time here, i'm a little wiser now) .

#include <functional>

// compare member variable of type T (class C)
template< typename C, typename T >
struct cmp_mem_var_t : std::binary_function<C,C,bool>
{
  cmp_mem_var_t( T C::*p_mem_var, bool ascend )
    : ptr_mem_var(p_mem_var), ascending(ascend) {}
  bool operator() ( const C& first, const C& second ) const
  {
    return ascending ?
             first.*ptr_mem_var < second.*ptr_mem_var :
             first.*ptr_mem_var > second.*ptr_mem_var ;
  }
  private:
    T C::*ptr_mem_var ;
    bool ascending ;
};

// compare result (type T) of a const member function (class C)
template< typename C, typename T >
struct cmp_mem_fun_t : std::binary_function<C,C,bool>
{
  cmp_mem_fun_t( T (C::*p_mem_fun)() const, bool ascend )
    : ptr_mem_fun(p_mem_fun), ascending(ascend) {}
  bool operator() ( const C& first, const C& second ) const
  {
    return ascending ?
             (first.*ptr_mem_fun)() < (second.*ptr_mem_fun)() :
             (first.*ptr_mem_fun)() > (second.*ptr_mem_fun)() ;
  }
  private:
    T (C::*ptr_mem_fun)() const ;
    bool ascending ;
};

// two helpers to deduce types (syntactic sugar)
template< typename C, typename T > inline cmp_mem_var_t<C,T>
compare_member( T C::*p_mem_var, bool ascending = true )
{ return cmp_mem_var_t<C,T>( p_mem_var, ascending ) ; }

template< typename C, typename T > inline cmp_mem_fun_t<C,T>
compare_member( T (C::*p_mem_fun)() const, bool ascending = true )
{ return cmp_mem_fun_t<C,T>( p_mem_fun, ascending ) ; }

and this is how it could be used:


       
vijayan121 1,152 Posting Virtuoso

> I find it interesting that the resolution implied by CLOCKS_PER_SEC is 1/1000000 second,
> but my actual results show 1/100 second.
how typical of linsux. appearances are more important than technical accuracy.
the reason for this dishonesty:

STANDARDS
     The clock() function conforms to ISO/IEC 9899:1990 (``ISO C90'').  How-
     ever, Version 2 of the Single UNIX Specification (``SUSv2'') requires
     CLOCKS_PER_SEC to be defined as one million.  FreeBSD does not conform to
     this requirement; changing the value would introduce binary incompatibil-
     ity and one million is still inadequate on modern processors.

- FreeBSD man pages (FreeBSD reports 128 as the value of CLOCKS_PER_SEC)

however, your os would have a variety of clocks/timers, many with much higher resolution.
see: http://www.freebsdmanpage.com/man/clocks-7.html

vijayan121 1,152 Posting Virtuoso

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

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

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

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

> a completely literal translation into C++ would be like this
yes, but we can do much better in C++. be type-safe and const-correct.

template< typename T > class Node
{
  private:
    T item;
    Node<T>* next;

  public:
    Node( const T& obj ) : item(obj), next(0) {}

    T& getItem() { return item; }
    const T& getItem() const { return item; }

    Node<T>* getNext() { return next; }
    const Node<T>* getNext() const { return next; }

    void setItem( const T& obj ) { item = obj; }
    void setNext( Node<T>* n ) {  next = n; }
};

// and for a java like node,
#include <boost/any.hpp>
// http://www.boost.org/doc/libs/1_35_0/doc/html/any.html
typedef Node<boost::any> java_node ;
vijayan121 1,152 Posting Virtuoso

let's say you have a struct/class of this kind:

struct A
{
  int number ;
  double value ;
  char name[30] ;
};

and you want to sort an array of A s on the member value .
first, write a comparison function that the sort can use which accepts two A s to be compared:

bool compare_on_descending_value( const A& first, const A& second )
{
  // function to compare elements of the sequence
  // return true if first should appear *before* second
  // in the sorted sequence; false otherwise
  // for example, this would sort on descending value (member)
  return first.value > second.value ;
}

then call std::sort (header <algorithm> ) passing the comparison function to tell it how elements should be compared for the sort:

void sort_on_descending_value( A* array, std::size_t num_elements )
{
  // use std::sort from <algorithm>
  std::sort( array, array+num_elements, compare_on_descending_value ) ;
}
vijayan121 1,152 Posting Virtuoso

as your 2D vector is 'rectangular' ( not 'jagged' ), you could just

#include <vector>

int main()
{
  // 25,000 '42's in a square matrix
  enum { N = 5000, M = 5000, VALUE = 42 };
  using std::vector ;
  vector< vector<int> > Numbers( N, vector<int>( M, VALUE ) );

  // Turn them all to zeros
  Numbers.assign( N, vector<int>(M) ) ;
}
vijayan121 1,152 Posting Virtuoso

> the way i'm trying to do is using a while loop and checking if words are more than 3 letters
> long....if they are i apply changes....
> if i come accross nodes other than "alphabetical" (like a "space")within 3 nodes back the loop
> breaks..do nothing..change nothing...
the logic looks ok. erasing the character (instead of replacing it with a space) would eliminate the need to remove duplicate spaces later.

> at times it says "list iterator not incrementable"
you need to check for incrementing past end of sequence after *every* increment.

> but it doesnt work. even the 2 letter worrds get affected
you are initializing count just once. you need to reset it for every word.

using a std::string (or a container with a random_access iterator like std::vector ) would have made the code simpler.

#include <algorithm>
#include <functional>

template< typename CNTR > 
void replace_char( CNTR& cntr, char e = 'e', std::size_t min_sz = 4 )
{
  using namespace std ;
  typedef typename CNTR::iterator iterator ;
  const char space = ' ' ;
  // TODO: this example assumes that words are seperated by spaces
  // TODO: modify to use std::isalpha, std::isspace etc.

  iterator first = find_if( cntr.begin(), cntr.end(),
                            bind2nd( not_equal_to<char>(), space ) ) ;
  while( first != cntr.end() )
  {
    iterator last = first ;
    typename CNTR::size_type n = 0 ;
    while( (last!=cntr.end()) && (*last!=space) ) { ++last ; ++n ; }
    if( n > min_sz …
vijayan121 1,152 Posting Virtuoso

> IS it possible to write openssl -based client socket application using c,c++ on
> windows-vc++ platform without using any winsock class and MFC class
yes.

> if possible then what i have to do
> (1) what openssl version i have to use for windows
the current release version of a library 0.9.8

> (2) what API i have to use for creating socket,connecting socket, reading data and writing data.
read the openssl documentation.
a tutorial would definitely help, there are several on the web. eg.
http://www.ibm.com/developerworks/linux/library/l-openssl.html

vijayan121 1,152 Posting Virtuoso

in the original code, the layout of classes a and b are as follows (addresses increasing from the bottom of the page to the top):

layout of object of class A

            _____________________
            |                   |
            |                   |
            |   int a1          |
            |                   |
A* -------->---------------------


layout of object of class B

            _____________________
            |                   |
            |   anonymous       |
            |   subobject a     |
            |                   |
A* -------->---------------------
            |                   |
            |   vtbl pointer    |
            | points to b::vtbl |
            |                   |
B* -------->---------------------

note: with this layout
conversion from a B* to an A* is expensive (check for NULL, if not NULL add an offset which is a constant known at compile time)
vtbl lookup is fast (a B* is itself the vtbl pointer, addition of an offset is not needed).
this is a typical optimization applied by C++ compilers

this can be verified by printing out the two pointers. and the error is obvious.

#include<iostream>
using namespace std;

class a {

public:
int a1; // If I remove this it'll work fine
a() {
cout << "Constructor of a \n";
}
~a() {
cout << "Destructor of a \n";
}

};

class b : public a{

public:
b() {
cout << "constructor of b \n";
}
virtual ~b() { // If I remove virtual from here ... it'll work fine
cout << "destructor of b\n";
}

};

int main()
{
  b* pb = new b ; // memory allocated at address pb
  cout << "b* pb: " …
vijayan121 1,152 Posting Virtuoso

do not pass the address of a local variable (with automatic storage duration) to a thread function; it may not be around by the time the thread executes.

// ...
char* input_sentence = new char[32];
std::strcpy( input_sentence, "ANGLE 360" ) ;
thread = _beginthread( SerialThread, 8192, input_sentence ) ;
// ...

void SerialThread( void* input )
{

     char*  line = static_cast<char*>(input) ;
     Fmain->Memo1->Lines->Append(line);
     delete [] line ;
     _endthread();
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> I'm looking for simplicity more than anything else. I want to be able to store scripts in our
> database, call them from within our C++ game engine, be able to pass arguments to them
> and be able to receive data back from them. I'd also like them to be able to call C++
> functions if need be, in order to access data from our database.

python with the Boost.Python library.
http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html

vijayan121 1,152 Posting Virtuoso

ideally, do not use the (now deprecated) functionality in namespace __gnu_cxx . they have been superceded by tr1 in c++0x.
use -std=c++0x (gcc 4.3) , std::tr1 (gcc4.2) or boost::tr1 (earlier versions).

the error is because __gnu_cxx::hash<> is a struct (function object); not a function. if you have to use it, use it this way

#include <functional>
#include <ext/hash_fun.h>
using namespace std ;

template<class X, class Pred= less<X> >
class Hash{
private:
  Pred comp;
public:
  enum{bucket_size = 4, min_buckets = 8}; 
  Hash() : comp(){ }
  Hash(Pred p) : comp(p){ }
  size_t operator()(const X& x) const{
    const size_t i= __gnu_cxx::hash<X> [B]()[/B] (x);
    return 16807U*(i%127773U)+(95329304U-2836U*(i/127773U));
  }
  
};
vijayan121 1,152 Posting Virtuoso

> How do I match the user-entered input to item #2 in the text file
the closest matching string in the text file is the one with the smallest Levenshtein distance (edit distance) from the user-entered input.
http://en.wikipedia.org/wiki/Levenshtein_distance

> and also detect that the difference between the user-entered input and item #2 is that
> the user-entered input is missing the letter 'u' in the word "input"?
use the information in the matrix used for computation of the Levenshtein distance
http://www-igm.univ-mlv.fr/~lecroq/seqcomp/node2.html

#include <algorithm>
#include <string>
#include <vector>
#include <iostream>

std::size_t levenshtein_distance( const std::string& s,
                                  const std::string& t )
{
  if( s.empty() ) return t.size() ;
  if( t.empty() ) return s.size() ;

  using std::size_t ;
  size_t n = s.size() ;
  size_t m = t.size() ;
  using std::vector ;
  vector< vector<size_t> > d( n+1, vector<size_t>(m+1) ) ;

  for( size_t i = 0; i <= n; ++i ) d[i][0] = i ;
  for( size_t j = 0; j <= m; ++j ) d[0][j] = j ;

  for( size_t i = 1 ; i <= n ; ++i )
  {
      for ( size_t j = 1; j <= m; j++)
      {
        int cost = s[ i - 1 ] == t[ j - 1 ] ? 0 : 1 ;
        d[i][j] = std::min( d[i-1][j] + 1,
                       std::min( d[i][j-1] + 1, d[i-1][j-1] + cost ) ) ;
      }
   }
   // TODO: minimum cost path(s) from d[0][0] to d[n][m]
   // gives the required alignment(s) between the two …
vijayan121 1,152 Posting Virtuoso

there is no readily available facility in the standard library to do this. however, the library is designed to be extensible: so we can easily write our own stream/streambuf derived classes.

the Boost.Iostreams library does contain stream/streambuf derived classes which use a file descriptor/HANDLE. Boost is widely portable, so we could just use it instead of rolling out our own classes.

#include <stdio.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>

int main()
{
  FILE* file = fopen( "/tmp/file.txt", "w" ) ;
  int fd = fileno(file) ;

  using namespace boost::iostreams ;
  file_descriptor_sink fdsink(fd) ;
  stream< file_descriptor_sink > ofstm( fdsink ) ;

  std::ostream& std_ostm = ofstm ;
  std_ostm << "FILE* " << file << " fd: " << fd << '\n' ;
}

note: link with libboost_iostreams. eg.

>g++ -Wall -std=c++98 -pedantic -I /usr/local/include -L /usr/local/lib -lboost_iostreams stream_from_filestar.cc
vijayan121 1,152 Posting Virtuoso

inlining does not take place

in the presence (or absence) of some compiler switches / #pragma directives.
eg. presence of -fno-inline or -finline-limit=small_number / absence of -O in g++

for functions that are called using pointers obtained at runtime.
eg. C callbacks (the comparison function for qsort), C++ virtual functions called polymorphically

if the level of nested or recursive calls to inline functions goes above a certain implementation defined limit

vijayan121 1,152 Posting Virtuoso