vijayan121 1,152 Posting Virtuoso

See the posts by arkoenig (towards the end) in this thread:
http://www.daniweb.com/software-development/cpp/threads/360216/c-value-initialization

vijayan121 1,152 Posting Virtuoso

while const int may not even be given storage because the compiler may just treat it as if it were a macro by inserting its value wherever it is used.

Yes, an object of type const int need not be stored anywhere.

But then, the same is also true of any object, even modifiable objects.

If we have int m = 23 ; m is an lvalue, and its adress can be taken: int* p = &m ; p will not be equal to the nullptr and p will not compare equal to a pointer to any object other than m; *p will alias m. All these are requirements of a conforming C++ implementatrion. That m should be actually stored somewhere is not.

The semantic descriptions in this International Standard defne a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine.
Foot note: This provision is sometimes called the 'as-if' rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program....

Consequently:

Under the 'as-if' rule an implementation is allowed to store two objects at the same machine address …

vijayan121 1,152 Posting Virtuoso

The point of the exercise is to use list throughout rather than vector.

Yes; the point of the exercise is to understand the difference between using a sequence container like std::vector<> that provides random access to its values and one like std::list<> that does not.

double median( list<double> vec )
{
    typedef list<double>::size_type vec_sz ;
    vec_sz size = vec.size() ;
    if(size==0) throw domain_error("median of an empty list");

    // std::list<> does not provide random access to the values
    // std::list<>::iterator is not a random_access_iterator
    // we can't use std::sort() which requires random acccess iterators
    // http://en.cppreference.com/w/cpp/algorithm/sort
    // instead use the member function list<>::sort
    // http://en.cppreference.com/w/cpp/container/list/sort

    // sort(vec.begin(),vec.end());
    vec.sort() ;

    vec_sz mid=size/2;

    // std::list<> does not provide random access;
    // it does not have a subscript operator
    // we have to iterate linearly using its bidirectional iterator
    // keeping a count of the position and keeping track of the previous value

    /*
    for(list<double>::const_iterator it=vec.begin(); it!=vec.end(); ++it)   // Start of "list" median calculation
        {
            if(it == mid)
            {
                return size%2==0 ? (vec[*it]+vec[*it-1])/2 : vec[*it];
            }
        }
    */

    list<double>::size_type position = 0 ;
    double previous ;
    for( list<double>::iterator iter = vec.begin() ; iter != vec.end() ; ++iter )
    {
        if( position == mid ) return size%2==0 ? ( previous + *iter ) / 2 : *iter ;
        previous = *iter ;
        ++position ;
    }
}

If you have a current (C++11) compiler:

double median( list<double> seq )
{
    auto size = seq.size() ;
    if(size==0) throw …
vijayan121 1,152 Posting Virtuoso

Use a library to do this. libcurl would be the default choice. http://curl.haxx.se/libcurl/

Sample source code: http://curl.haxx.se/libcurl/c/ftpget.html

Tutorial: http://curl.haxx.se/libcurl/c/libcurl-tutorial.html

vijayan121 1,152 Posting Virtuoso

However I am aware of the .h/.cpp model and never bought into it: instead I only use cpp file and I have a master file that include them all in a way (alas manually!)to avoid any circularity of duplication. By using pre-compiled headers (the headers referring to .cpp files) I have not experienced any problem of slow build).

I'm not sure that I clearly understand what you are trying to say. But I'm quite alarmed by what I think you are driving at.

The seperate compilation model is fundamental to any reasonably large C++ software development. And that is founded on the idea of header files specifying the interfaces. This is an old book, written even before the 1998 C++ standard - and its age shows at several places. But I would still consider it mandatory reading for anyone aspiring to be a serious C++ programmer:
http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620
See if you can get your hands on a copy; it would clarify a lot of things that you have asked about.

1) List all the files in a directory that contains the functions definitions required by each function of a specific cpp file, outputing the files and functions.
2) List all the files in a directory that use each function definition of a specific cpp file, outputing the files and functions.

Perhaps you could start by reading:
http://www.ibm.com/developerworks/linux/tutorials/l-gnutex/index.html

4) create a tree to help me view the entire structure …

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

So,what should I do to solve this problem?

Write your own TRACE().

#include <cstdarg>
#include <cstdio>
#include <windows.h>
#include <iostream>

void TRACE( const char* format, ... )
{
    va_list args ;
    va_start( args, format ) ;

    enum { MAX_MESSAGE_SIZE = 4192 } ;
    char msg[ MAX_MESSAGE_SIZE ] ;
    std::vsnprintf( msg, MAX_MESSAGE_SIZE, format, args ) ;

    va_end(args) ;

    if( ::IsDebuggerPresent() ) ::OutputDebugStringA(msg) ;
    else std::clog << "DEBUG => " << msg ;
}

