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

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

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

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

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

can I happily assume that the C++ language will handle that detail correctly without my intervention?

Yes. The implementation is responsible for setting the vtable pointer correctly during construction.

Just make sure that you do not treat C++ objects as 'raw bits'. For example:

struct A
{
    virtual ~A() {}

    A() { std::memset( this, 0, sizeof(A) ) ; /* NO! */ }

    A( const A& that ) { std::memcpy( this, &that, sizeof(A) ) ; /* NO! */ }

    A& operator= ( const A& that )
    { std::memcpy( this, &that, sizeof(A) ) ; /* NO! */ return *this ; }

    void write( std::ostream& stm ) const
    { stm.write( reinterpret_cast<const char*>(this), sizeof(A) ) ; /* NO! */ }

    void read( std::istream& stm )
    { stm.read( reinterpret_cast<char*>(this), sizeof(A) ) ; /* NO! */ }


    int i ;
    long l ;
    char c[128] ;
};

You may want to have a look at Lippman's 'Inside the C++ Object Model' http://www.amazon.com/Inside-Object-Model-Stanley-Lippman/dp/0201834545

vijayan121 1,152 Posting Virtuoso

The problem has nothing to do with either templates or destructors. This too will result in undefined behaviour:

int main()
{
    int coordinates[3] ;
    delete[] coordinates ; // ???
}
vijayan121 1,152 Posting Virtuoso

> But I don't know how to declare a variable to save the value of *minIt

typename std::iterator_traits<iterator>::value_type saved_value = *minIt ;

See: http://www.sgi.com/tech/stl/iterator_traits.html

Do you really need it?

template< typename iterator >
void selection_sort( iterator begin, iterator end )
{
    if( begin != end ) 
    {
       // find the minimum value in [ begin, end ),
       // and swap it with the value at begin
       std::iter_swap( begin, std::min_element( begin, end ) ) ;

       // repeat for [ begin+1, end )
       selection_sort( ++begin, end ) ;
    }
}
vijayan121 1,152 Posting Virtuoso

We don't need to write largerthan<>() when std::greater<>() in <functional> is available.

We can also perform the reduce() operation directly on the array; without using a temporary list<>

#include <algorithm>
#include <functional>

template< typename T >
std::size_t reduce( T ar[], std::size_t n )
{
    std::sort( ar, ar+n, std::greater<T>() ) ;
    return std::unique( ar, ar+n ) - ar ;
}
vijayan121 1,152 Posting Virtuoso

The problem here seems to be re-using the template parameter as the parameter for another template for some reason?

I don't understood the problem. An example, perhaps?

vijayan121 1,152 Posting Virtuoso
template <class T>
void WriteImage(typename T::Pointer image, std::string filename);

As per the IS, a nested typename (for example, the typename Pointer nested in the typename T here) is non-deducible.

If a template parameter is used only in nondeduced contexts and is not explicitly specified, template argument deduction fails.

The nondeduced contexts are:

* The nested-name-specifier of a type that was specified using a qualified-id.

* A type that is a template-id in which ... <elided>

vijayan121 1,152 Posting Virtuoso

i don't really understand it).

i would still like to know why i can create a 4 million 1D array but i can't create
a 4 million 2D array????????

For a dynamically allocated array, eg. new[] T[N] the new expression yields a pointer to the first element of the array. ie. T* ptr_first_element = new T[N] ; slong (*newarray)[limitsqr] = new slong[limitsqr][limitsqr] ; is equivalent to

typedef slong[limitsqr] array_type ;
array_type* newarray = new array_type[limitsqr] ;

We are creating an array with dynamic storage duration where each element is an array; the pointer to the first element is therefore a pointer to an array.

vijayan121 1,152 Posting Virtuoso
const slong limitsqr=2000;
    slong (*newarray)[limitsqr] = new slong[limitsqr][limitsqr] ;
    
    // delete with: delete[] newarray ;
vijayan121 1,152 Posting Virtuoso

