vijayan121 1,152 Posting Virtuoso

Although, this code doesn't actually compile for me, it complains about line 30

Yeah, the code is C++1X. I guess I should have mentioned that.

If you are using C++98, you should have also got errors for lines 17 and 20. For C++98, you would need to modify them to something like:

typedef typename std::map< key_type, int>::iterator iterator ;

for( iterator iter = frequency_map.begin() ; iter != frequency_map.end() ; ++iter )
// etc.
vijayan121 1,152 Posting Virtuoso

A slightly more efficient version of the above:

template< typename CHAR_TYPE, typename TRAITS_TYPE, typename ALLOCATOR_TYPE >
void trim_r( std::basic_string<CHAR_TYPE,TRAITS_TYPE,ALLOCATOR_TYPE>& str )
{
    struct _is_space : public std::ctype<CHAR_TYPE> 
    { bool operator() ( CHAR_TYPE c ) const { return is( space, c ) ; } } ;
    _is_space is_space ;

    auto iter = str.rbegin() ; 
    while( (iter!=str.rend()) && is_space(*iter) ) ++iter ;
    str.erase( iter.base(), str.end() ) ;
}
vijayan121 1,152 Posting Virtuoso

You would need to search for chars in strings, extract substrings from strings, convert numbers to strings and strings to numbers.

In general, most programming problems are easy to tackle if we reduce complexity by breaking up the problem into a number of smaller problems, each of which are easy to solve.

What we need to do is something like this:
given a string representation of a ploynomial: f(x) = "2.4x^4 - 1.2x^3 + 6x^2 + 4.1x + 9.2" We need to get the string representation of its derivative: f'(x) = "9.6x^3 - 3.6x^2 + 12x + 4.1" 1. Device a facility to represent a polynomial in our program.

A term of the polynomial can be represented as a pair with a double coefficient and an int exponent. typedef std::pair<double,int> term ; See: http://www.cplusplus.com/reference/std/utility/pair/
For example, the second term of f(x) is given by std::make_pair( -1.2, 3 ) A polynomial can be represented as a sequence of terms typedef std::vector<term> polynomial ; See: http://www.cppreference.com/wiki/container/vector/start
For example, the sequence for f(x) would have the following terms: (2.4,4), (-1.2,3), (6.0,2), (4.1,1), (9.0,0)

2. Write a function to get the derivative of a term term derivative( const term& t ) ; This is easy, derivative of (a,b) is (a*b,b-1); for example, derivative of (-1.2,3) would be (-3.6,2)

3. Write a function to get the derivative of a polynomial polynomial derivative( const polynomial& p ) ; This too is easy; return a …

Nick Evan commented: Nice one. +16
vijayan121 1,152 Posting Virtuoso

This would suffice for char and wchar_t.
Also for any user defined CHAR_TYPE that has defined a ctype facet.

#include <string>
#include <locale>

template< typename CHAR_TYPE, typename TRAITS_TYPE, typename ALLOCATOR_TYPE >
void trim_r( std::basic_string<CHAR_TYPE,TRAITS_TYPE,ALLOCATOR_TYPE>& str )
{
    std::locale loc( std::locale(), new std::ctype<CHAR_TYPE>() ) ;
    auto iter = str.rbegin() ; // C++1X
    while( (iter!=str.rend()) && std::isspace(*iter,loc) ) ++iter ;
    str.erase( iter.base(), str.end() ) ;
}
vijayan121 1,152 Posting Virtuoso

Use std::bitset<>, perhaps?

#include <bitset>
#include <limits>
#include <string>
#include <iostream>

int main()
{
    unsigned char x = 0x02 ; 
    unsigned char y = 0x01 ;
    unsigned char z = 0x03 ;

    typedef std::bitset< std::numeric_limits< unsigned char >::digits > bits ;
    std::cout << bits(x).to_string() + bits(y).to_string() + bits(z).to_string() << '\n' ;
}
vijayan121 1,152 Posting Virtuoso
#include <iostream>

[b]// declare the template friend function first[/b]

template< typename T > struct matrice ;
template < typename T > 
std::ostream& operator<< ( std::ostream& stm, const matrice<T>& m ) ;

template< typename T > struct matrice
{
    //...

    [b]// add <> to the friend declaration in the class 
    // this tells the compiler that the friend function is a template[/b]

    friend std::ostream& operator<< [b]<>[/b] ( std::ostream& stm, const matrice& matrice ) ;

    // ...
};

// define the friend function normally

template < typename T > 
std::ostream& operator<< ( std::ostream& stm, const matrice<T>& m )
{
    // ...
    return stm ;
}

See: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16

vijayan121 1,152 Posting Virtuoso

but would it be possible for you to modify your program to do a search for the Ps before replacing them instead?

If you had really understood the program, you would have been able to make such a trivial modification yourself.

What its lacking, and perhaps the reason it executes so fast, is that it is not doing a search for each ‘P’ in your std::string str variable, but rather it is relying on the repeating pattern of a ‘P’ every 7th character,

The reason it executes faster is because an algorithm which took quadratic time was replaced by an algorithm which takes linear time. This was clearly indicated in the comments in the original code. Even if you have to search for the 'P' in the string, the time taken remains linear and would not lead to an order of magnitude change in speed. It also doesn't matter what programming language you write this in; all that is being done is iterating through a sequence of bytes and moving chunks of bytes around in memory. It will take roughly the same time when compiled to native code.

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

