vijayan121 1,152 Posting Virtuoso

//This doesn`t workbecause of const problem...

template <int p>    
bool FComapare (Node *lId, Node* rId) ;

Here, p must be a constant known at compile-time.

for (int i = 0;i < partNum; ++i)
{
    //This doesn`t workbecause of  const problem...
    set<Node *, bool (*)(Node*,Node*) > f(&FComapare<i>);
    m_F.push_back(f);
}

Because i is not a constant.

jonsca commented: Nice explanation +6
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

When the loop

while(getline(ErrorFile,line))
{
}

exits, the stream is in a failed/eof state. When a stream is in an error state, all operations on the stream will fail. You need to first clear the error state before you do anything more with the stream.

For example, in the following snippet,

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

int main()
{
    std::ifstream file( __FILE__, std::ios::in|std::ios::out) ;
    std::vector< std::streampos > pos ;
    std::string line ;
    pos.push_back( file.tellg() ) ;
    while( std::getline( file, line ) ) pos.push_back( file.tellg() ) ;

    file.clear() ; // clear the failed/eof state of the stream

    std::reverse( pos.begin(), pos.end() ) ;

    {
        // seek, get and print the last line
        if( std::getline( file.seekg( pos[0] ), line ) )
            std::cout << std::setw(5) << pos[0] << ": " << line << '\n' ;
        file.clear() ; // and again clear the failed/eof state of the stream

        // seek, get and print remaining lines (in reverse order)
        for( std::size_t i = 1 ; i < pos.size() ; ++i )
        {
            std::getline( file.seekg( pos[i] ), line ) ;
            std::cout << std::setw(5) << pos[i] << ": " << line << '\n' ;
        }
    }
}
////////////////////////////////////////////////////////////////////////////////

, no output will be generated if you comment out line 16.

As you are trying to read from a file being continuously appended to by another program, it would be prudent to just close the file each time you reach eof. And then reopen it just before the …

vijayan121 1,152 Posting Virtuoso

A vector of pointers?

struct student ;

struct subject
{
   // ...
   std::vector< student* > list_of_students ;
   // ...
};

struct student
{
   // ...
   std::vector< subject* > list_of_subjects ;
   // ...
};
vijayan121 1,152 Posting Virtuoso

I mean why ++, --, +, - are working? every time we use ++ or -- or any other operator does it invoke the &() operator?

Yes. There is an implicit conversion from an INT to an int& ;

void foo( INT& i )
{
   ++i ;
   // evaluates to ++ (i.operator int&()) ;
   // in effect ++i.builtin_int ; 
}

So for a non-const INT , all int operations are possible; and are applied directly on the member variable builtin_int.

For a const INT , only those int operations that are possible on an r-value are available.

See: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.12

vijayan121 1,152 Posting Virtuoso

I think we must creat every operator for this class like: +, -, *, /, %, pow(x,y),...

Just two would suffice.

struct INT
{
    INT() {}
    INT( int value ) : builtin_int(value) {}

    operator int& () { return builtin_int ; }
    operator int () const { return builtin_int ; }

    int builtin_int ;
};
vijayan121 1,152 Posting Virtuoso

The trailing const on a non-static member function means that the abstract (logical, externally visible) state of the object pointed to by this will not be changed by this member function. Where possible, the compiler enforces this rule. However, the const specifier does not promise that the physical state ("raw bits") of the object will never change.

struct mystring
{
    private:

      int len ; // number of chars in the mystring; part of it's logical state

      char* p ; // points to the (first char of) the actual chars of the mystring
                // every char in this buffer forms part of the logical state
                // if we allocate a new buffer, copy the contents of the current buffer
                // into the new buffer, and then modify p to point to the new buffer,
                // the logical state of mystring does not change
    public:

      // ... mystring member functions

      // *** compile-time error - attempt to change the const object *this
      void foo() const { ++len ; }

      // fine by the compiler - no attempt to change the member p
      // see: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.15
      // *** but it is a logical error - changes the logical state of a const object
      void bar() const { if(len>0) p[0] = 'a' ; }

      // fine  - it is ok to change a different (non-const) object
      void baz() const { mystring another ; ++another.len ; /* ... */ }