arkoenig wrote:
> I would think that if you replace the type std::pair<std::string, unsigned long> in
> lines 7 and 23 by std::pair<const std::string, unsigned long>, it ought to work.
> At least I can't think immediately of any reason it shouldn't.

I had always thought that this error (given by every compiler that I've used, even with std::pair<const std::string, unsigned long>) is because of Koenig lookup. Though I've never really understood why SFINAE does not apply in this case.

But if Koenig himself says that that it ought to work, my understanding is obviously incorrect. So what's going on here?

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

To pass incoming data from one thread to another, the typical technique is:
1. The receiver of the data adds it to a queue shared between multiple threads.
2. The worker thread picks the data off the queue and processes it.

For this to work properly, the queue needs to be written so that data can safely be added by one thread and removed by another thread without corrupting the data structure. The standard way of doing this is by using a condition variable in conjunction with a mutex.

For a tutorial explaining this, see: http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

Here's a simple single-generator/single-consumer example (with random integer data generated in one thread and processed by another):

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/random.hpp>
#include <ctime>
#include <iostream>
#include <queue>

typedef boost::mutex::scoped_lock scoped_lock ;
typedef int event ;

struct event_queue_t
{
    bool empty() const
    {
        scoped_lock lock(mutex) ;
        return queue.empty() ;
    }

    const event& front() const
    {
        scoped_lock lock(mutex) ;
        return queue.front() ;
    }

    void push( const event& e )
    {
        scoped_lock lock(mutex) ;
        queue.push(e) ;
        condition.notify_one() ;
    }

    event pop()
    {
        scoped_lock lock(mutex) ;
        while( queue.empty() ) condition.wait(lock) ;
        event e = queue.front() ;
        queue.pop() ;
        return e ;
    }

    private :
        std::queue<event> queue ;
        mutable boost::mutex mutex ;
        boost::condition condition ;
} ;

event_queue_t event_queue ;
enum { N = 128 } ;
boost::mutex stdout_mutex ;

void event_generator()
{
    using namespace boost ;
    mt19937 twister( std::time(0) ) ;
    uniform_int<> distribution(0,999) ;
    variate_generator< mt19937&, …
vijayan121 1,152 Posting Virtuoso

AFAIK, SDL event polling can't be done in a thread other than the thread that set the video mode.

You could do something like this: The main thread (which set the video mode) polls for events and when an input event is received, it pushes it into (an appropriately synchronized) queue. The event handling thread runs a loop which waits on the queue, picks up events from it and then handles it.

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

Don't boost::filesystem::remove_all and boost::filesystem::remove require a full path as the argument?

AFAIK, lines 20 and 28 should have checkAndRemove( dir_iter->path(), BAD_TYPES ) instead of checkAndRemove( dir_iter->path().leaf(), BAD_TYPES )

vijayan121 1,152 Posting Virtuoso

If you feel at home with templates, you might want to have a look at boost::multi_index<>. http://www.boost.org/doc/libs/1_42_0/libs/multi_index/doc/index.html

For example, a multi_index with two ordered non_unique keys would look something like this:

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace ::boost ;
using namespace ::boost::multi_index ;
using namespace std ;

struct A
{
    A( int i, const char* n, double d ) : id(i), _name(n), _data(d) {}

    const int id ; // non-unique key
    const string& name() const { return _name ; } // non-unique key

    // tags for lookup
    struct by_id {} ;
    struct by_name {} ;

    private :
        string _name ;
        double _data ;
        // ...

        friend inline ostream& operator<< ( ostream& stm, const A& a )
        {
            return stm << "{ " << a.id << ", " << a.name()
                       << ", " << a._data << " }" ;
        }
} ;

typedef multi_index_container
    <

        A,

        indexed_by<
                 ordered_non_unique< tag<A::by_id>,
                        BOOST_MULTI_INDEX_MEMBER( A, const int, id ) >,

                 ordered_non_unique< tag<A::by_name>,
                    BOOST_MULTI_INDEX_CONST_MEM_FUN( A, const string&, name ) >
                  >

    > dual_key_multimap ;

template< typename TAG, typename MULTI_INDEX_CNTR > inline
void print( MULTI_INDEX_CNTR& multi_index_cntr, ostream& stm = cout )
{
    typename MULTI_INDEX_CNTR::template index<TAG>::type& seq =
                                     multi_index_cntr.get<TAG>() ;
    copy( seq.begin(), seq.end(),
          ostream_iterator<typename MULTI_INDEX_CNTR::value_type>(stm,"\n") ) ;
}

template< typename TAG, typename MULTI_INDEX_CNTR, typename KEY > inline
void erase_all_with_key( MULTI_INDEX_CNTR& multi_index_cntr, const KEY& key )
{
    typedef typename MULTI_INDEX_CNTR::template index<TAG>::type SEQ ;
    SEQ& seq = multi_index_cntr.get<TAG>() ;
    seq.erase( seq.lower_bound(key), seq.upper_bound(key) ) ; …
vijayan121 1,152 Posting Virtuoso

The value_type of a std::multimap<KEY,T> is std::pair< const KEY, T > . So,

std::multimap<SortKey,T> firstMap;
std::multimap<SearchKey, pair< const SortKey, T >* > secondMap;


// ...
     std::multimap<SortKey,T>::iterator it = firstMap.insert( std::make_pair(key1,data) ) ;

     std::pair< const SortKey, T >* mizi = &*it ;
     secondMap.insert( std::make_pair(key2,mizi) ) ;
// ...
vijayan121 1,152 Posting Virtuoso

> Would it be efficient to create separate lookup tables for, say, common functions
> (i.e., there is a group of ~40 with the same params etc, another group with ~20)
> and then use an if/else for the individual distinct functions?

Efficiency requirements are design constraints; efficiency per se is not a design goal. The idea would be to get to a design that is simple, maintainable and flexible within the constraints imposed by efficiency needs.

So, I'd suggest: go ahead with that for the individual distinct functions. Perhaps with a switch/case on the function id instead of a sequence of if/ else ifs. Profile the code, measure its performance, and leave it at that if the performance is acceptable.

vijayan121 1,152 Posting Virtuoso

Templating allows me to fill that vector with anything, not just classes derived from Node, which could screw things up. As such, this seems like a sloppy and potentially error-prone workaround.

Use SFINAE to restrict the types to just Node or derived classes of Node.

Also, in the example, AddValues() returns an int, whereas AddBetterValues() returns a double. My Node's Print() function is virtual, as that makes sense, but there will be cases that require me to define new functions for classes derived from the Node class which have no relationship to the existing ones: If I add a vector of values to the BetterNode class for example.

My main aim was just to reduce the amount of code I have to duplicate, by putting things common to all nodes in the base Node class, and likewise for the Base class.

For AddValues() to be polymorphic, the function must have the same name (but different implementations) in different classes. To make it (compile-time) polymorphic on the result type (int in one case and double in the other), have the node and its derived classes announce the type of the result.

An elided example (using boost::enable_if and boost::type_traits):

#include <boost/utility.hpp>
#include <boost/type_traits.hpp>
#include <iostream>

using boost::is_base_of ;
using boost::enable_if ;

struct node
{
    typedef int value_type ;

    explicit node( int i ) : v(i) {}

    value_type value() const { return v ; }

    int v ;
} ;

// generalization of base<T>; declared, not defined
template< typename T, …
lytnus commented: Thanks for your help and example code :) +0
vijayan121 1,152 Posting Virtuoso

> For a novice like me, do you think a long if/else would be more easily implemented?

More easily implemented right now, yes. But 200 if/else if statements would not be pretty to maintain, and code size would be larger than that for a look up table.

> Isn't there a lot of overhead in this?
> I have ~200 external DLL functions, so I'd need to write a wrapper for each one of them.

In terms of performance overhead, 100 string comparisons are not great for performance; you could give each function a unique integral id and use much faster integer comparisons instead.

In terms of programmer overhead:

You would not need to write a wrapper for each of them; if these 200 functions fall into, say, 5 different types of function parameters, you would need just five forwarding wrappers.

An alternative approach would be to have five different look up tables, one for each function type.

As a simplified example, let's say you have just two different types of functions in all:

typedef int function_type_foo( const char* cstr ) ;
typedef int function_type_bar( int, double ) ;

With many functions of the same type:

int foo_one( const char* arg )
{ return printf( "foo_one( '%s' )\n", arg ) ; }

int foo_two( const char* arg )
{ return printf( "foo_two( '%s' )\n", arg ) ; }
// ...

int bar_one( int arg1, double arg2 )
{ return printf( …
vijayan121 1,152 Posting Virtuoso

> The problem lies in the declaration of the lookup table.
> All the functions are already defined in an external DLL, and I can't touch them.

So write wrappers of your own that call the functions in the DLL.

> The problem now is that the "WriteMemory" commands take different arguments from the "ReadMemory" commands.
> Also there are many more variations of functions to follow. So issues arise with the declaration of the Lookup Table

Have wrapper variadic functions functions which unpack the arguments using <stdarg.h> then forward the call to the external function. And be extremely careful in doing this - make sure that you have no type errors.

#include <stdio.h>
#include <assert.h>
#include <stdarg.h>

int foo( const char* arg ) // external dll function
{ return printf( "foo( '%s' )\n", arg ) ; }

int bar( int arg1, double arg2 ) // external dll function
{ return printf( "bar( %d, %f )\n", arg1, arg2 ) ; }

typedef enum function_id_ { FOO = 1, BAR = 2 } function_id ;

int foo_wrapper( function_id id, ... )
{
    typedef const char* arg_type ;
    arg_type a ;

    assert( id == FOO ) ;

    va_list arg_list ;
    va_start( arg_list, id ) ;
    a = va_arg( arg_list, arg_type ) ;
    va_end( arg_list ) ;

    return foo(a) ;
}

int bar_wrapper( function_id id, ... )
{
    typedef int arg1_type ;
    typedef double arg2_type ;
    arg1_type a ;
    arg2_type b ;

    assert( id == BAR ) …
vijayan121 1,152 Posting Virtuoso

> I want default value to be NULL so that whenever I encounter NULL
> I know that there is no implementation for this function.
> I wonder If NULL will be suitable for function that returns some type of value

There are two ways that you can simulate this behaviour.

1. Have the function return a discriminated union which could be null;
for example boost::any http://www.boost.org/doc/libs/1_42_0/doc/html/any.html
And have the default implementation return null.

2. The default implementation of the function does not return; it throws.

#include <iostream>
#include <boost/any.hpp>
#include <stdexcept>

struct not_implemented_error : std::runtime_error
{
    explicit not_implemented_error()
              : std::runtime_error( "function not implemented." ) {}
};

struct base
{
    virtual boost::any foo() { return boost::any() ; }
    virtual int bar() const
    {
        throw not_implemented_error() ;
        return 0 ; // for compilers which may complain otherwise 
    }
    protected : virtual ~base() = 0 ;
};

base::~base() {}

struct one : base // does not implement bar
{
    virtual boost::any foo() { return 100 ; }
} ;

struct two : base // does not implement foo
{
    virtual int bar() const { return 200 ; }
} ;

void test_it( base* object )
{
    boost::any result  = object->foo() ;
    if( result.empty() )
        std::cerr << "object->foo(): function not implemented\n" ;
    else
        std::cout << "object->foo() returns " << boost::any_cast<int>(result) << '\n' ;

    try
    {
        std::cout << "object->bar() returns " << object->bar() << '\n' ;
    }
    catch( const std::exception& error )
    {
        std::cerr …
vijayan121 1,152 Posting Virtuoso

> I don't want the user to be able to do "cout << someClass << endl;" But I do want to be able to do "someStringStream << someClass;"

Is that a very good idea? Consider not overloading the stream insertion operator at all, and instead just providing a member function to_string() which can be used to stringify the object.

> However when I overload the << operator in my class, it wouldn't compile.

Modify the (original) overloaded operator to:

std::stringstream& operator<<( std::stringstream& stream, const A& someobject)
{
    static_cast<std::ostream&>(stream) << someobject.num;
    return stream;
}

Why would this compile, while the earlier form (without the cast) wouldn't?
See http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19

Also modify the code in main from

A a1(7);
std::stringstream stream1;
stream1 << "Hello world! " << a1;

To

A a1(7);
std::stringstream stream1;
stream1 << "Hello world! " ;
stream1 << a1;

Why is this change required? See my earlier post.

vijayan121 1,152 Posting Virtuoso

Change std::stringstream& to std::ostream& in the overloaded operator and you would be ok.

class A 
{ 
public: 
	int num; 
	A(int x) : num(x) {}; 
	friend std::ostream& operator<<( std::ostream& stream, const A& someobject );
};

std::ostream& operator<<( std::ostream& stream, const A& someobject )
{
	stream << someobject.num;
	return stream;
};

Why is this so? Because in:

std::stringstream stream1;
stream1 << "Hello world! " << a1;

stream1 << "Hello world! " returns a std::ostream&

Ancient Dragon commented: Perfect solution :) +33
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
class Cat : public Animal{
	double weight;
 public:
	Cat(string name, double weight)
		: Animal(name), weight(weight) {this-> weight = weight;} 
	void print() const {
                Animal::print() ; // *** added *** 
		cout << "Weight = " << weight << endl;
	}
vijayan121 1,152 Posting Virtuoso

> The math problem is ((20+x) & 1234)=1000 as an example.

The equality may have no solution. For (A+x) & B == C, if any bit in B is 0 while the same bit in C is 1, there is no solution.
((20+x) & 1234)==1000 does not have a solution.

> needs to get both the highest possible value of x and the lowest possible value of x

For (A+x) & B == C, if there is a solution, the highest possible value for (A+x) is ~( B ^ C )
And the smallest possible value for (A+x) is C.

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

int main()
{
  const unsigned long A = 20UL, B = 11247UL, C = 1000UL ;
  // find min and max values for x when ( (A+x) & B ) == C

  enum { NBITS = std::numeric_limits<unsigned long>::digits } ;
  std::bitset<NBITS> b(B), c(C) ;

  // if any bit in B is 0 when the corrosponding bit in C is 1,
  // there is no solution
  for( std::size_t i = 0 ; i < NBITS ; ++i )
      if( c[i] && !b[i] )
      {
          std::cerr << "( (" << A << "+x) & " << B << ") = " << C
                    << " has no solution.\n" ;
          return 1 ;
      }

  // if there is a solution, highest possible value of (A+x) is ~( B ^ C )
  std::bitset<NBITS> max_A_plus_x = ~( b ^ c ) …
cwarn23 commented: Very good info in great detail +5
vijayan121 1,152 Posting Virtuoso
//set<*Node> neighbours;
set<Node*> neighbours;
vijayan121 1,152 Posting Virtuoso

> can we pass arrays to functions

You couldn't pass arrays to functions in C, and couldn't pass them in C++98 either.

And you won't be able to do that in C++0x too. However, in C++0x you could pass a std::initializer_list<> to a function;
that is what someFunction({{1,2},{3,4},{5,6}}); attempts to do.

#include <iostream>
#include <vector>

template< typename SEQ > void foobar( const SEQ& s )
{
    for( auto iter = s.begin() ; iter != s.end() ; ++iter )
         std::cout << *iter << ' ' ;
    std::cout << '\n' ;
}

template< typename T > void foobar( const std::initializer_list<T>& a )
{
    for( auto iter = a.begin() ; iter != a.end() ; ++iter )
         std::cout << *iter + 10 << ' ' ;
    std::cout << '\n' ;
}

struct A { int a ; int b ; } ;

struct B { B( int x ) : b(x) {} private: int b ; } ;

struct C
{
  A aa[2] ;
  B bbb[3] ;
  operator int() const { return aa[0].a ; }
} ;

int main()
{
    foobar( { 0, 1, 2, 3, 4, 5 } ) ;

    std::vector<int> seq{ 0, 1, 2, 3, 4, 5 } ;
    foobar( seq ) ;

    foobar( { C{ { {1,2}, {3,4} }, {5,6,7} },
              C{ { {7,8}, {9,0} }, {1,2,3} },
              C{ { {4,5}, {6,7} }, {8,9,0} } } ) ;
}
mike_2000_17 commented: very nice! +1
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> i am not understanding about ,Preprocessor,Compiler ,linker , Loader ,CPU

If you are just starting out, don't bother all that much about the gory details of what these different entities are right now. Just get a rough idea of what #include means, write the first hello world program, compile it and get it running, write a few more simple programs and so on. In due course of time, as you program, you would get to understand each of these.

Here is a simple tutorial: (simple, but just use it to get a rough idea; don't even try to digest all of it before you have written a few programs)
http://www.redantigua.com/c-compiler-behind-the-scenes-index.html

Something you could look at after a while: http://www.tenouk.com/ModuleW.html

Ancient Dragon commented: good advice :) +31
vijayan121 1,152 Posting Virtuoso

> which kinds of constructors can be applied during compile time ?

None in C++98; though constructors can be elided as in the case of RV optimization.

Objects constructed via the the constexpr mechanism in C++0x.
http://www2.research.att.com/~bs/C++0xFAQ.html#constexpr

vijayan121 1,152 Posting Virtuoso
class Test{
     public:
      Test()=default;
      Test(char in1,char in2):char1(in1),char2(in2){}
      char char1;
     private:
      char char2;
    };
    Test obj={'a','b'};//invalid in c++0x

It is valid in C++0x.
The final proposal is here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2640.pdf

vijayan121 1,152 Posting Virtuoso

> as far as i understand the if statment should stop evaluating if the first condition is false
> [as it is an && operation] (ie no player occupies the seat, therefore the pointer is invalid)
> so it should not try to evaluate the player->inRound bit

Your understanding is correct.So it will it be completely safe if isOccupied is set and cleared correctly.

> secondly if this is bad code can you suggest a safer way to do such a thing?

It is not bad code unless it sets isOccupied incorrectly. The only extra safety that can be provided is
a. Make sure that seat[x].player is set to zero whenever the seat is not occupied
b. Provide an extra check to verify that seat[x].player is not a null pointer before you try to access seat[x].player->inRound

vijayan121 1,152 Posting Virtuoso

> Why does C++ seem more complicated than Visual Basic?

Because it *is* more complicated than Visual Basic.

But you don't need to be extraordinarily brilliant to learn C++ and to use C++ effectively. Almost all programmers who make a genuine attempt to become good C++ programmers do succeed in their attempts. In a reasonable period of time, which is more than what is required for, say, Visual Basic. The world is complex, some problems are hard, and the tools we use to solve those difficult problems are necessarily more complex.

vijayan121 1,152 Posting Virtuoso

Write a constructor for A

class A
{
   public:
      A( /* ... */ ) : fv( length, fix_fac ) {}
   private:
     fixvec fv ;
};
vijayan121 1,152 Posting Virtuoso

> My operator+= works
> However i cant get the operator+ to work

The problem seems to be in your copy constructor; operator+ needs to make a copy.

First, verify that the copy constructor Str2::Str2( const Str2& ) is working correctly.

vijayan121 1,152 Posting Virtuoso

Specify std::ios::ate as the file mode in the constructor.

Or if the file is already open, close it and reopen with std::ios::ate as the file mode.

vijayan121 1,152 Posting Virtuoso

> error: ‘numeric_limits’ was not declared in this scope

#include <limits>

> error: ‘streamsize’ was not declared in this scope

std::streamsize

vijayan121 1,152 Posting Virtuoso

In this function

CEntityFactoryDictionary EntityFactoryDictionary( )
{
  static CEntityFactoryDictionary s_EntityFactoryDictionary;
  return s_EntityFactoryDictionary;
}

You are returning (by value) an anonymous temporary object which is a copy of the static s_EntityFactoryDictionary; you call InstallFactory on this anonymous temporary object which is immediately destroyed after that.

Modify the function as:

CEntityFactoryDictionary[B]&[/B] EntityFactoryDictionary( )
{
  static CEntityFactoryDictionary s_EntityFactoryDictionary;
  return s_EntityFactoryDictionary;
}

and you should be ok.

Caveat: I haven't looked at the rest of your code.

vijayan121 1,152 Posting Virtuoso

do you mean in findpath.h i write it like this

extern int map[]

Yes.

and in area.cc i make it like this?

int map[]

No. Like this:

int map[ MAP_WIDTH * MAP_HEIGHT ] = 
{

// 0001020304050607080910111213141516171819
	1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,   // 00
	1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,1,   // 01
	1,9,9,1,1,9,9,9,1,9,1,9,1,9,1,9,9,9,1,1,   // 02
	1,9,9,1,1,9,9,9,1,9,1,9,1,9,1,9,9,9,1,1,   // 03
	1,9,1,1,1,1,9,9,1,9,1,9,1,1,1,1,9,9,1,1,   // 04
	1,9,1,1,9,1,1,1,1,9,1,1,1,1,9,1,1,1,1,1,   // 05
	1,9,9,9,9,1,1,1,1,1,1,9,9,9,9,1,1,1,1,1,   // 06
	1,9,9,9,9,9,9,9,9,1,1,1,9,9,9,9,9,9,9,1,   // 07
	1,9,1,1,1,1,1,1,1,1,1,9,1,1,1,1,1,1,1,1,   // 08
	1,9,1,9,9,9,9,9,9,9,1,1,9,9,9,9,9,9,9,1,   // 09
	1,9,1,1,1,1,9,1,1,9,1,1,1,1,1,1,1,1,1,1,   // 10
	1,9,9,9,9,9,1,9,1,9,1,9,9,9,9,9,1,1,1,1,   // 11
	1,9,1,9,1,9,9,9,1,9,1,9,1,9,1,9,9,9,1,1,   // 12
	1,9,1,9,1,9,9,9,1,9,1,9,1,9,1,9,9,9,1,1,   // 13
	1,9,1,1,1,1,9,9,1,9,1,9,1,1,1,1,9,9,1,1,   // 14
	1,9,1,1,9,1,1,1,1,9,1,1,1,1,9,1,1,1,1,1,   // 15
	1,9,9,9,9,1,1,1,1,1,1,9,9,9,9,1,1,1,1,1,   // 16
	1,1,9,9,9,9,9,9,9,1,1,1,9,9,9,1,9,9,9,9,   // 17
	1,9,1,1,1,1,1,1,1,1,1,9,1,1,1,1,1,1,1,1,   // 18
	1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,   // 19

};
vijayan121 1,152 Posting Virtuoso

Instead of defining it here, as

int map[ MAP_WIDTH * MAP_HEIGHT ] =
{
   // ...
};

Just declare it in this file

extern int map[] ;

(And then define it in the implementation file of area, eg. area.cc)

vijayan121 1,152 Posting Virtuoso

1. Declare each template friend function before the definition of template class. (#include of the header, as you have will do).

2. Add <> in the friend declarations.

template <class T> class UList ;

template <typename T > void sort( UList<T>& ) ;

template <typename T >
std::ostream& operator << ( std::ostream&, const UList<T>& ) ;


template < typename T >  class UList
{
  public:

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

    friend void sort [b]<>[/b] ( UList<T>& ) ;
    
    // ...
} ;

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