int main()
{
    TRACE( "test: (%+8.*d) <%#.3X> {%#6.3f} [%6.*s]\n", 4, 10, 200, 1.0, 4, "abcdef" ) ;
}
vijayan121 1,152 Posting Virtuoso

> However, it seems you'd have to make a 'lookup' map for every function you want to call?

Yes.

> Also, since the template parameter of image (e.g. image<int>) matches exactly the
> template parameter of the function (e.g. get_it<int>), is there not a way
> to make that map automatically without explicitly listing the types?

There is a way to make that map automatically with the help of the preprocessor; but you have to at least specify the types involved.

The Boost Preprocessor library would be handy. Create a list of the types involved.
For example, ( int, ( double, ( short, BOOST_PP_NIL ) ) ) and then use a repetition construct like BOOST_PP_LIST_FOR_EACH

vijayan121 1,152 Posting Virtuoso
int otherFunc(void)
{
  float foo = .5f;
  //assume widget has been created
  g_signal_connect(G_OBJECT(widget), "clicked", G_CALLBACK(kitty), (gpointer)&foo);
}

Wouldn't this foo be destroyed by the time the event handler kitty is called?

Also, do read up on comparing floating point values. http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

vijayan121 1,152 Posting Virtuoso

> Of course I could add pure virtual functions in ImageBase and implement them in Image,
> but then I will be using a modified version of the library, which is huge headaches for users.
> Is there a way to do this without touching ImageBase?

If the only issue is with not modifying image_base , add an interface class between image_base and image<>

struct image_base { virtual ~image_base() {} /* ... */ } ;

struct basic_image : image_base { virtual int get_it() = 0 ; } ;

template< typename T > struct image :  basic_image { virtual int get_it() override { return sizeof(T) ; } } ;

int main()
{
    std::vector< basic_image* > seq = { new image<int>(), new image<double>(), new image<int>() } ;
    for( auto& p : seq ) std::cout << p->get_it() << '\n' ;
}

Or if the std::vector< image_base* > must itself be exposed to the users,

int main()
{
    std::vector< image_base* > seq = { new image<int>(), new image<double>(), new image<int>() } ;
    for( auto& p : seq ) std::cout << dynamic_cast<basic_image*>(p)->get_it() << '\n' ;
}

If modification to image<T> is also taboo, you have to simulate dynamic dispatch programmatically.

struct image_base { virtual ~image_base() {} /* ... */ } ;

template< typename T > struct image :  image_base { int get_it() { return sizeof(T) ; } } ;

template< typename T > int get_it( image_base* p ) { return dynamic_cast< image<T>* >(p)->get_it() ; }

std::unordered_map< std::type_index, std::function< …
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> Hm, I thought that was what I wanted, but that requires the POD type (inner template parameter) to be passed implicitly.
> What about this:

In the function (btw, it is an overload, not a specialization)

// Handles MyClass<int>, MyClass<float>, MyClass<anything>
template <typename T>
void Output( const MyClass<T>& object)
{
  std::cout << "Special " << std::endl;
}

The type of object is (a reference to const) MyClass<T> And the template parameter is T (not MyClass<T>).

int main()
{
  MyClass<double> myClass;
  
  // void Output( const MyClass<T>& object) selected by deduction with partial ordering
  Output(myClass) ; 
  
  // error: T is explicitly specified to be MyClass<double>. Therefore, asks for
  // an instantiation of the template with an argument of type MyClass< MyClass<double> >
  Output<MyClass<double> >(myClass);
  
  // fine: T is explicitly specified to be double, type of myClass is MyClass<double>
  // void Output( const MyClass<T>& object) selected by partial ordering
  Output<double>(myClass) ; 
}
vijayan121 1,152 Posting Virtuoso

Native support for rtti in C++ is minimal; type-safe down and cross casts and a run-time type identifier (which apply to only polymorphic types). This is woefully inadequate to implement an architecture using the reflection pattern.
http://www.vico.org/pages/PatronsDisseny/Pattern%20Reflection/index.html

Since the language is statically typed, programs are not run under an interpreter (they run on real machines, not virtual machines), and often performance is important, the preferred mechanism in C++ is to use reflection at compile-time rather than run-time (template metaprogramming). The standard library has <typetraits>, and it is possible to extend the reflection facility - for example, the Type Traits Introspection library (boost sandbox) http://svn.boost.org/svn/boost/sandbox/tti/libs/tti/doc/html/index.html