      // fine  - mutable members are never const;
      // they do not …
vijayan121 1,152 Posting Virtuoso

Does any of you guys know where I can learn C++? What's the best website you know

Perhaps you would want to consider learning to use C++ in the most effective way along with learning C++. Rather than join a whole generation of programmers who started to learn the most primitive level at which one can use C++, and then continued to program for ever at that level, I would suggest a 'top-down' approach where you learn the language, the library and learn by using these to solve programming problems.

I don't know of a web resource that teaches C++ this way; perhaps you could invest in buying one first C++ book and then look at the web for additional resources. Koenig and Moo's "Accelerated C++ - Practical Programming by Example" http://www.acceleratedcpp.com/ is a good first introduction to C++.

A good book (freely available on the web) that teaches C++ in the traditional way - starting at low-level C-like aspects and then moving on to higher abstractions - is Eckel's "Thinking in C++" http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html

Some other resources you may find useful:
"C++ Annotations" from University of Groningen http://www.icce.rug.nl/documents/cplusplus/
Informit's C++ Reference Guide http://www.informit.com/guides/content.aspx?g=cplusplus
Tutorials etc at cplusplus.com http://www.cplusplus.com/

A couple of newsgroups where people learning C++ can ask questions or seek clarifications on doubts and expect to get good answers:
alt.comp.lang.learn.c-c++ http://groups.google.com/group/alt.comp.lang.learn.c-c++/about
comp.lang.c++ http://groups.google.com/group/comp.lang.c++/about

vijayan121 1,152 Posting Virtuoso

Unix tee is a filter which reads from stdin and in addition to piping the input to stdout also copies it into a file.

In C++, we can generalize the idea to a reusable component. Create a user-defined ostream that can send its output to two output streams. tee is then just a special case; read input from stdin and send output to stdout and a std::ofstream.

#include <iostream>

template < typename CHAR_TYPE,
           typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
struct basic_teebuf : public std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE >
{
    typedef std::basic_streambuf< CHAR_TYPE, TRAITS_TYPE > streambuf_type ;
    typedef typename TRAITS_TYPE::int_type int_type ;

    basic_teebuf( streambuf_type* buff_a, streambuf_type* buff_b )
            : first(buff_a), second(buff_b) {}

    protected:
        virtual int_type overflow( int_type c )
        {
            const int_type eof = TRAITS_TYPE::eof() ;
            if( TRAITS_TYPE::eq_int_type( c, eof ) )
                return TRAITS_TYPE::not_eof(c) ;
            else
            {
                const CHAR_TYPE ch = TRAITS_TYPE::to_char_type(c) ;
                if( TRAITS_TYPE::eq_int_type( first->sputc(ch), eof ) ||
                    TRAITS_TYPE::eq_int_type( second->sputc(ch), eof ) )
                        return eof ;
                else return c ;
            }
        }

        virtual int sync()
        { return !first->pubsync() && !second->pubsync() ? 0 : -1 ; }

    private:
        streambuf_type* first ;
        streambuf_type* second ;
};

template < typename CHAR_TYPE,
           typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
struct basic_teestream : public std::basic_ostream< CHAR_TYPE, TRAITS_TYPE >
{
    typedef std::basic_ostream< CHAR_TYPE, TRAITS_TYPE > stream_type ;
    typedef basic_teebuf< CHAR_TYPE, TRAITS_TYPE > streambuff_type ;

    basic_teestream( stream_type& first, stream_type& second )
         : stream_type( &stmbuf ), stmbuf( first.rdbuf(), second.rdbuf() ) {}