int main()
{
    enum { MAXP = 100, BLOCKSZ = 50, TAIL=40 } ;
    const char* const crnl = "\r\n" ;
    typedef std::string::size_type size_type ;
    typedef std::string::iterator iterator ;

    std::string str( "---P------P----------P--P-P--------------------------P--P--"
                     "-------P-----P------------P----P------P-------P-----P------"
                     "--PPP---PP------P------P-P-------P------P----P--P----P-----" ) ;
    {
        std::string temp ;
        temp.reserve( str.size() + MAXP ) ;
        iterator begin = str.begin() ;

        size_type a = …
vijayan121 1,152 Posting Virtuoso

Do you mean something like this:

struct shape
{
    virtual ~shape() {}
    virtual void print() const = 0 ;
    virtual double delta() const { return 1.0 ; }
    // ...
};

struct sphere : shape
{
    virtual void print() const { std::cout << "sphere\n" ; }
    // ...
};

struct cylinder : shape
{
    virtual void print() const { std::cout << "cylinder\n" ; }
    // ...
};

struct shape_with_flowers : shape
{
    shape_with_flowers( std::shared_ptr<shape> ss ) : s(ss) {}
    std::shared_ptr<shape> s ;
    virtual void print() const { std::cout << "with flower! " ; s->print() ; }
    virtual double delta() const { return s->delta() + 2.0 ; }
    // ...
};

This is fine; it is the decorator design pattern and may be the most elegant solution to the design problem.
http://www.vincehuston.org/dp/decorator.html

vijayan121 1,152 Posting Virtuoso

A fast (very fast) implementation of the Sieve of Atkin: http://cr.yp.to/primegen.html

The less well known Sieve of Sundaram:

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

// sieve of sundaram (naive implementation)
std::vector<int> generate_primes( int N ) 
{
    const int M = N / 2 ;
    std::vector<bool> sieve( M, true ) ;
    for( int i = 1 ; i < M ; ++i )
    {
        const int L = (M-i) / ( 2*i + 1 ) ;
        for( int j = i ; j <= L ; ++j )
            sieve[ i + j + 2*i*j ] = false ;
    }

    std::vector<int> primes ;
    primes.push_back(2) ;
    for( int i = 1 ; i < M ; ++i ) 
        if( sieve[i] ) primes.push_back( i*2 + 1 ) ;
    return primes ;
}

int main()
{
    std::vector<int> primes = generate_primes(100) ;
    std::for_each( primes.begin(), primes.end(), 
                   [] ( int n ) { std::cout << n << ' ' ; } ) ; // C++1x
    std::cout << '\n' ;
}

And the exotic visual sieve: http://plus.maths.org/issue47/features/kirk/index.html

Clinton Portis commented: a fast algorithm with few lines of code +6
vijayan121 1,152 Posting Virtuoso

A generalized (any uni-modal or multi-modal input sequence) version of essentially the same algorithm:

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

// C++1x
template< typename INPUT_ITERATOR, typename OUTPUT_ITERATOR >
void copy_modal_values( INPUT_ITERATOR begin, INPUT_ITERATOR end, // input sequence
                        OUTPUT_ITERATOR result ) // modes to be placed in this sequence
{
  typedef typename std::iterator_traits<INPUT_ITERATOR>::value_type key_type ;
  std::map< key_type, int> frequency_map ;

  while( begin != end ) ++frequency_map[*begin++] ;

  int max_freq = 0 ;
  for( auto iter = frequency_map.begin() ; iter != frequency_map.end() ; ++iter )
    if( iter->second > max_freq ) max_freq = iter->second ;

  for( auto iter = frequency_map.begin() ; iter != frequency_map.end() ; ++iter )
    if( iter->second == max_freq ) *result++ = iter->first ;
}

// simple test driver
int main()
{
  const int a[] = { 1, 2, 6, 7, 6, 2, 8, 8, 6, 8, 2, 9 } ;
  enum { N = sizeof(a)/sizeof(*a) } ;
  std::cout << "modes of [ " ;
  std::for_each( a, a+N, [](int i ) { std::cout << i << ' ' ; } ) ;
  std::cout << "] are [ " ;
  copy_modal_values( a, a+N, std::ostream_iterator<int>( std::cout, " " ) ) ;
  std::cout << "]\n" ;
}
vijayan121 1,152 Posting Virtuoso

My understanding is that in C++ there are much more elegant ways of handling this.

There are. For instance, using a polymorphic call wrapper.
std::function (C++1x), std::tr1::function (C++98 with tr1 extensions) or boost::function (vanilla C++98).

For example C++98 with boost:

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>

struct NewtonRaphson
{
    typedef boost::function< double( double& ) > function_t ;

    void set_it( function_t fun ) { function = fun ; }

    double call_it( double& arg ) { return function(arg) ; }

    function_t function ;
};

float free_fun( double& d )
{ std::cout << "::freefun( " << d << " ) => " ; return d += 1.0 ; }

struct function_object
{
  long double operator() ( double& d ) const
  { std::cout << "::function object( " << d << " ) => " ; return d += 2.0 ; }
};

struct asolver
{
    double compute( double& d ) const
    { std::cout << "asolver::compute( " << d << " ) => " ; return d += 3.0 ; }
};

int main()
{
    NewtonRaphson nr ;
    double d = 10.5 ;

    nr.set_it( free_fun ) ;
    std::cout << nr.call_it(d) << '\n' ;

    nr.set_it( function_object() ) ;
    std::cout << nr.call_it(d) << '\n' ;

    asolver solver ;
    nr.set_it( boost::bind( &asolver::compute, solver, _1 ) ) ;
    std::cout << nr.call_it(d) << '\n' ;
}

It is not shown in the snippet, but you could also wrap a lambda function.

mike_2000_17 commented: very nice! Didn't know about that! +1
vijayan121 1,152 Posting Virtuoso

A teacher of mine told me that when an object of a class is created then six things are created. ...
1)Copy constructor
...

Copy constructors etc. are synthesized (if required) by the compiler at compile-time.

Objects are created at runtime.

vijayan121 1,152 Posting Virtuoso

The libcurl libray you are linking to is using a different version of the C Runtime Library. In your project, modify the settings to use the DLL version of the CRT. For the debug build, link to the debug build of libcurl; for the release link to the release build of libcurl.
See: http://msdn.microsoft.com/en-us/library/6wtdswk0%28v=VS.100%29.aspx

vijayan121 1,152 Posting Virtuoso

don't say how to do this using usarname and password.

One way is to put the username and password in the URL ftp://username:password@hostname/
see: RFC 1738 http://www.ietf.org/rfc/rfc1738.txt
In the example cited:

//#define REMOTE_URL      "ftp://example.com/"  UPLOAD_FILE_AS
#define REMOTE_URL      "ftp://username:password@example.com/"  UPLOAD_FILE_AS

Passing the username and password in plaintext is usually inadvisable; cyphertext should be used instead.
To find out how to do this, see: RFC 2228 http://www.ietf.org/rfc/rfc2228.txt

error C2664: 'fread' : cannot convert parameter 4 from 'void *' to 'FILE *'

Cast the expression to a FILE*.

// size_t retcode = fread(ptr, size, nmemb, stream);
std::size_t retcode = std::fread( ptr, size, nmemb, static_cast<std::FILE*>(stream) ) ;

You might want to use a C++ wrapper for libcurl. http://www.curlpp.org/

vijayan121 1,152 Posting Virtuoso

What is the integer or double equivalent of the NULL...The computer checks the particular index in the array to know if it contains a value or not.

What we are talking about here is the null in the relational database world; the SQL NULL, which essentially says that "this information is missing" or "no information has been stored for this".

For example, "What was the int that the user entered as input?"
78 - the user entered 78
-3 - the user entered -3
0 - the user entered 0
null - we do not know. This information was never entered, or if it was entered, it was not stored anywhere.

The double (floating point) equivalent of the SQL NULL could probably be a NaN http://en.wikipedia.org/wiki/NaN

For int, there is no equivalent "not an int". We would have to create a user-defined type to represent that. For example:

#include <stdexcept>

struct int_or_null
{
   int_or_null() : nothing(true) {}
   int_or_null( int i ) : something(i), nothing(false) {}

   bool is_null() const { return nothing ; }
   operator bool() const { return !nothing && something ; }

   int_or_null& operator= ( int i ) { something = i ; nothing = false ; return *this ; }
   int_or_null& make_null() { nothing = true ; return *this ; }

   // comparison operators for null are similar to those for NaN
   bool operator== ( const int_or_null& that ) const
   { return nothing ? false : !that.nothing && something==that.something ; }
   // …
Ancient Dragon commented: my first thought too :) +35
vijayan121 1,152 Posting Virtuoso

Here is the PowerBASIC program I’m trying to implement and match as close as possible speed wise in either C or C++. It’ll do this 2MB buffer thing in 0.078 seconds (78 ticks) on my old laptop…

This is how I would translate the PowerBASIC code to C++

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

// BEWARE OF DOG. SLIPPERY WHEN WET.

int main()
{
    enum { K = 7, N = 2*1024*1024, N1 = N + N/7, BLOCKSZ = 90, M = N1 + 2*N1/BLOCKSZ, TAIL = 4000 } ;
    const char* const crnl = "\r\n" ;
    typedef std::string::size_type size_type ;
    typedef std::string::iterator iterator ;

    // create a string containing N ' '
    std::string str( N, ' ' ) ;

    // replace every Kth ' ' with a 'P'
    for( size_type i = K-1 ; i < N ; i += K ) str[i] = 'P' ;

    // replace every 'P' with a 'PU'

    // we could do this in quadratic time by:
    // for( size_type i = K ; i < N1 ; i += K+1 ) str.insert( str.begin()+i, 'U' ) ;

    // however, by using some temporary memory, we can do it in linear time by:
    {
        std::string temp ;
        temp.reserve(N1) ;
        iterator i = str.begin() + K ;
        const iterator end = str.end() - K ;
        for(  ; i < end ; i += K )
        {
            temp.insert( temp.end(), i, i+K ) ;
            temp += 'U' ;
        }
        temp.insert( temp.end(), i, str.end() ) ; // copy …
vijayan121 1,152 Posting Virtuoso

> 201 * 201 = 40401 possible tuples.
Yes, 40401 tuples. Thanks.

vijayan121 1,152 Posting Virtuoso

You need to read lines (not individual strings) from the file. Use std::getline() for that.

std::string someName ;
while( std::getline( infile, someName ) )
    name_vec.push_back(someName);

See: http://www.arachnoid.com/cpptutor/student2.html

Then use std::random_suffle() to randomly shuffle the contents of the vector.
See: http://stdcxx.apache.org/doc/stdlibref/random-shuffle.html

Do not forget to seed the random number generator in main.
See: http://www.richelbilderbeek.nl/CppSrand.htm

vijayan121 1,152 Posting Virtuoso

allocates and creates a 2MB buffer of '-' chars, replaces every 7th char with a 'P'; then replaces every 'P' with a 'PU'; then replaces every '-' with an '8';

This will yield the eight chars '888888PU' repeated over and over again to fill 2M + 2M/7 chars

then copies this string in 90 byte chunks to another buffer appending a CrLf to each 90 byte line

The first 92 bytes: 888888PU repeated 11 times followed by 88Cr-Lf
The next 92 bytes : 8888PU followed by 888888PU repeated 10 times followed by 8888Cr-Lf
Then: 88PU followed by 888888PU repeated 10 times followed by 888888Cr-Lf
Then: PU followed by 888888PU repeated 11 times followed by Cr-LF

And now: 888888PU repeated 11 times followed by 88Cr-Lf
The pattern repeats after every 360 (LCM of 90 and 8) bytes in the original buffer; every 368 bytes in the second buffer.

and finally outputs the last 4000 bytes to a MessageBox()

You should now be able to do away with the 2M + 2M/7 buffer altogether and directly generate just the last 4000 bytes needed for the output in a 4000 byte buffer.

vijayan121 1,152 Posting Virtuoso

Since x, y are integers limited to the inteval [ -100, +100 ] there are just 200*200 == 40000 possible tuples (x,y). Just use brute force.

vijayan121 1,152 Posting Virtuoso

Simple Random Selection Without Replacement From a Finite Population

1. Let [b]P[/b] be the fraction of lines to be written into the first file ( [b]P[/b] == 0.63 => 63% )

2. Read all the 300 or so lines from the input file into a [b]std::vector< std::string >[/b]

3. Let [b]N[/b] be the size of the vector (number of lines read)

4. Shuffle the contents of the vector using [b]std::random_shuffle()[/b]

5. Let [b]M[/b] be [b]P * N[/b] rounded to the nearest integer

6. Write the first [b]M[/b] lines into the first output file.

7. Write the remaining [b]N-M[/b] lines into the second output file.
vijayan121 1,152 Posting Virtuoso

Change s2=s2+s1[i]; to s2 += s1[i]; and you would get the behaviour you expect. (why?)

vijayan121 1,152 Posting Virtuoso

If the requirement is that each derived class should have no knowledge of the relative ordering of objects of that class with respect to objects of the other derived classes (any such knowledge should be localized to that part of the program where one needs to sort these objects), a non-intrusive technique has to be used. Since these are polymorphic types, you can create a predicate for the sort using RTTI. eg. to sort on type,

struct base { virtual ~base() {} /* ... */ };
struct A : base { /* ... */ } ;
struct B : base { /* ... */ } ;
struct C : base { /* ... */ } ;
struct D : A { /* ... */ } ;

struct compare_types
{
    bool operator() ( const base* first, const base* second ) const
    {
        static const std::type_info* tinfo[] = { &typeid(A), &typeid(B), &typeid(C), &typeid(D) } ;
        enum { N = sizeof(tinfo)/sizeof(*tinfo) } ;

        // check for nullptr elided
        int a = 0 ; for( ; a < N ; ++a ) if( typeid(*first) == *tinfo[a] ) break ;
        int b = 0 ; for( ; b < N ; ++b ) if( typeid(*second) == *tinfo[b] ) break ;

        return a < b ;
    }
};

void foo( std::vector<base*>& sequence )
{
    // ...
    std::sort( sequence.begin(), sequence.end(), compare_types() ) ;
    // ...
}
vijayan121 1,152 Posting Virtuoso

So far, with c++, all I know how to do is create a super class called Object and make both the Sphere and Plane classes inherit from the Object class. The problem is, when I loop through my scene objects and call the findIntersection method, I get an error saying that the Object class doesn't have a method called findIntersection. So how do I pass the findIntersection call on to the Sphere or Plane?

First, unlike in Java, non-static member functions in C++ classes are not run-time polymorphic by default. Only functions declared as virtual are bound at run-time. So the base class should be something like

class Object
{
   // ....

   public :
      // ideally findIntersection would be 'pure', but ignore that nicety for now
      virtual float findIntersection( const Ray& ray ) const { return 0 ; }

      // a virtual destructor is mandatory in C++ for any class having a virtual function
      virtual ~Object() {}

   // ....
} ;

And then we can have derived classes which override Object::findIntersection.

class Sphere : public Object
{
   public :
      virtual float findIntersection( const Ray& ray ) const
      {
          float intersection ;

          // ...

          return intersection ;
      }
};

Second, In Java class Y { ... void foo( Object x ) { ... } ... } ; x is a reference to an object. C++ does not work that way; the default in C++ is value semantics. x doesn't refer to an object somewhere, you could say that x

vijayan121 1,152 Posting Virtuoso

But I need to separate the each digit of a double variable how I can do this?

A floating-point representations is inexact; so very often you can compute a more accurate result of an operation on real numbers in your head than your computer can do with floating-point numbers. When it comes to 'each digit of a double variable' (where by 'digit' you mean 'decimal digit'), things get even murkier. The floating-point representation of a real number typically uses a radix of 2; though the external representation is decimal (to base 10). We expect 0.01 to be exactly representable; the digits are 0, 0, and 1 followed by zeroes. However 0.01 may not be exactly representable (in limited memory) using a binary radix.

With those caveats in place, write out the double value (to the precision that you require) to a std::ostringstream and pick off the digits from the characters in the std::string.

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <locale>

int main()
{
    double a = 10.35 ;
    std::cout << std::fixed << std::setprecision(16) << a << '\n' ;

    std::ostringstream stm ;
    stm << std::fixed << std::setprecision(16) << a ;
    std::string str = stm.str() ;

    std::cout << "decimal digits: " ;
    for( std::string::size_type i = 0 ; i < str.size() ; ++i )
        if( std::isdigit( str[i], stm.getloc() ) )
        {
            int digit = str[i] - '0' ;
            std::cout << digit << ' ' ;
        }
    std::cout << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

To do this, I need to be able to identify the maximum value of the element in the array and its associated index. In addition, I also want to be able to label the problems with strings as opposed to the array index number. What can I do?

Obviously you need to correct the error indicated by Saith

but you failed to realize, or at least looked over the small detail that the array starts at [0], and not [1], the array goes from problem[0] to problem[8] NOT problem[1] to problem[9].

To associate a string label with each problem, find the element with the maximum value, and print the associated label, create an array containing the labels:

void print_label( const int problem[], const char* const label[], int N )
{
   int max_value = problem[0] ;
   int max_index = 0 ;

   for( int i=1 ; i<N ; ++i ) if( max_value < problem[i] )
   {
       max_value = problem[i] ;
       max_index = i ;
   }

   std::cout << label[ max_index ] << '\n' ;
}

int main ()
{
    // ...
    enum { NPROBS = 9 } ; // number of problems
    int problem[ NPROBS ] = {0} ; // initialize to all zeroes
    const char* const  label[ NPROBS ] = { "label one", "label two", /* etc. */ } ;
    
    // ...

    print_label( problem, label, NPROBS ) ;
    // ...
}

Consider making your code data-driven. For example,

void assign( int dest[], const int srce[], int N )
{ for( …
vijayan121 1,152 Posting Virtuoso

Technically speaking you can change the publicity of a in the derived class by doing this:

class x
{
   int a;
};

class y : public x
{
public:
   x::a;
};

No.

vijayan121 1,152 Posting Virtuoso

Btw we can't change main().

Unless you change main, you do not have a well-formed C++ program - main must return an int

class x { int a ; protected: int& cheat() { return a ; } } ;

class y : public x { public: y() : a( cheat() ) {} int& a ; } ;

int main() { y k ; k.a = 3 ; }
vijayan121 1,152 Posting Virtuoso

but a bit less practical cause i dont know the exact number of arguments

One option is to use the boost preprocessor metaprogramming library.
http://www.boost.org/doc/libs/1_45_0/libs/preprocessor/doc/index.html

For example,

file /tmp/pp.h

#include <boost/preprocessor.hpp>
#include <boost/any.hpp>
#include <vector>

#define repeat_this( place_holder, N, CNTR ) CNTR.push_back( boost::any( Argument ## N ) ) ;

#ifndef BOOST_PP_IS_ITERATING
# ifndef PP_H_INCLUDED
# define PP_H_INCLUDED

// no args case
std::vector< boost::any > make_sequence() { return std::vector< boost::any >() ; }

#define BOOST_PP_ITERATION_LIMITS ( 1, 16 )
#define BOOST_PP_FILENAME_1 "/tmp/pp.h"
#include BOOST_PP_ITERATE()
# endif
#else
# define N BOOST_PP_ITERATION()

// 1 to 16 args case
template < BOOST_PP_ENUM_PARAMS( N, typename T ) >
std::vector< boost::any > make_sequence( BOOST_PP_ENUM_BINARY_PARAMS( N, T, Argument ) )
{
    std::vector< boost::any > many ;
    BOOST_PP_REPEAT( N, repeat_this, many)
    return many ;
}

#endif

file check_it_out.cc

#include "/tmp/pp.h"
#include <string>
#include <iostream>

void print_types( const std::vector< boost::any >& seq )
{
    for( std::vector< boost::any >::size_type i =0 ; i < seq.size() ; ++i )
    {
        if( seq[i].type() == typeid(int) ) std::cout << "int " ;
        else if( seq[i].type() == typeid(double) ) std::cout << "double " ;
        else if( seq[i].type() == typeid(std::string) ) std::cout << "string " ;
        else std::cout << "some_other_type " ;
    }
    std::cout << '\n' ;
}

int main()
{
    int i = 6, j = 7, k = 8 ;
    double d = 9, e = 10 ;
    std::string str = "hello world" ;

    print_types( make_sequence( i, j, d ) ) ;
    print_types( make_sequence( …
vijayan121 1,152 Posting Virtuoso

Would you agree that although the void* mimics the Java interface most closely, the best C++ base would use templates?

Yes.

Also, you may want to keep this in mind. The way iterators are thought about in Java is fundamentally different from the way we use iterators in C++. Both privide an abstract mechanism to access the elements of a sequence one by one, but they use different concepts. A Java Iterator is an interface to a container; a single Java iterator knows about the entire range it traverses. A C++ iterator is an abstraction to identify one element of a sequence; it can move forward in the sequence, but has no idea about the range. In C++, we use a pair of iterators to denote a range.

Another (conceptually less important) difference is that a Java Iterator 'points' to the 'empty space' between elements of a sequence, while a C++ iterator directly 'points' to an element. The C++ iterator can be used like a pointer to an object.

A second area where the differences between the two languages is large is in resource management and error handling. Java uses the try-finally construct whereas C++ uses RAII proper.

I did some research on void* etc and the derived class would then be using templates to cast the pointer. I also note that in 'The C++ Programming Language' Stroustrup describes the use of void* in templates.

AFAIK, the use of a template specialization for void* as a …

vijayan121 1,152 Posting Virtuoso

Compute the depth D of the n-ary tree.
The two dimensional matrix representation will have D columns.

Perform a traversal (say a postorder traversal) of the n-ary tree. During the traversal,

a. Push each node encountered onto a stack. (the first node pushed would be the root).

b. If the node is a leaf node:
        Add the entire contents of the stack as a row of the 2D array. 
        If the size of the stack is less than [b]D[/b], add a [b]null[/b] at the end. 
        (with a complete n-ary tree, more than one [b]null[/b] will never be required.)

    Else:
        Move down to the next level, processing each of the [b]n[/b] children one by one.

c. Pop the node just visited off the stack, move up one level and continue with the traversal.
vijayan121 1,152 Posting Virtuoso

Let us say that we have a full 3-ary tree as follows:

[B]root[/B] 0
                                           |
                  -------------------------------------------------
                  |                        |                      |
                [B]alpha[/B] 1                   [B]beta[/B] 2                 [B]gamma[/B] 3
                  |                        |                      |
        --------------------     --------------------     --------------------
        |         |        |     |         |        |     |         |         |
      [B]delta[/B] 4  [B]epsilon[/B] 5  [B]zeta[/B]   [B]eta[/B]      [B]theta[/B]    [B]iota[/B]  [B]kappa[/B]    [B]lambda[/B]      [B]mu[/B]
        |
--------------------
|        |         |
[B]nu[/B]       [B]xi[/B]      [B]omicron[/B]

A two dimensional array representation of this tree (in the manner required) could be:

row 0: root, alpha, delta, nu
row 1: root, alpha, delta, xi
row 2: root, alpha, delta, omicron
row 3: root, alpha, epsilon, null
row 4: root, alpha, zeta, null
row 5: root, beta, eta, null
row 6: root, beta, theta, null
row 7: root, beta, iota, null
row 8: root, gamma, kappa, null
row 9: root, gamma, lambda, null
row 10: root, gamma, mu, null


If the full tree is a complete tree (every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible), a one dimensional array representation is possible. For the complete 3-ary tree above:

root, alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa, lambda, mu, nu, xi, omicron
  0     1     2      3      4       5       6    7     8      9     10     11    12  13  14    15

The position of the children of node at position p would be p*3+1, p*3+2, p*3+3
The position of the …

jonsca commented: Nice diagram. +6
Nick Evan commented: Excellent post, as always. +16
mrnutty commented: NIce greek letter skills +6
vijayan121 1,152 Posting Virtuoso

I need to store each path in a tree as a row in a two dimensional array of size #of paths x N. I couldn't find the appropriate indexing scheme for the array.

Could you clarify your question? Is it a binary tree or an n-ary tree? What do you mean by 'each path in a tree'? Or is it a directed acyclic graph?

vijayan121 1,152 Posting Virtuoso

I have a text file with characters. I must able to read the length of characters in the file by every line and count the frequency of each characters for each line.
I am still new for c++.

Simplify the problem by breaking it up into two smaller sub-problems:

a. Read each line in a file

b. Count the frequency of each character in a single line

And now, a. Read each line in a file can be broken up into

a1. Open the file for input
a2. Read line by line till end of file


a1. Open the file for input is easy:

std::ifstream file( filename ) ;
if( !file )
{
   std::cerr << "error opening file\n" ;
   std::exit( EXIT_FAILURE ) ;
   // or if this is in main() return EXIT_FAILURE ;
}

a2. Read line by line till end of file
The easiest and least error-prone way to do this is to use a std::string.
See this tutorial: http://www.arachnoid.com/cpptutor/student2.html

std::string line ;
while( std::getline( file, line ) )
{
    // b. Count the frequency of each character in the line
}

Now the problem reduces to:
1. We have a variable line of type std::string containing the line just read from the file.
2. The number of chars in the line is given by line.size(). Store this in a variable N.
3. The chars are line[0], line[1], ... line[N-1].

We need to count the …

vijayan121 1,152 Posting Virtuoso

You might want to have a look at Kernighan and Pike's 'The Practice of Programming'.
http://www.pearsonhighered.com/educator/product/Practice-of-Programming-The/9780201615869.page#takeacloserlook

vijayan121 1,152 Posting Virtuoso

Send a large file across the network and measure the average Round Trip Time.

TCP Throughput = TCP Recieve Window Size / Round Trip Time

eg. if TCP Recieve Window Size is 64K, RTT is 100 ms,
TCP Throughput = 64K * 8 / 0.1 = 5242880 bps = 5.2 Mbps

Your bandwidth = TCP Throughput attained at the optimal TCP Recieve Window Size.

vijayan121 1,152 Posting Virtuoso

I don't want others to edit my strings. It appears there's no easy solution for this, as I don't want any internet connection or such methods

Here's one (stand alone, without network etc.) way to do it; this might help to get you started. It assumes that all you are seeking is 'security through obscurity' (steganography), rather than cryptography proper.

the hex conversion seems to be the easist way to prevent noobs from touching the actual strings

Yes. Other than by using cryptographic techniques, you cannot stop a determined expert hacker.

a. Create a header file with declarations of identifiers for string literals to be used in the program; for example mystrings.h

extern const char* const url ;
extern const char* const message ;
// ...

b. Create a text file containing the string literals. The example assumes that these literals start with the char sequence (" and end with ") . For brevity, it is assumed that these char sequences are not present anywhere else (in comments, in quoted strings, etc.). For example, mystrings.p

#include "mystrings.h"

const char* const url = ("http://www2.research.att.com/~bs/C++0xFAQ.html") ;

const char* const message = ("hello world!") ;

// ...

c. Write a program to read such a file and generate a C++ file containing equivalent obfuscated strings. Again, for brevity, all error handling is elided and a toy obfuscation algorithm is used. obfuscate.cc

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

std::string obfuscate( const std::string& str …
.It. commented: Valued answer. +1
jonsca commented: Above and beyond the call of duty +6
vijayan121 1,152 Posting Virtuoso

Please post the code for void MainWindow::on_btnStart_clicked() . It is around line 31 of mainwindow.cpp

From the error message, you are trying to copy an object of type Producer somewhere in that function and a copy constructor for Producer can not be synthesized (because the base class copy constructor is private).

vijayan121 1,152 Posting Virtuoso

First create a user defined type to represent 23 zero bits and 1 one bit.

#include <cstdint> // C++1X (or <stdint.h> for C99)
struct pattern
{
    enum { NBYTES = 3 } ;
    std::uint8_t bytes[NBYTES] ; // 3 x 8 bits == 24 bits
};

Then provide mechanisms to read such a variable from an input stream and to compare two such variables for equality.

std::istream& operator>> ( std::istream& stm, pattern& p )
{ return stm.read( reinterpret_cast<char*>( p.bytes ), pattern::NBYTES ) ; }

bool operator== ( const pattern& first, const pattern& second )
{ return std::equal( first.bytes, first.bytes + pattern::NBYTES, second.bytes ) ; }

Finally, write the function to return a "yes" or a "no"

const char* find_pattern( const char* path_to_file )
{
    std::ifstream file( path_to_file, std::ios::binary ) ;
    std::istream_iterator<pattern> begin(file), end ;
    static const pattern search_pattern = { { 0, 0, 1 } } ; // 23 zero bits and 1 one bit
    return std::find( begin, end, search_pattern ) == end ? "no" : "yes" ;
}
dip7 commented: Helpful advise. Thanks a lot! +2
vijayan121 1,152 Posting Virtuoso

The problem as I saw it was how to return the unknown 'Object'

The Java programmer's Object is the C or C++ programmers void*.
If a Java method returns an Object, you need to cast it to the correct type before you can do something useful with it.

The closest C++ equivalent would be:

#include <stdexcept>

struct Iterator
{
    virtual ~Iterator() throw() {} // required in C++ (for well-defined behaviour)

    virtual void first() throw() = 0 ;
    virtual void last() throw() = 0 ;
    virtual void next() throw() = 0 ;
    virtual void previous() throw() = 0 ;

    virtual bool isDone() const throw() =  0 ;

    virtual void* current() const throw(std::out_of_range) = 0 ;
};
vijayan121 1,152 Posting Virtuoso

Is there any way to use something like get/getline without providing an argument for storage variable?

If the type involved has default or trivial initialization, you could write such a function yourself. For example:

template< typename T > inline
T get( std::istream& stm ) throw (std::runtime_error)
{
    T temp ;
    if( !( stm >> temp ) ) throw std::runtime_error( "bad stream input" ) ;
    return temp ;
}

And then:

try { std::cout << get<int>( std::cin ) << '\n' ; }
    catch( const std::runtime_error& ) { std::cerr << "error in input\n" ; }

But it doesn't buy you much over:

int i ; if( std::cin >> i ) std::cout << i << '\n' ;
    else std::cerr << "error in input\n" ;
vijayan121 1,152 Posting Virtuoso

Where they are getting information for USER , %CPU , %MEM & TIME+ in Linux

From procfs mounted at /proc
See: http://en.wikipedia.org/wiki/Procfs

Source for procfs utilities: http://procps.sourceforge.net/

vijayan121 1,152 Posting Virtuoso

that shuffles the array and is straight-forward and pretty easy to implement, so that's a good solution.

It is straight-forward and pretty easy to implement, but it is not a correct solution.

There are N! ways of arranging a sequence of N elements. A random shuffle should yield uniformly distributed results; that is, the probability of any particular ordering is 1/N!. There are a number of algorithms that seem at first sight to implement random shuffling of a sequence, but do not in fact produce a uniform distribution over the N! possible orderings. It is easy to write the random shuffle naively and get it wrong.

The Art of Computer Programming, Vol. 2, section 3.4.2 “Random sampling and shuffling”, Knuth describes two (correct) algorithms:

a. If the number of items to sort is small, then simply put all possible orderings in a table and select one ordering at random. In this particular case the table would need 12! rows.

b. “Algorithm P” which Knuth attributes to Moses and Oakford (1963), but is now known to have been anticipated by Fisher and Yates (1938); the 'Fisher–Yates shuffle' http://en.wikipedia.org/wiki/Fisher-Yates_shuffle

always selecting j from the entire range of valid array indexes on every iteration also produces a result which is biased, albeit less obviously so. This can be seen from the fact that doing so yields n^n distinct possible sequences of swaps, whereas there are only n! possible permutations of an n-element array. Since n^n can never …

vijayan121 1,152 Posting Virtuoso

Essentially you just need to implement a 2D polygon clipping algorithm which can handle polygons that are not necessarily convex.

Greiner-Horman algorithm: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.3266&rep=rep1&type=pdf

Vatti clipping algorithm: http://books.google.com/books?id=fGX8yC-4vXUC&pg=PA98

vijayan121 1,152 Posting Virtuoso

but I am not sure the Input/Output chapter covers everything I will need to know.

Any reasonable book should cover all that you need about file i/o for this task. Basically, you just need to be know how to read and write bytes (or sequences of bytes). Dictionary<int, int> would be std::map<int,int> ; read up on std::map<>.

An array of bytes would be byte[] a std::vector<unsigned char> (preferably) or just a plain C-style array; read up on std::vector<>

vijayan121 1,152 Posting Virtuoso

Why did you choose inline here

is_prime() is a small (code size) function that is called millions of times.
See: http://en.wikipedia.org/wiki/Inline_expansion

and why do you return n>1 && primes[n] ?

primes is a vector of bools where primes[n] == true if and only if n is prime.
For example, primes[13] == true and primes[18] == false n>1 && primes[n] => if n is greater than one (to take care of negative n), and primes[n] is true, then n is prime.

Why did you enumerate AMAX, BMAX, and NMAX? Why not just do make_primes(241001) ?

The idea was to make the code a bit more easy to modify; for example if the problem statement changed from
the current n² + an + b, where |a| < 1000 and |b| < 1000 to, say, n² + an + b, where |a| < 500 and |b| < 20000 .

Of course I messed up by writing

for( int a = -999 ; a < 1000 ; ++a )
{
    for( int b = -999 ; b < 1000 ; ++b )

instead of

for( int a = 1 - AMAX ; a < AMAX ; ++a )
{
    for( int b = 1 - BMAX ; b < BMAX ; ++b )

Why do you call make_primes and pass such a large value?

It is the largest value (plus one) that the quadratric n² + an + b, where |a| <= AMAX and …

frogboy77 commented: comprehensive answer +1
jonsca commented: Agreed +6
vijayan121 1,152 Posting Virtuoso

Anyone got any useful optimization tips?

for (vector<int>::const_iterator it = primes.begin(); *it < check + 1; ++it) performs a linear search in O(N) time where N == primes.size()

As the primes are in sorted order, you can reduce the time to O(log N) by doing a binary search.

Better still, you can do this in O(1) (constant time) by indexing into the vector.

For example:

#include <vector>
#include <cassert>
#include <iostream>

std::vector<bool> make_primes( std::size_t N ) // primes < N
{
   std::vector<bool> sieve( N, true ) ;
   sieve[0] = sieve[1] = false ;

   for( std::size_t i = 2; i*i < N ; ++i ) if( sieve[i] )
      for( std::size_t j = i + i ; j < N ; j += i ) sieve[j] = false ;

   return sieve ;
}

inline bool is_prime( int n, const std::vector<bool>& primes )
{ return n>1 && primes[n] ; }

int main ()
{
    enum { AMAX = 1000, BMAX = 1000, NMAX = 200 } ;
    const std::vector<bool>& primes = make_primes( NMAX*NMAX + AMAX*NMAX + BMAX + 1 ) ;

    int max_axb = 0 ;
    int max_n = 0;

    for( int a = -999 ; a < 1000 ; ++a )
    {
        for( int b = -999 ; b < 1000 ; ++b )
        {
            int n = 0 ;
            while( is_prime( n*n + a*n + b, primes ) ) ++n ;
            if( n > max_n )
            {
                max_n = n ;
                max_axb = a * b …
vijayan121 1,152 Posting Virtuoso

> Considering quadratics of the form:

> n² + an + b, where |a| < 1000 and |b| < 1000

> Find the product of the coefficients, a and b, for the quadratic expression that
> produces the maximum number of primes for consecutive values of n, starting with n = 0.

>> ... I found out that b always needs to be prime ...

This assumption does not appear to be correct. Counter-examples are easy to find:

1. with n == 7, a == 2, n² + an == 49 + 14 == 63, n² + an + b is prime

for b in [ -58, -56, -52, -50, -46, ..., -10, -4, +4, +8, +10, +16, +20, ... ]


2. with n == 5, a == -4, n² + an == 25 - 20 == 5, n² + an + b is prime

for b in [ -3, -2, 0, +2, +6, +8, +12, +14, +18, +24, ..... ]

vijayan121 1,152 Posting Virtuoso

sizeof( char* )

vijayan121 1,152 Posting Virtuoso

How can I solve the problem and get the same functionality?

By using a function object instead of a function. (Sorry, missed this question earlier.)

struct FComapare
{
    explicit FComapare( int i ) : p(i) {}

    bool operator() ( Node* lId, Node* rId ) const
    {
        if(lId->getDiff(p) < rId->getDiff(p))
            return true;
        else if(lId->getDiff(p) == rId->getDiff(p))
        {
            if(lId->getLT() < rId->getLT())
                return true;
            else if(lId->getLT() == rId->getLT())
                return (lId->getTFG() < rId->getTFG());
        }
        return false;
    }

    int p ;
};

std::vector< std::set< Node*, FComapare > > m_F;

And then,

for( int i = 0 ; i < partNum ; ++i )
    m_F.push_back( std::set< Node*, FComapare >( FComapare(i) ) ) ;