If run-time reflection is what is required, there are two canonical approaches:

1. A meta Compiler that parses normal C++ code and generates code and meta information needed for reflection.
Qt's Meta-Object Compiler: http://developer.qt.nokia.com/doc/qt-4.8/moc.html
Cern rellex: http://root.cern.ch/drupal/content/reflex
XCppRefl library: http://www.extreme.indiana.edu/reflcpp/

2. A purely programmatic approch with library support to make meta information for
reflection available. For example, Helium (C++ game engine toolkit) uses this technique.
See http://www.gamasutra.com/view/feature/6379/sponsored_feature_behind_the_.php

vijayan121 1,152 Posting Virtuoso

This would suffice:

template< typename T > void foo( const T& t ) ;

template< typename T > void foo( const MyClass<T>& mc ) ;

The partial ordering of templates involved (that is taken into account in the deduction process) would make the second template be preferred over the first for objects of type MyClass<T>.

daviddoria commented: Thanks for several very helpful answers! +12
vijayan121 1,152 Posting Virtuoso

If the sequence of characters in the input stream is valid (a sequence that could have been written out during output), consume all the valid characters and update the object to reflect the new values

Else leave the object unchanged and set the stream to a failed state.

With this stream output operator

std::ostream& operator<< ( std::ostream& stm, const Complex& c )
{ return stm << c.real << std::showpos << c.imaginary << 'i' ; }

The corresponding input operator would be something like:

std::istream& operator>> ( std::istream& stm, Complex& c )
{
    int real;
    int imaginary ;

    if( ( stm >> real >> imaginary ) && ( stm.get() == 'i' ) )
    {
        // successful; put values in the complex object
        c.real = real ;
        c.imaginary = imaginary ;
    }

    else // set the stream to a failed state
           stm.setstate( std::ios::failbit ) ;

    return stm ;
}
vijayan121 1,152 Posting Virtuoso

The IS specifies that a predicate should not assume that the dereferenced iterator yields a non-const object. Arguments should therefore be taken by reference-to-const or by value.

The IS also specifies that algorithms that take function objects as arguments are permitted to copy those function objects. So in most cases, the overloaded function call operator would be a const member function.

struct S { int v ; } ;

struct binary_predicate
{
  bool operator() ( const S& a, const S& b ) const
  { return a.v < b.v ; }
};

If the predicate holds mutable state, it should be suitably wrapped (so that object identity is maintained). For example:

struct S { int v ; } ;

struct predicate_with_state
{
  explicit predicate_with_state() : num_compares(0) {}

  bool operator() ( const S& a, const S& b ) // not const
  { ++num_compares ; return a.v < b.v ; }

  int num_compares ;
};