    private: streambuff_type stmbuf ;
};

typedef basic_teebuf<char> teebuf ;
typedef basic_teestream<char> teestream ;

A dumbed down (no error handling, …

Nick Evan commented: You're sick. But in a good way :) +16
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

An example may help.

Code that does not use RAII:

struct M
{
    M() ; // may throw! 
    // ...
};

struct A
{
    A( const char* s, const char* path ) ;
    ~A() ; // required

    // ...
        
    private:
       char* cstr ;
       FILE* file ;
       M* ptr_m ;

       void init() ; // may throw!
};

A::A( const char* s, const char* path ) :
       cstr( new char[std::strlen(+1)] ),
       file( std::fopen( path, "r+t" ) ),
       ptr_m( new M ) // *** what happens if M::M() throws?
                      // cstr won't be deleted, file won't be closed
{
    std::strcpy( cstr, s ) ;
    init() ; // *** what happens if init() throws?
             // ptr_m and cstr won't be deleted, file won't be closed
}

A::~A()
{
    delete ptr_m ;
    std::fclose(file) ;
    delete [] cstr ;
}

// etc.

Code that uses RAII:

struct M
{
    M() ; // may throw!
    // ... 
};

struct A
{
    A( const char* s, const char* path ) ;
    // no need to write destructor

    // ...
    
    private:
       std::string str ;
       std::ifstream file ;
       std::tr1::unique_ptr<M> ptr_m ;

       void init() ; // may throw!
};

A::A( const char* s, const char* path ) :
       str(s), file( path, std::ios::in|std::ios::out ),
       ptr_m( new M ) // *** don't care if M::M() throws;
                      // destructors of file and str will be executed 
{
    init() ; // *** don't care if init() throws;
             // destructors of ptr_m, file and str will be executed 
}

// etc
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

Only half! Why?

That it is half is a clue, isn't it?
Answer: rounding error

Let f1 be a particular representable floating point number, and f2 be the next representable floating point number. If the IEEE-754 rounding method (round to nearest, ties to even) is used (as almost every current implementation does), then

f1 + delta yields f2 if delta == (f2-f1)/2

See: http://docs.sun.com/source/806-3568/ncg_goldberg.html#689

jonsca commented: Good one +5
Ancient Dragon commented: excellent :) +34
vijayan121 1,152 Posting Virtuoso

I would like to know that my result is exact or not! It is possible somehow?

See: http://docs.sun.com/source/806-3568/ncg_goldberg.html

Perhaps you should consider using a library; for example MPFR http://www.mpfr.org/

vijayan121 1,152 Posting Virtuoso
#include <boost/regex.hpp>
#include <string>
#include <boost/lexical_cast.hpp>

using namespace std;

double scrape( const std::string& base, const std::string& match )
{
    boost::regex re(match);
    boost::smatch matches;

    // while( boost::regex_search( start, base.end(), matches, re ) )
    if( boost::regex_search( base, matches, re ) )
    {
        std::string value( matches[1].first, matches[1].second );
        return boost::lexical_cast<double>(value) ;
    }
    else return 0.0 ;
}
StuXYZ commented: well spotted +3
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

Class basic_directory_iterator is an important component of the library. It provides an input iterator over the contents of a directory, with the value type being class basic_path. Typedefs directory_iterator and wdirectory_iterator are provided to cover the most common use cases.

The following function, given a directory path and a file name, recursively searches the directory and its sub-directories for the file name, returning a bool, and if successful, the path to the file that was found. The code below is extracted from a real program, slightly modified for clarity:

bool find_file( const path & dir_path,         // in this directory,
                    const std::string & file_name, // search for this name,
                    path & path_found )            // placing path here if found
    {
      if ( !exists( dir_path ) ) return false;
      directory_iterator end_itr; // default construction yields past-the-end
      for ( directory_iterator itr( dir_path );
            itr != end_itr;
            ++itr )
      {
        if ( is_directory(itr->status()) )
        {
          if ( find_file( itr->path(), file_name, path_found ) ) return true;
        }
        else if ( itr->leaf() == file_name ) // see below
        {
          path_found = itr->path();
          return true;
        }
      }
      return false;
    }

The expression itr->path().leaf() == file_name, in the line commented // see below, calls the leaf() function on the path returned by calling the path() function of the directory_entry object pointed to by the iterator. leaf() returns a string which is a copy of the last (closest to the leaf, farthest from the root) file or directory name in the path object.

In addition to leaf(), several other function …

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

There are no simple answers. http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.3

In my experience, a good function to inline is one
i. which has a stable (unlikely to change) implementation.
ii. which is frequently called (the program spends a signifanct portion of its time in calling and executing the function).
iii. which has a code size comparable to the code size required to set up the activation record and call the function.

The compiler or the linker is in no position to make a judgement about i.

Unless an implementation has a good profile-guided optimizer, and the developer profiles the unoptimized program in a production environment, and makes the profiling information available to such a compiler, it is in no position to make a judgment about ii.

In reality, determining correctly if it is beneficial to inline a function requires knowledge that the compiler or linker does not have at build-time. A function that is worthwhile to inline when running on a processor with say a 4 MB processor cache and 4 GB memory (with no other serous load other than the program in question), may be harmful to inline if
i. You take it to a machine with a 2 MB processor cache and 2 GB of memory.
ii. The same 4 MB cache / 4 GB memory machine has several other programs also running simultaneously, and making demands on memory.


In general, the rules I follow are:
i. …

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

e2 was wrong. 7.38.....

Not really; it would be something like that. 7.389056...

In 1 + x/1! + x^2/2! + X^3/3! + ..... + x^n/n! + x^(n+1)/(n+1)! + ..... ,
just as n! == (n-1)! * n , x^n == x^(n-1) * n .
We can eliminate the computation of pow() for each term.

double x ; std::cout << "x? " && std::cin >> x ;