int main()
{
   std::vector<S> seq = { {6}, {4}, {9}, {1}, {4} } ;
   predicate_with_state predicate ;

   // wrap the predicate in a std::reference_wrapper<>
   std::sort( seq.begin(), seq.end(), std::ref(predicate) ) ;
   std::cout << predicate.num_compares << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

> Is it possible to write a c++ compiler in c++ ?

The first C++ compiler was written in C++. http://www2.research.att.com/~bs/bs_faq.html#bootstrapping

Clang is written in pure C++; with heavy use of C++ facilities (like STL). http://clang.llvm.org/ Pretty well-written code too, IMHO.

mike_2000_17 commented: good to know! +14
vijayan121 1,152 Posting Virtuoso

> talk with an attorney who has some knowledge of intellectual property issues.

+1

vijayan121 1,152 Posting Virtuoso

Build the program from within the CodeBlocks IDE.

Start the command line interpreter (Start Menu -> Run... -> cmd on Windows XP ), switch to the directory which contains the executable (typically <Project Directory>\bin\Debug) and run it from the command prompt.
For example: > test.exe how now brown cow

Srinivas0 commented: clear explanation on command line parameters +2
vijayan121 1,152 Posting Virtuoso

"The most effective way to increase your knowledge is to try new problems in a controlled way. Pick one aspect of C++ that you haven't understood before and write a program that, aside from using that one aspect, uses only things that you have already mastered. Then do what it takes to understand what your program is doing - and why."
- Andrew Koenig and Barabara Moo in 'Ruminations on C++'.

So write a small program; something like this:

#include <iostream>

int main( int argc, char* argv[] )
{
    std::cout << "#arguments (argc): " << argc << '\n' ;
    for( int i=0 ; i<argc ; ++i )
        std::cout << "argument #" << i << " (argv[" << i << "]): " << argv[i] << '\n' ;
}

The run it from the command line with different command lines, look at the output and reason about it. For example, with a program called test:

> ./test
> ./test one two three four
> ./test -one -two=2 three,four

If you are just into arrays, have read something about at, to deepen your understanding write a small program:

#include <iostream>

int main( int argc, char* argv[] )
{
    enum { N = 4 } ;
    short array[N] = { 0, 1, 2, 3 } ;
    std::cout << "#elemebts: " << N << '\n'
              << "size of an element: " << sizeof( array[0] ) << '\n'
              << "size of array: " << sizeof(array) << '\n' ;

    for( int i …
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

sum+=(1/factorial(i)) ; Is integer division ok here?

A more efficient way to sum up this series would be to use the recurrence relation between successive terms.
1/1! + 1/3! + 1/5! + ... = a<0> + a<1> + a<2> + ...
a<0> = 1 ; a<1> = a<0> / (2*3), a<2> = a<1> / (4*5)
etc.
In general, we have the recurrence relation: a<i> = a<i-1> / ( (i*2) * (i*2+1) )

double sum = 1.0 ;
double term = 1.0 ;
for i in [1,n-1]
    compute and set new value of term using the recurrence relation
    add term to sum
end for
vijayan121 1,152 Posting Virtuoso

> for this to work the base class, here GUIComponent, must have a virtual function -
> since mine doesn't need it, I just shut down the error with ...

You need a virtual destructor; C++ requires that a class having a virtual function must have a virtual destructor. Even if there was no dynamic_cast and no other virtual functions, you would still require a virtual destructor if you do something like this:

std::vector<GUIComponent*> components ;
components.push_back( new TextLabel( /*...*/ ) ) ; // etc

// use the vector
// ...

// finaly clean up
// the correct destructor (and operator delete) must be called here.
for( component* c : components ) delete c ;

Consider using smart pointers instead of raw pointers whenever clean up is required; for instance if GUIComponent objects were dynamically allocated with new.

std::vector< std::unique_ptr<GUIComponent> > or std::vector< std::shared_ptr<GUIComponent> > would take care of resource management. See:
http://www.devx.com/cplus/10MinuteSolution/28347/0/page/1
http://www.devx.com/cplus/10MinuteSolution/39071/1954

Smart pointers are handy whenever acquisition and release of resources are an issue - for example when using a C-library (may be SDL) with low-level facilities (sandwich functions) for resource management. For example:

void function( /*...*/ ) // pseudocode
{
    // ... ;

    std::shared_ptr<std::FILE> file( std::fopen( __FILE__, "r" ), std::fclose ) ;
    // the destructor of shared_ptr will call std::fclose

    // ...

    foo( /* ... */ ) ; // safe evn if foo throws; file will be closed

    // ...

    if( nothing_more_2b_done ) return ; // …
vijayan121 1,152 Posting Virtuoso

"Another effective technique is to explain your code to someone else. This will often cause you to explain the bug to yourself. Sometimes it takes no more than a few sentences, followed by an embarrassed ``Never mind, I see what's wrong. Sorry to bother you.'' This works remarkably well; you can even use non-programmers as listeners. One university computer center kept a teddy bear near the help desk. Students with mysterious bugs were required to explain them to the bear before they could speak to a human counselor."
- Brian W. Kernighan and Rob Pike in 'The Practice of Programming'

vijayan121 1,152 Posting Virtuoso

> Assuming the OP doesn't know anything about sets or containers other than arrays and that there are 5 balls and 5 students then this becomes a learning situation for using loops, arrays, conditionals, flags and generating random values.
> Basicaly: Declare an array of 5 ints. . check the array of ints ...

Implementing a Fisher–Yates shuffle http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle would give an equivalent learning situation as far as syntactical constructs are concerned. It would also teach something about algorithms - about looking for a more elegant and efficient solution to a programming problem than what the obvious brute force approach suggests.

vijayan121 1,152 Posting Virtuoso

> if you could explain a bit i would really appreciate it.

Star by reading http://www.learncpp.com/cpp-tutorial/135-stream-states-and-input-validation/
and http://latedev.wordpress.com/2011/11/16/c-stringstreams/

Google would throw up many more links.

vijayan121 1,152 Posting Virtuoso

> s this legal? (For example, can I set a GUIComponent as the return of a function and instead return a subclass?)

Yes. For example:

GUIComponent* getComponent() { return new TextLabel( /* ... */ )

is fine, provided TextLabel is a derived class of GUIComponent.


> Why is the compiler complaining?

The compile-time type of the result of the function is a pointer to GUIComponent (though the run-time of the pointed object might be TextLabel). And the compiler cannot see a member-function getFont() in GUIComponent.


> What would work?

A simple way would be to perform a type-safe run-time down-cast to TextLabel and call getFont() on the result of the cast. For example:

GUIComponent* gui_component = guiList[0]->getComponent(1) ;

TextLabel* text_label = dynamic_cast<TextLabel*>(gui_component) ;

if( text_label != nullptr ) 
{
   // use text_label
   auto font = text_label->getFont() ;
   // etc
}
else
{
   // this component is not a TextLabel 
}

See: http://www.bogotobogo.com/cplusplus/dynamic_cast.php

epicbeast9022 commented: Detailed, correct response! +1
vijayan121 1,152 Posting Virtuoso

In lines 90-93, change

Decorator ( Switch * sw ) : swit ( *sw )
    {
        swit = sw;
    }

To

Decorator ( Switch * sw ) : swit ( sw ) // initialize the [B]pointer[/B] swit with sw
{}
vijayan121 1,152 Posting Virtuoso

N students to be given a different random ball each from a population of M balls.

a. M is not much larger than N (for example 100 balls and 50 studenta):
Generate a random permutation of the M balls (std::random_shuffle()) and assign the first ball in the permutation to the first student, the second ball to the second student and so on for the N students.

b. M is much larger than N (for example 1000000 balls and 50 studenta):
Choose a random ball for each student, storing the chosen balls in a hash table (std::unordered_set<>) and reject duplicate choices.

c. M is not known before hand (for example, one ball per line to be read from a file with an unknown number of lines)
1. Create a sample of N balls from the first N lines.
2. For eack ball in line k in lines [ n+1, n+2, n+3, ... ]) after that, with probability k/n let the kth ball replace a random ball in the
sample. At the end, allot balls from the sample to the students.
See: http://www.stats.uwo.ca/faculty/aim/vita/pdf/McLeod83.pdf

vijayan121 1,152 Posting Virtuoso

Enable ISO C++ conformance (eg. --std=c++0x -pedantic) and warning messages (eg. -Wall).

char * s = "hello world";

would have made the compiler emit a diagnostic - something like
"warning: deprecated conversion from string constant to char*".

vijayan121 1,152 Posting Virtuoso

You have not opened the stream successfully - the FILE* pointer was NULL at the time you did an fseek().

Verify that fopen() returned a non-NULL pointer. (Perhaps you are using a relative path to file which is no longer correct for the project copied into a different directory).

vijayan121 1,152 Posting Virtuoso

ntdll.dll etc. are system library files; the PDB files for these are required only if you want to debug system library function calls. You can safely ignore these warnings.

You might want to add a line so that the program would wait for an input at the end:

int main()
{
	std::cout << "Hello world!\n";
        std::cin.get() ;
}
vijayan121 1,152 Posting Virtuoso

You need to add Sally.cpp to the project.

Menu: Project->Add Files ... IIRC.

vijayan121 1,152 Posting Virtuoso

> I cant seem to find anything useful on the web except adding outside libraries for this one

With a conforming implementation, nothing more than the standard C++ library is needed. Something like this:

#include <thread>
#include <atomic>
#include <chrono>

void save_file( const std::string& path, int minutes,
                std::atomic<bool>& keep_saving /* , hashtable */ )
{
    const std::chrono::duration<int> duration( minutes * 60 ) ; // seconds
    do
    {
        std::this_thread::sleep_for(duration) ;
        // TODO: save hashtable to the file
        // NOTE: synchronized read access to the hashtable would be required.
    }
    while(keep_saving) ;
}

int main()
{
    std::string path_to_file = "whatever" ;
    std::atomic<bool> keep_saving_file(true) ;
    std::thread thread_to_save_file( save_file, path_to_file, 5, keep_saving
                                     /* , hashtable */ ) ;

    // do other stuff
    // ...

    // quit program now
    keep_saving_file.store(false) ;
    thread_to_save_file.join() ;

}

> workspace is vs2008 windows

With VS2008, there is no support for C++11 features; an external library would be required. Boost.Threads is an option; this would give the closest possible mapping to standard C++ threads. http://www.boost.org/doc/libs/1_48_0/doc/html/thread.html

vijayan121 1,152 Posting Virtuoso

Without using arrays and without using strings? That makes it interesting.
Something like a linked list would obviously work, but perhaps storing each character in the local frame of a (recursive) function would be the simplest.

#include <iostream>

void read_and_print_reverse()
{
    char c = std::cin.get() ;
    if( c != '\n' )
    {
        read_and_print_reverse() ;
        std::cout << c ;
    }
}

int main()
{
    std::cout << "enter a sentence (terminate it with a new-line): " ;
    read_and_print_reverse() ;
}
vijayan121 1,152 Posting Virtuoso

> how would i stop a user from entering a letter when they should be entering a number?

There is no really portable way of doing that. What can be done is: let the user enter any set of characters, and if those do not form a valid number, ask for input again.

This may be all that you need:

int number ;
while( !( std::cout << "number? "  && std::cin  >> number ) )
{
    std::cin.clear() ;
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ) ;
}

With this, an input of 129XY would accepeted and treated as equivalent to 129. If 129XY is to be treated as invalid input, then validating the input as a string is required.

Use std::istringstream for this; it is easier than trying to validate it character by character yourself. 567, -567, +567 are all valid; 5-67, +-567, +5+67 are not.

int get_int()
{
    int number ;
    std::string str ;
    std::cout << "number? " && std::cin >> str ;
    std::istringstream stm(str) ;
    return stm >> number && stm.eof() ? number : get_int() ;
}
vijayan121 1,152 Posting Virtuoso

> Or something purely mathematical.

A problem in combinatorics.

A sequence of N integers contains the numbers [1,N] in some random order. For example:

enum { N = 25 } ;
std::vector<int> seq ;
for( int i = 0 ; i < N ; ++i ) seq.push_back(i+1) ;
// the sequence contains N integers [ 1, 2, 3 ... N-1, N ]
std::random_shuffle( seq.begin(), seq.end() ) ; // in some random order

The tranformation of this sequence is a sequence of N integers where each element is the count of integers appearing later in the original sequence that are less than the number in that position.

std::vector<int> transform_sequence( const std::vector<int>& seq )
{
    std::vector<int> result_seq( seq.size(), 0 ) ;

    for( std::vector<int>::size_type i = 0 ; i < seq.size() ; ++i )
        for( std::vector<int>::size_type j = i+1 ; j < seq.size() ; ++j )
            if( seq[j] < seq[i] ) ++result_seq[i] ;

    return result_seq ;
}

If the original sequence is: [ 5 2 7 3 1 6 8 4 ]
The transformation of it is: [ 4 1 4 1 0 1 1 0 ]

If the original sequence is: [ 3 1 2 5 6 4 ]
The transformation of it is: [ 2 0 0 1 1 0 ]

If the original sequence is: [ 3 6 9 7 2 8 1 4 5 ]
The transformation of it is: [ 2 4 6 4 1 3 0 0 0 …

vijayan121 1,152 Posting Virtuoso

A couple of points:

1. In the dll implementation, preferrably #define BUILD_DLL prior to including the header file.

2. Writing DllMain is optional; if there is nothing special you need to do you can omit it, and the library gives a default implementation.

3. Unless your design intent is to make the DLL functionality usable by C clients, extern "C" is completely unnecessary; it limits C++ functionality. C++ features like classes, virtual functions, overloaded function names and operators, exceptions etc can be used seamlessly across DLLs. (Templates also can be used, but with some care - linking to Dlls is done at load/run time, templates provide pure compile time mechanisms).

For an example of using C++ across DLL boundaries, see: http://www.daniweb.com/software-development/cpp/threads/390349/1683141#post1683141

vijayan121 1,152 Posting Virtuoso

> While I'm inserting such entity in a std::map the code fails and makes the program crash.
> Because I can suppose it's a error from one of my class

The crash doesn't seem have anything to do with inserting into a std::map<> per se.

a. in void EntityManager::RegisterEntity( BaseGameEntity* NewEntity )
validate that the pointer is not a nullptr, and then check the result of calling NewEntity->ID() on it.

b. If that gives a problem, write a simple console program to use as a test frame. For example,

#include <map>
#include <iostream>

struct BaseEntity
{
    virtual ~BaseEntity() {}
    virtual int ID() const = 0 ;
};

struct BattleEntity : BaseEntity
{
    virtual int ID() const /* override */
    {
        static int id = 100 ;
        return id += 7 ;
    }
} ;

std::map< int, BaseEntity* > map ;

void test_insert( BaseEntity* p )
{
    int id = p->ID() ;
    std::cout << "inserting object at: " << p << " with id: " << id << " ... " ;
    auto result = map.insert( std::make_pair( id, p ) ) ;
    if( result.second) std::cout << "inserted.\n" ;
}

int main()
{
    for( int i=0 ; i<10 ; ++i ) test_insert( new BattleEntity() ) ;

    for( const auto& pair : map )
        std::cout << pair.first << ' ' << pair.second << '\n' ;
}

Compile it and run it.
Then substitute your actual base class for BaseEntity and test it again.
Then substitute …

vijayan121 1,152 Posting Virtuoso

> I was wondering if anyone has some good examples of running python functions and scripts
> within C++ using the Python C API.

Python documentation has a simple example: http://docs.python.org/extending/embedding.html
Another simple example: http://code.google.com/p/kanghtta/source/browse/trunk/Python/Demo/embed/demo.c?r=16
Somewhat more involved: http://www.codeproject.com/KB/cpp/embedpython_1.aspx


> What are some ways to use python in C++ programs,
> such as calling python functions from C++ and calling C++ functions from python?

Instead of using the somewhat low level Python C API, you could use a library that wraps it and provides more functionality. For example:
http://www.boost.org/doc/libs/1_48_0/libs/python/doc/
http://www.swig.org/

vijayan121 1,152 Posting Virtuoso

> 1st line defines array_type[N] as a data type which creates array of objects of person structure?
array_type is the type, it is an alias for an array of N persons.

> 2nd line defines data type pointer_to_array_type which will create pointers to objects of structure person?
No. The type pointer_to_array_type is a pointer to an array of N persons.

> 3rd line defines data type pointer_to_pointer_type which will create pointers to pointers to objects of structure person?
No. The type pointer_to_pointer_type is a pointer to a pointer_to_array_type

Try this: (demangling is g++ specific)

#include <cxxabi.h>
#include <typeinfo>
#include <iostream>

template< typename T > void print_demangled_type_name()
{
    enum { BUFFSZ = 2048 } ;
    char temp[ BUFFSZ ] ;
    std::size_t sz = BUFFSZ ;
    int status ;
    __cxxabiv1::__cxa_demangle( typeid(T).name(), temp, &sz, &status ) ;
    std::cout << ( status==0 ? temp : "__cxa_demangle error" ) << '\n' ;
}

template< typename T > void print_demangled_type_name( const T& t )
{  print_demangled_type_name<T>() ; }


struct person{ int number ; } ;

int main()
{
   enum { N = 3 } ;
   typedef person array_type[N] ;

   array_type a ;
   person b[N] ; // b is of the same type as a
   print_demangled_type_name<array_type>() ; // prints: person[3]
   print_demangled_type_name(a) ; // prints: person[3]
   print_demangled_type_name(b) ; // prints: person[3]

   typedef array_type* pointer_to_array_type ;
   pointer_to_array_type c = &a ;
   person (*d)[N] = &b ; // d is of the same type as c
   print_demangled_type_name<pointer_to_array_type>() ; // prints: person (*) [3]
   print_demangled_type_name(c) …
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> I have the array of objects of structure, and wished to point to it over the pointer
> which already points to it ( pointer to pointer to array of objects. ).
> Confusing?

Using a few typedefs would help eliminate the confusion:

int main()
{
   struct person{ int number ; } ;
   enum { N = 3 } ;

   typedef person array_type[N] ;
   typedef array_type* pointer_to_array_type ;
   typedef pointer_to_array_type* pointer_to_pointer_type ;


   array_type a = { person{ 10 }, person{ 111 }, person{ 1222 } } ;
   pointer_to_array_type p = &a ;
   pointer_to_pointer_type pp = &p ;

   std::cout << a[0].number << ' '
             << (*p)[1].number << ' '
             << (**pp)[2].number << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

> In gcc 3.4.6, it gives a Warning:
> warning: this decimal constant is unsigned only in ISO C90

Ideally, use a more recent version of the compiler (ie. not older than the oldest maintained release).

For precise control over the integral type on which enums are based, use scoped enums.

// the integral type on which [B]one[/B] is based defaults to [B]int[/B]
// [B]two[/B] is based on [B]unsigned long long[/B], [B]three[/B] on [B]std::int_fast16_t[/B]
enum struct one { A = 100, B, C, D } ;
enum struct two : unsigned long long { A = 12345678987654321ULL , B, C, D } ;
enum struct three : std::int_fast16_t { A, B, C, D } ;

> And if for some magical reason I needed one bigger than unsigned long long how would I do that?

Such a large integral type would have to be simulated via a user defined type. For example:

struct big_int
{
    big_int( long long ) ;
    big_int operator* ( long long n ) const ;
    // etc
    // ...
};

The ennum would have to be simulated too:

struct big_enum
{
    static const big_int&& A ;
    static const big_int&& B ;
};

const big_int&& big_enum::A = big_int( std::numeric_limits<long long>::max() * 25 ) ;
const big_int&& big_enum::B = big_enum::A * 100 ;

Close to a scoped enum except that an enumerated value is an rvalue reference to const instead of a constexpr.

vijayan121 1,152 Posting Virtuoso

> My knowledge about C++ and programming so far is 27 youtube videos.
> It took me 1,5 hours to figure out and write this

Pretty good first effort, I would say. Well done!

Relying on youtube videos alone might not be a good idea; get a text book too.

'Accelerated C++' by Koenig and Moo, for instance. I like it because it teaches C++ from the outset (rather than how to compile C code using a C++ compiler). http://www.acceleratedcpp.com/

> Look how easy a nonrecursive solution is:

Depends on who is doing the looking. A lisper would say: 'Look how easy a recursive solution is'.

> "2 lines fewer... (3 if you formatted better)

Really?

int factorial_recursive( int n )
{
    return n==1 ? 1 : n * factorial_recursive(n-1) ;
}

int factorial_iterative( int n )
{
    int result = 1 ;
    for( int i = 2 ; i <= n ; ++i ) result *= i ;
    return result ;
}

Depends on who writes the code; and how it is written.

> And not a wasting O(n) memory as well as n calls and returns. "
> Better? :-P

Not any better; while being more pompous, it is still based on the same naive assumption that it is the C++ source code that gets executed directly at run time.

I just tried to actually verify just how wasteful the recursive version could …

vijayan121 1,152 Posting Virtuoso

> well, I posts this because when I search internet for the difference between for and while,
> many people say it work the same and tell that the only difference is the form.

These two are equivalent:

for( int i = 0 ; i < 10 ; ++i ) {}

{ int i = 0 ; while( i < 10 ) { ++i ; } }
"The for statement
[B]for( for-init-statement  condition ; expression ) statement[/B]

is equivalent to
[B]{
    for-init-statement 
    while( condition )  
    {
      statement 
      expression ;
    }
}[/B]

except that 
a. names declared in the for-init-statement are in the same declarative-region as those declared in the condition, 
b. a continue in statement (not enclosed in another iteration statement) will execute expression before re-evaluating condition." - [B]IS[/B]
vijayan121 1,152 Posting Virtuoso

> It has no effect

For standard types, a unary + always yields an r-value.

unsigned short s = 8 ;
unsigned short& r = s ; // s is an l-value
unsigned short&& rvr = +s ; // +s yiels an r-value

For standard types, a A unary + performs a promotion where applicable.

unsigned short s = 8 ;
auto x = s ; // type of x is unsigned short
auto y = +s ; // type of y is signed int
    //(unsigned int if int cannot represent the full range of unsigned short)

char c = 'A' ;
std::cout << c << ' ' << +c << '\n'

For user-defined types, the overloaded unary + operator could do anything one pleases.

#include <iostream>
#include <string>
#include <boost/xpressive/xpressive.hpp>

using namespace boost::xpressive ;

void foo( const std::string& str, const sregex& re )
{
    sregex_iterator iter( str.begin(), str.end(), re ), end ;
    for( ; iter != end ; ++iter ) std::cout << '[' << (*iter)[0] << "] " ;
    std::cout << '\n' ;
}

int main()
{
    std::string str = "abcd1234efgh789ij" ;

    foo( str, _d ) ; // prints 7 matches:  [1] [2] [3] [4] [7] [8] [9]

    foo( str, +_d ) ; // prints 2 matches: [1234] [789]
}
vijayan121 1,152 Posting Virtuoso

> I don't understand the need for "std::string::size_type i = 0".
> Please explain.

std::string::size_type is an alias (a typedef) for some unsigned integral type that is sufficiently large to represent the number of chars in a std::string, no matter how long the string is. An int need not be able to do that on every implementation.

std::string::size_type eliminates the guesswork involved in choosing a suitable integral type to represent the position of a char in a std::string; using it allows us to write code that is portable across implementations.

> I have tried your code but it didn't work.

That came as a surprise to me; so I've just tried compiling and running the code. All three versions of strand_to_codons() work as expected. (With a conforming compiler, of course.)

vijayan121 1,152 Posting Virtuoso

For Spirit to be able to parse data directly into a class/struct/union, a fusion adapter is required.
See: http://www.boost.org/doc/libs/1_48_0/libs/spirit/doc/html/spirit/qi/tutorials/employee___parsing_into_structs.html

For std::pair<> support, just: [B]#include <boost/fusion/include/std_pair.hpp>[/B] which would pull in (along with some other stuff) BOOST_FUSION_ADAPT_STRUCT( std::pair, ( std::string, first ), ( std::string, second ) ) ;

vijayan121 1,152 Posting Virtuoso

In login.h change #ifdef LOGIN_H to #ifndef LOGIN_H