    double err ; std::cout << "error tolerence? " && std::cin >> err ;

    double ex = 0.0 ;
    double term = 1.0 ;

    for( int n = 1 ; term > err ; ++n )
    {
        ex += term ;
        term *= x / n ;
    }
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

Choosing a pseudo random-number generator involves a trade-off between the quality of the generator and its run-time performance. A variety of generators are available in Boost (and/or TR1).
http://www.boost.org/doc/libs/1_42_0/libs/random/random-generators.html
http://www.johndcook.com/cpp_TR1_random.html

vijayan121 1,152 Posting Virtuoso

You seem to be running out of memory; verify that malloc()s return a non-NULL pointer.

vijayan121 1,152 Posting Virtuoso

> Are there any library to solve this problem?

There are many libraries:
http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic#Libraries

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

And to fix the error, make this change: hFileMap = OpenFileMapping( /*PAGE_READONLY*/ FILE_MAP_READ, true, "animationMemFileClientOut");

vijayan121 1,152 Posting Virtuoso

> is there any function that gets the mode of an array without using pointers ?

No. The array subscripting operator is a binary operator on a pointer and an integral value. http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=%2Fcom.ibm.vacpp7l.doc%2Flanguage%2Fref%2Fclrc05arsubex.htm

If the distribution is unimodal and the array can be modified (sorted), a simple way to get the modal value is to sort the array and then make a single pass through it to pick up the value that occurs most often. This takes O( N log N ) time. For example:

#include <iterator>
#include <algorithm>

template< typename RAND_ACCESS_ITER >
typename std::iterator_traits<RAND_ACCESS_ITER>::value_type
        a_modal_value( RAND_ACCESS_ITER begin, RAND_ACCESS_ITER end )
{
  typedef typename std::iterator_traits<RAND_ACCESS_ITER>::value_type value_type ;

  std::sort( begin, end ) ;

  std::size_t max_freq = 0 ;
  std::size_t curr_freq = 1 ;
  value_type mode = *begin ;
  value_type previous = *begin ;

  for( ++begin ; begin != end ; ++begin )
  {
    if( *begin == previous ) ++curr_freq ;
    else
    {
      if( curr_freq > max_freq )
      {
        max_freq = curr_freq ;
        mode = previous ;
      }
      previous = *begin ;
      curr_freq = 1 ;
    }
  }
  return curr_freq > max_freq ? *(--end) : mode ;
}

If the sequence is mutimodal, or the array can not be modified, it can still be done in O( N log N ) time by using auxiliary storage for a std::map<> For example,

#include <iterator>
#include <map>

template< typename ITERATOR, typename OUTPUT_ITERATOR >
void copy_modal_values( ITERATOR begin, ITERATOR end, // input sequence
         OUTPUT_ITERATOR result ) // all modes …
vijayan121 1,152 Posting Virtuoso

Change ofstream f("test.exe", ios::out | ios::binary); To ofstream f("test.exe", ios::in | ios::out | ios::binary); The first is equivalent to the C mode string "wb", the second is equivalent to "r+b" which is what you need here.

vijayan121 1,152 Posting Virtuoso

If you have some familiarity with standard algorithms:

std::string str = " string \twith \n ws." ;
    str.erase( std::remove_copy_if( str.begin(), str.end(), str.begin(), ::isspace ),
               str.end() ) ;
vijayan121 1,152 Posting Virtuoso
#include <string>
#include <iostream>
#include <sstream>

int to_number( const std::string& word )
{
    std::istringstream stm(word) ;
    int n ;
    if( ( stm >> n ) && stm.eof() ) return n ;
    else throw 0 ;
}

int main()
{
    std::string word ;
    int counter = 1 ;
    while( std::cout << counter << "> " && std::cin >> word )
    {
        try { counter = to_number(word) ; }
        catch(int) { ++counter ; }
    }
}
vijayan121 1,152 Posting Virtuoso
char exe_name[ MAX_PATH ] ;
GetModuleFileNameA( GetModuleHandle(0), exe_name, MAX_PATH ) ;

http://msdn.microsoft.com/en-us/library/ms683197%28VS.85%29.aspx

Suzie999 commented: good help +1
vijayan121 1,152 Posting Virtuoso

> Why it always introduces in front of the name,numbers?

std::type_info::name returns an implementation defined C-style string.

For the compiler that you are using (GCC 3.x or above), you can demangle with abi::__cxa_demangle()

#include <typeinfo>
#include <string>
#include <cxxabi.h>
#include <stdexcept>
#include <cstdlib>

std::string demangled_name( const std::type_info& tinfo )
{
    int status = 0 ;
    std::size_t length = 0 ;
    char* temp = abi::__cxa_demangle( tinfo.name(), 0, &length, &status ) ;
    if( status != 0 ) throw std::runtime_error( "demangle error" ) ;
    std::string name(temp) ;
    std::free(temp) ;
    return name ;
}
vijayan121 1,152 Posting Virtuoso

To just copy a file:

#include <fstream>

bool copy_file( const char* infile, const char* outfile )
{
    std::ifstream fin( infile ) ;
    std::ofstream fout( outfile ) ;
    return fout << fin.rdbuf() ;
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> Is sorting necessary?
Yes, if you want to use std::unique

> How can I sort this type of struct?
By writing an overloaded operator bool A::operator< ( const A& that ) const and then using std::sort

vijayan121 1,152 Posting Virtuoso

> There are 16 such string type struct members? How can I sort string variables?
std::string has overloaded comparison operators. So you could sort them in the same way as ints.

> What does unique actually do? Does it remove duplicates
> or just move duplicates along with the actual variable to the end of the sequence
Just move the duplicate elements to the end of the sequence.
http://stdcxx.apache.org/doc/stdlibug/13-5.html

> I dont want to remove the duplicates but to store them in another vector
Something like this would do the trick.

void copy_duplicates( std::vector<A>& seq, std::vector<A>& duplicates  )
{
    std::sort( seq.begin(), seq.end() ) ;
    std::copy( std::unique( seq.begin(), seq.end() ), seq.end(),
               std::back_inserter(duplicates) ) ;
}

> And will this method be fast enough for using with over 60000 records???
The time taken would be O( N log N ). If 16 strings are being compared, it would take a few seconds.

vijayan121 1,152 Posting Virtuoso

If your precision is 0.01 then this error is negligible so you don't really have to worry about it. Just limit the output to 2 decimals.

Not quite. The result would depend on the magnitude of the number involved and the number of significant digits in the mantissa of the floating point representation that is used.

Try this:

std::cout << std::fixed << std::setprecision(2) ;
for( double a = 1.0 ; a < 1.0e+30 ; a *= 10.0 )
{
    double b =  a + 0.01 ;
    std::cout << a << ' ' << b << ' ' << b-a << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

Write comparison operators for operator< and operator== for the struct. eg.

struct A
{
    int x, y, z ;

    inline bool operator< ( const A& that ) const ;

    inline bool operator== ( const A& that ) const
    { return (x==that.x) && (y==that.y) && (z==that.z) ; }
};

bool A::operator< ( const A& that ) const
{
    if( x < that.x ) return true ;
    else
    {
        if( x > that.x ) return false ;
        if( y < that.y ) return true ;
        else
        {
            if( y > that.y ) return false ;
            return z < that.z ;
        }
    }
}

Use std::sort to sort the vector and then std::unique to move duplicates to the end of the sequence. Finally, use std::vector<>::erase to remove the duplicate elements from the vector.

void remove_dups( std::vector<A>& seq )
{
    std::sort( seq.begin(), seq.end() ) ;
    seq.erase( std::unique( seq.begin(), seq.end() ), seq.end() ) ;
}
vijayan121 1,152 Posting Virtuoso

In

// ...
int x = 8 ;
int y = 9 ;
auto foobar = [ &x, y ]( int a, int b ) { return x += a + b + y ; }
// ...

[ &x, y ] specifies the identifiers declared outside the lambda function that will be available to the lambda (closure). In this example, the lambda function captures x by reference and y by value ( int a, int b ) is the parameter list of the lambda function { return x += a + b + y ; } is the lambda function's body

see: http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions

vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
#include <sstream>
#include <algorithm>

int main()
{
    // read verbs from the file into a vector
    std::ifstream verbs_file( "verbs.txt" ) ;
    std::istream_iterator<std::string> begin(verbs_file), end ;
    std::vector<std::string> verb_seq( begin, end ) ;

    // get the sentence from stdin
    std::string sentence ;
    std::getline( std::cin, sentence ) ;

    // read the sentence word by word
    std::istringstream stm(sentence) ;
    std::string word ;
    while( stm >> word )
    {
        // if the word is in the sequence of verbs
        if( std::find( verb_seq.begin(), verb_seq.end(), word ) != verb_seq.end() )
        {
          std::cout << "the verb is: " << word << '\n' ;
          break ;
        }
    }
}
vijayan121 1,152 Posting Virtuoso

Use the stream manipulators std::setw and std::setfill.
http://www.cplusplus.com/reference/iostream/manipulators/setfill/

#include <iostream>
#include <iomanip>

int main()
{
    int hours = 6 ;
    int minutes = 2 ;
    std::cout << hours << ':'
              << std::setw(2) << std::setfill('0') << minutes << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

I didn't say it ought to work -- I said that I didn't immediately see a reason that it shouldn't. As it happens, I made that post before I had had my morning coffee :-)

Phew! Thank you. You had me worried for a while.

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

> I would love to integrate assembly into my programs

The assembly code that you would write is implementation dependent, and therefore non-portable.

vijayan121 1,152 Posting Virtuoso

Consider using a Patricia trie. http://en.wikipedia.org/wiki/Radix_tree

A C++ standard library compatible implementation: http://code.google.com/p/patl/

vijayan121 1,152 Posting Virtuoso

> i want to put the number of the line for each item in the second column of the array

You really need not store the line number separately; the row number of a two-dimensional array (or array-like structure) would become the implicit line number.

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

int main()
{
    // for a brief tutorial on using std::vector<>
    // see http://www.cprogramming.com/tutorial/stl/vector.html
    std::vector< std::vector<int> > vec2d ;

    std::ifstream indata( "Ayman.dat" ) ;
    if( !indata ) // file couldn't be opened
    {
        std::cerr << "Error: file could not be opened\n" ;
        return 1 ;
    }

    std::string line ;
    // To read a complete line of text into a std::string, use std::getline.
    // see: http://www.cplusplus.com/reference/string/getline/
    while( std::getline( indata, line ) ) // keep reading until end-of-file
    {
        // create an input stringstream to read ints from line
        // see: http://www.fredosaurus.com/notes-cpp/strings/stringstream.html
        std::istringstream stream(line) ;

        // create a pair of iterators to iterate over the ints in the stream
        // about iterators: http://www.mochima.com/tutorials/STL.html
        // http://www.cplusplus.com/reference/std/iterator/istream_iterator/
        std::istream_iterator<int> begin(stream), end ;

        // read the the int values in the stream into a vector, and
        // add the vector<> of ints to vec2d
        vec2d.push_back( std::vector<int>( begin, end ) ) ;
    }

    // vec2d now contains the ints from the file, number of lines is vec2d.size()
    // vec2d[0] - vector of ints from line 0, number of ints are vec2d[0].size()
    // vec2d[1] - vector of ints from …
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&, …