vijayan121 1,152 Posting Virtuoso

It appears that

a. There are going to be a very large number of DataStruct and Action objects (since the memory footprint of DataStruct is quite small).

b. DataStruct objects are added, but never removed (since the key is based on the size of the map).

In that case, using both a std::map<> and a std::set<> is unnecessary; a std::vector<> (with the key as the position in the sequence) and a std::set<> would suffice.

Something like this:

struct DataStruct
{
    double xData, yData ;
    std::vector<DataStruct>::size_type keyVal ;
    friend bool operator< ( const DataStruct& a, const DataStruct& b ) ;
};


class MapClass
{
    static std::vector<DataStruct> seq ;
    static std::set<DataStruct> set ;

    public:
        typedef std::vector<DataStruct>::size_type pos_t ;

        static pos_t AddDataStruct( const DataStruct& ds )
        {
            auto iterator = set.find( ds ) ;
            if( iterator != set.end() ) return iterator->keyVal ;
            else
            {
                pos_t pos = seq.size() ;
                seq.push_back(ds) ;
                seq.back().keyVal = pos ;
                set.insert( seq.back() ) ;
                return pos ;
            }
        }

        static const DataStruct& get( pos_t pos ) { return seq[pos] ; }
};

class Action
{
   MapClass::pos_t dataKey ;

   void do_stuff()
   {
      const DataStruct& ds = MapClass::get(dataKey) ;
      // ...
   }
};

with some additional trickery, more memory can be saved - make the value_type of the std::set<> a position in the sequence held by std::vector<>

If Datastruct objects also need to be removed as the program is running, this won't work; you could use boost::bimap<> in that case.
http://www.boost.org/doc/libs/1_47_0/libs/bimap/doc/html/index.html


       
Jsplinter commented: excellent! +3
vijayan121 1,152 Posting Virtuoso

> could I make lambda expression play the trick like above?
> so I don't have to write another functor for small cases

Boost Phoenix has polymorphic lambdas.
And once there are polymorphic lambdas with support for lazy evaluation, no extra boiler plate is required:

#include <string>
#include <iostream>
#include <boost/phoenix/core.hpp>

template< typename T, typename U, typename FN > bool foo( T a, U b, FN fn )
{ return fn(a,b) <= fn(b,a) ; }

int main()
{
    using namespace boost::phoenix::arg_names ;

    auto plus = arg1 + arg2 ; // polymorphic lambda

    int i = 7, j = 9 ;
    double d = 3.456 ;
    std::string a = "abc", b = "defghijk" ;

    std::cout << plus(i,j) << ' ' << plus(i,d) << ' ' << plus(a,b) << '\n' ;

    std::cout << std::boolalpha << foo( i, d, plus ) << '\n' ;
}

C++ lamda expressions are monomorphic (polymorphic lambdas would have given more flexibility and expressive power). AFAIK, it was concepts that required lambdas to be monomorphic. With concepts, a constrained template should be able to use only other similarly constrained templates; asking for concept checks with lazy evaluation of constraints (which polymorphic lambdas would require) would have made the life of compiler writers extremely difficult. Concepts were eventually dropped, and supporting polymorphic lambdas in the absence of concepts would have been a fairly straightforward matter; however the clear intent is to definitely have concepts in the next standard ("in maybe five years" - Stroustrup).

mike_2000_17 commented: great info! +14
vijayan121 1,152 Posting Virtuoso

> Where did you get that quote from?

A Microsoft Knowlege Base article, circa 2005

> any global or static object (non-volatile or volatile) will be flushed before a write on any volatile object.
> I am correct in thinking this?

Yes, the documentation is pretty clear - in Microsoft C++ volatile enforces acquire and release ordering for all volatile variables as well as all non-volatile variables with a static storage duration.

This is usually all that you require. However, there are situations where sequentially consistent ordering is necessary.
See: http://www.justsoftwaresolutions.co.uk/threading/memory_models_and_synchronization.html

vijayan121 1,152 Posting Virtuoso

> 1) I can`t do what I intended to do initially if I use pure C++99. It is impossible.

It is impossible to do it in portable code. And you have to accept that the code generated would be largely sub-optimal.

> I could do it with C++11. (.... I won`t bet anything that Microsoft will make it happen anytime soon,...)

Perhaps sooner than you expect; I suppose they are interested in the performance of the code generated by their compiler. Converting all the libraries to exploit C++11 will take some time though.

In the interim, Anthony Williams' JustThread library is (commercially) available. http://www.stdthread.co.uk/

> My current C++ (VS2009) allows me to do what I want, actually very easily, simply because:
> a) the keyword "volatile" meaning has been changed to a proprietary-sort of meaning

Not really 'changed'. They have just added on non-standard semantics to volatile. As has every mainstream compiler writer; each one in a different way.

The Microsoft compiler treats volatile in the manner that Java (1.5+) does - close to volatile T being treated as C++11 would treat volatile std::atomic<T>

> so that it now actually means it will flush *everything I wanted to be flushed*: any temporary variable ...

I'm not too sure of that unless it has changed after 2005. This is what the Microsoft documentation used to say:

Declaring a variable as volatile prevents the compiler from reordering references to that …

vijayan121 1,152 Posting Virtuoso

The volatile keyword was introduced at the time when C had no notion of concurrency other than time-slicing on a single processor. The notion of volatile in C++ is the same as what it is in C.

This article by Myers and Alexandrescu is instructive: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf

This is what they have to say about volatile:

One might hope that the above fully volatile-qualified code would be guaranteed by the Standard to work correctly in a multithreaded environment, but it may fail for two reasons.
First, the Standard’s constraints on observable behavior are only for an abstract machine defined by the Standard, and that abstract machine has no notion of multiple threads of execution. As a result, though the Standard prevents compilers from reordering reads and writes to volatile data within a thread, it imposes no constraints at all on such reorderings across threads. At least that’s how most compiler implementers interpret things. As a result, in practice, many compilers may generate thread-unsafe code from the source above. If your multithreaded code works properly with volatile and doesn’t work without, then either your C++ implementation carefully implemented volatile to work with threads (less likely), or you simply got lucky (more likely). Either case, your code is not portable.

And their conclusion:

Finally, DCLP and its problems in C++ and C exemplify the inherent difficulty in writing thread-safe code in a language with no notion of threading (or any other form of concurrency). Multithreading considerations are pervasive, …

vijayan121 1,152 Posting Virtuoso

> I want to ether copy it to another location

#include <fstream>

int main()
{
    std::ifstream fin( "myfile.dat", ios_base::in|std::ios_base::binary ) ;
    std::ofstream fout( "myfile.cpy", ios_base::out|std::ios_base::binary ) ;
    fout << fin.rdbuf() ;
}

> or (more likely) send it through zlib's deflate.

Simplest if you use a C++ wrapper over zlib.
For example, using the Boost Iostream library http://www.boost.org/doc/libs/1_47_0/libs/iostreams/doc/index.html

#include <fstream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/zlib.hpp>

int main()
{
    std::ifstream fin( "myfile.dat", ios_base::in|std::ios_base::binary ) ;
    std::ofstream fout( "myfile.z", ios_base::out|std::ios_base::binary ) ;

    boost::iostreams::filtering_streambuf< boost::iostreams::output > stmbuf ;
    stmbuf.push( boost::iostreams::zlib_compressor() ) ;
    stmbuf.push(fout) ;

    boost::iostreams::copy( fin, stmbuf );
}
Ancient Dragon commented: good suggestions :) +17
vijayan121 1,152 Posting Virtuoso

> any good suggestion about free, robust allocator which design for small objects?

Loki perhaps.
http://loki-lib.sourceforge.net/html/a00524.html

Also see: http://drdobbs.com/184402039

vijayan121 1,152 Posting Virtuoso

std::make_shared<> is just a wrapper over std::allocate_shared<> with the allocator defaulted to std::allocator<>.

Assuming there is a constructor A::A( int, const char*, double ) for A,

auto pa = std::make_shared<A>( 1, "hello", 22.8 ) ;

is more efficient when compared to

std::shared_ptr<A> pa( new A( 1, "hello", 22.8 ) ) ;

It requires only one memory allocation instead of two; storage for the objct and its shared reference count is allocated together.

mike_2000_17 commented: Nice! +14
vijayan121 1,152 Posting Virtuoso

Template instantiation is done at compile-time; no there is no run-time overhead for instantiating a template.

> but I am not sure how implicit function invokation works.
> I don`t think compiler will create a different function for evey datatype available
> (since there can be many different data-types in one program).

Yes. AFAIK, every implementation creates a different instantiation each time. This can lead to code bloat for template functions containing a significant amount of code; you may want to write your code in such a way that this issue is addressed.
See: http://drdobbs.com/184403053

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.9
Some what dated; in current C++, you would use std::enable_if<> and friends.

C++ requires that each template instatiation occurs exactly once in the program if it is needed, and not at all otherwise. There is also a code bloat problem if the implementation violates this rule. I haven't checked the situation with the more recent versions, but g++ used to be (and probably still is) a notorious violator.
See: http://docs.freebsd.org/info/gcc/gcc.info.Template_Instantiation.html

vijayan121 1,152 Posting Virtuoso

An external merge sort using four files, perhaps?

http://en.wikipedia.org/wiki/Merge_sort#Use_with_tape_drives

vijayan121 1,152 Posting Virtuoso

For each class, you need to have a header file x.h and an implementation file x.cpp.
Include the header file in order to use the class.

For example:

//////////// duties.h /////////////////

#ifndef DUTIES_H_INCLUDED_
#define DUTIES_H_INCLUDED_

#include <string>

class Duties
{
    public: static void submitChangeDutyRequests( const string& ) ;
};

#endif // DUTIES_H_INCLUDED_
//////////// duties.cpp //////////////////

#include "duties.h"

void Duties::submitChangeDutyRequests( const string& requests )
{
   // ...
}
////////// homepage.h /////////////////////

#ifndef HOMEPAGE_H_INCLUDED_
#define HOMEPAGE_H_INCLUDED_

#include <string>

class HomePage
{
    public: static void HsubmitChangeDutyRequests( const string& ) ;
};

#endif // HOMEPAGE_H_INCLUDED_
//////////// homepage.cpp //////////////////

#include "homepage.h"
#include "duties.h"

void HomePage::HsubmitChangeDutyRequests( const string& requests )
{
   Duties::submitChangeDutyRequests( requests ) ;
}
////////////  main.cpp ////////////////////////

#include <iostream>
#include "homepage.h"

int main()
{
    // ...
    std::string request ;
    while( std::cout << "request? " && std::getline( std::cin, request ) )
    {
        // ...
        HomePage::HsubmitChangeDutyRequests(request) ;
        // ...
    }
}
vijayan121 1,152 Posting Virtuoso

> Does anyone has a brilliant (and simple!) way to selectively control access
> by giving different rights to different friends?

I don't have anything brilliant, but using access helpers to provide selective access is reasonably simple.

class A
{
    void foo() {}
    void bar() {}

    // grant void foo_not_bar( A& ) access to foo, but not to bar
    // grant void bar_not_foo( A& ) access to bar, but not to foo

    public :
        class foo_access_helper
        {
           private: static void foo( A& a ) { a.foo() ; }
           friend void foo_not_bar( A& ) ;
        };
        friend class foo_access_helper ;

        class bar_access_helper
        {
           private: static void bar( A& a ) { a.bar() ; }
           friend void bar_not_foo( A& ) ;
        };
        friend class bar_access_helper ;
};

void foo_not_bar( A& a ) { A::foo_access_helper::foo(a) ; }

void bar_not_foo( A& a ) { A::bar_access_helper::bar(a) ; }
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

Since std::multimap<> stores the keys in an ordered manner,

#include <map>

template< typename K, typename T, typename C, typename A >
typename std::multimap<K,T,C,A>::size_type num_unique_keys( const std::multimap<K,T,C,A>& mmap )
{
    if( mmap.size() < 2U ) return mmap.size() ;

    const C& cmp = mmap.key_comp() ;
    typename std::multimap<K,T,C,A>::size_type n = 1 ;
    auto prev = mmap.begin()->first ;

    for( auto iter = mmap.begin() ; iter != mmap.end() ; ++iter )
        if( cmp( prev, iter->first ) ) { ++n ; prev = iter->first ; }

    return n ;
}

Obviously, this won't work with std::unordered_multimap<>.

alwaysLearning0 commented: cool +5
vijayan121 1,152 Posting Virtuoso

This is what TR 18015 : Technical Report on C++ Performance has to say about the costs of exception handling:

For some programs, difficulty in predicting the time needed to pass control from a throw-expression to an appropriate catch clause is a problem. This uncertainty comes from the need to destroy automatic objects and – in the “table” model – from the need to consult the table. In some systems, especially those with real-time requirements, it is important to be able to predict accurately how long operations will take. For this reason current exception handling implementations may be unsuitable for some applications. However, if the call tree can be statically determined, and the table method of EH implementation is used, it is possible to statically analyze the sequence of events necessary to transfer control from a given throw-expression to the corresponding catch clause. Each of the events could then be statically analyzed to determine their contribution to the cost, and the whole sequence of events aggregated into a single cost domain (worst-case and best-case, unbounded, indeterminate). Such analysis does not differ in principle from current time estimating methods used for non-exception code.

In short, rather than making blanket assumptions about the performance cost of throw/catch constructs, one needs to devote some time to analyzing the costs. The results would vary widely depending on both the program being analyzed and the implementation's exception-mechanism design trade-offs.

The entire report is freely available: http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf
Worth re-reading if C++ performance …

mike_2000_17 commented: Confirms what I thought! Very interesting report! +14
vijayan121 1,152 Posting Virtuoso

char thousands[] = {"", "M", "MM", "MMM", "MMMM"}; This is an error; thousands is an array of chars, not an array of c-style strings.
You need to do something like this instead. const char* thousands[] = {"", "M", "MM", "MMM", "MMMM"}; > i have one error, which is C2110: cannot add two pointers.

If you want to use the + operator to concatenate strings, use std::string instead of c-style string.

char a[100] = "abcd" ;
const char b[] = "ef" ;
a = a + b ; // *** error *** 

std::string c = "abcd" ;
c = c + b ; // fine

See: http://www.cprogramming.com/tutorial/string.html

vijayan121 1,152 Posting Virtuoso

> I am trying to compile this example http://www.boost.org/doc/libs/1_42_0/...
> and I am getting the error "/usr/local/boost_1_47_0/...

There is a version mismatch. The code for 1.47.0 would be:

BOOST_FOREACH( const std::string& name, m_modules )
{
   // pt.put( "debug.modules.module", name, true ) ;
   pt.add( "debug.modules.module", name, true ) ;
}

See: http://www.boost.org/doc/libs/1_47_0/doc/html/boost_propertytree/tutorial.html

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

> its only when the vector get reallocated in memory (due to another thread loading a different sample into it)

The memory buffer held by the vector could get reallocated.

You need to synchronize access to the vector across multiple threads.

vijayan121 1,152 Posting Virtuoso

Pete Becker's 'The C++ Standard Library Extensions: A Tutorial and Reference' has been available for some time.
http://www.amazon.com/Standard-Library-Extensions-Tutorial-Reference/dp/0321412990/ref=sr_1_1?s=books&ie=UTF8&qid=1313201008&sr=1-1

'C++ Concurrency in Action' by Anthony Williams has in-depth coverage of concurrency features in C++11.
http://www.manning.com/williams/

Scott Meyers' presentation materials on C++11 is also a useful resource.
http://www.artima.com/shop/overview_of_the_new_cpp

InformIT has a series of articles on C++0x by Danny Kalev; for example:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=254

jonsca commented: Good info, too +14
Chilton commented: Hey. Thanks a lot for the help. +3
vijayan121 1,152 Posting Virtuoso

In the boost distribution: <directoy_where_boost_has_been_unpacked>/boost_1_47_0/doc/html PDF documentation can be downloaded from sourceforge: http://sourceforge.net/projects/boost/files/boost-docs/1.47.0/


Or use wget. Something like:
> wget --mirror -p --no-parent --convert-links -P ./boostdoc http://www.boost.org/doc/libs/1_47_0/libs/libraries.htm


Note: 1_47_0 is boost version 1.47.0. Use 1_46_1 for 1.46.1 and so on.

vijayan121 1,152 Posting Virtuoso

If you are going to perform unformatted I/O, open the stream in binary mode (use std::ios_base::binary). Or else, text mode escape sequence translations will take place.

vijayan121 1,152 Posting Virtuoso

> Might I ask for an explanation of this line
> typename std::enable_if< std::is_arithmetic<T>::value, T >::type* = 0 Well, the original question was about

Only valid integer should be returned. All other input should be tossed, user should be asked again for valid integer input.

I took the liberty of generalizing that to 'Only valid number should be returned. All other input should be tossed, user should be asked again for valid numeric input.'. Where the number is any numeric (integral or real) type.

So, the template function

template< typename T = int > T number_from_stdin( ... )

should only be available for numeric types. The last parameter to the function is just a place holder with a default value to ensure that T is a numeric type.

An instance of std::is_arthmetic<T> holds true only if the type T is an arithmetic type (either an integral type or a floating point type). std::is_arithmetic<volatile int>::value is true , so an improved version of the function would be:

template< typename T = int >
T number_from_stdin(  const char* prompt = "enter a valid number, then a <newline>: ",
                      const char* emsg = "error: input is not numeric\n",
                      typename std::enable_if< std::is_arithmetic<T>::value, T >::type* = 0  )
{
    std::string str ;
    std::cout << prompt ;
    if( std::getline( std::cin, str ) )
    {
        std::istringstream stm(str) ;
        [B]typename std::remove_cv<T>::type number ;[/B]
        char trailing_crud ;
        if( ( stm >> number ) && !( stm >> std::ws >> trailing_crud ) ) return …
vijayan121 1,152 Posting Virtuoso
[B]>[/B] int number;
[B]>[/B] stm >> number;
[B]>[/B] while( stm.fail() ) ....

This kind of construct fails to check for crud remaining in the input; 567#$! would be treated as a valid number with a value of 567.

If the attempt to read a non-ws char after reading the number is successful, there was some crud left in the input line.

#include <type_traits>
#include <iostream>
#include <sstream>

template< typename T = int >
T number_from_stdin(  const char* prompt = "enter a valid number, then a <newline>: ",
                      const char* emsg = "error: input is not numeric\n",
                      typename std::enable_if< std::is_arithmetic<T>::value, T >::type* = 0  )
{
    std::string str ;
    std::cout << prompt ;
    if( std::getline( std::cin, str ) )
    {
        std::istringstream stm(str) ;
        T number ;
        char trailing_crud ;
        if( ( stm >> number ) && !( stm >> std::ws >> trailing_crud ) ) return number ;
    }
    std::cerr << emsg ;
    return number_from_stdin<T>( prompt, emsg ) ;
}
vijayan121 1,152 Posting Virtuoso

Straddling compile-time techniques and run-time techniques requires a fair amount of care. The code tends to be fairly stylized.

For this paricular example:

#include <iostream>
#include <boost/any.hpp>
#include <vector>
#include <boost/mpl/list.hpp>
#include <boost/mpl/for_each.hpp>
using namespace boost ;

struct triangle
{
    void draw() const // polymorphic across many different types 
    { std::cout << "triangle {sides:" << a << ',' << b << ',' << c << "}\n" ; }
    int a, b, c ;
} ;

struct rectangle
{
    void draw() const
    { std::cout << "rectangle {widthxheight:" << width << 'x' << height << "}\n" ; }
    int width, height ;
} ;
struct circle
{
    void draw() const { std::cout << "circle {radius:" << radius << "}\n" ; }
    int radius ;
} ;

struct draw_it
{
    explicit draw_it( const any& a ) : object(a) {}

    template< typename T > void operator() (T) const
    {
        // the argument (which is ignored) is just a place holder; a null pointer to T
        try { any_cast<T>(object)->draw() ; throw drew_it() ; }
        catch( const bad_any_cast& ) {}
    }

    struct drew_it {} ;

    private:  const any& object ; // has a pointer to the actual object to be drawn
} ;

template< typename TYPELIST, typename ITERATOR >
void draw_all( ITERATOR begin, ITERATOR end )
{
    for( ; begin != end ; ++begin )
    {
        try
        {
            mpl::for_each<TYPELIST>( draw_it(*begin) ) ;
            std::cerr << "I don't know how to draw this object\n" ;
        }
        catch( const draw_it::drew_it& ) { /* ok */ }
    } …
mrnutty commented: Another good post +13
alwaysLearning0 commented: liked it. +4
vijayan121 1,152 Posting Virtuoso

The K-means clustering algorithm computes yields K clusters, where K is given by you. You have to "tell" the algorithm beforehand how many clusters the data set should be broken up into.

A hierarchical clustering algorithm on the other hand forms successive groupings, with the number of clusters varying from from 1 to N (where N is the cardinality of the data set). Hierarchical clustering lets you choose which of the N steps gives you the most convenient number of clusters for your analysis. Ward's algorithm is a commonly used agglomerative hierarchical clustering algorithm. http://iv.slis.indiana.edu/sw/ward.html

Different clustering methods have different strengths and weaknesses. Which algorithm to use, choosing the distance metric which is most appropriate, and determining the number of clusters to specify for K-means clustering or select from hierarchical clustering are interesting problems. Discriminant function analysis is typically used for these quality measures.

Jsplinter commented: Interesting... more food for thought to digest. Thank you! +2
vijayan121 1,152 Posting Virtuoso

list is a typedef (an alias for) a pointer to a nodo_lista. typedef struct nodo_lista *list; If struct nodo_lista does have a member function insert_list(), then: (i)->primerapos[B]->[/B]insert_list(&primerapos, contador_etiquetas);

vijayan121 1,152 Posting Virtuoso

Though the standard does not say anything specific about the representation of a wchar_t, it is either strictly Unicode (UCS-2) or ISO 10646 (UCS-4) on every implementation. These two have an identical character repertoire and code points for the Basic Multilingual Plane. In practice, this will remove non-printable characters from a string.

void remove_non_printable_chars( std::wstring& wstr )
{
    // get the ctype facet for wchar_t (Unicode code points in pactice)
    typedef std::ctype< wchar_t > ctype ;
    const ctype& ct = std::use_facet<ctype>( std::locale() ) ;

    // remove non printable Unicode characters
    wstr.erase( std::remove_if( wstr.begin(), wstr.end(),
                    [&ct]( wchar_t ch ) { return !ct.is( ctype::print, ch ) ; } ),
                wstr.end() ) ;
}

Incidentally, U+0020 is a printable Unicode character.

mrnutty commented: man you know too much +13
vijayan121 1,152 Posting Virtuoso

> I know I could try getline(cin, FullName), then split it them all
> but the text did not recommend this and suggesting 3 string variables

This would be one way of doing it:

std::string FirstName, LastName ;
	std::cout << "What is your first and last name? " ;

	if( std::cin >> FirstName >> LastName >> std::skipws )
        {
            std::string MiddleName ;
	    std::cout << "What is your middle name? "
                         "enter EOF (Posix CTRL+D, Microsoft CTRL+Z) if none: " ;
	    std::cin >> MiddleName ;

            std::cout << '\n' << LastName << ", " << FirstName ;
            if( !MiddleName.empty() ) std::cout << ' ' << MiddleName ;
	    std::cout << ".\n" ;
        }
vijayan121 1,152 Posting Virtuoso

To get a random int between 0 and 31 (inclusive) using rand(), prefer something like int( 32.0 * ( rand() / (RAND_MAX+1.0) ) ) ; Or else, you would be assuming that the least significant 5 bits of the pseudo random number generated by rand() are also randomly distributed.

vijayan121 1,152 Posting Virtuoso
string parseInputString( const string& oneline ) // prefer passing by const referance
{
    // when possible, initialize objects at the point of their definition
    string::size_type index = oneline.find (' ') ;
    string firstName = oneline.substr( 0, index ) ;

    // find the next non-space character
    index = oneline.find_first_not_of( ' ', index ) ;

    string lastName ;
    if( index != string::npos ) // if there is something after the spaces
        lastName = oneline.substr( index ) ; // lastName is everything from there on

    return lastName + ", " + firstName + "." ;

}
vijayan121 1,152 Posting Virtuoso
v.assign( 1U, 4 ) ; // usually more efficient than create temporary vector and then swap
v = { 4 } ; // only in C++ 2011
vijayan121 1,152 Posting Virtuoso
typedef A::B B ;

// ...
Jsplinter commented: thanks +2
vijayan121 1,152 Posting Virtuoso

Use boost::filter_iterator, perhaps.
http://www.boost.org/doc/libs/1_46_0/libs/iterator/doc/filter_iterator.html

A trivial example:

#include <vector>
#include <algorithm>
#include <boost/iterator/filter_iterator.hpp>
#include <iostream>

int main()
{
    std::vector<int> seq = { 36, 4, 63, 21, 41, 64, 0, 35, 4, 17, 8, 33 } ;
    auto is_odd = [] ( int i ) { return i%2 != 0 ; } ;
    auto odd_begin = boost::make_filter_iterator( is_odd, seq.begin(), seq.end() ) ;
    auto odd_end = boost::make_filter_iterator( is_odd, seq.end(), seq.end() ) ;
    std::cout << "min_odd_element: " << *std::min_element( odd_begin, odd_end ) << '\n' ;
}
fandango commented: Always good to learn something new! +1
vijayan121 1,152 Posting Virtuoso

> when things mess up with template
> It can't work as the way you show me

You need to disambiguate the overload. As long as you do that, it would work - templates or no templates.

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

template < typename T > T foobar( T a, T b ) { return a+b ; }

template < typename T > T foobar( T a, T& b, T c ) { return b = a-b+c ; }

int main()
{
    // disabiguate the overloaded functions for boost::bind
    int (&int_foobar)(int,int) = foobar ;
    double (&dbl_foobar)(double,double&,double) = foobar ;

    boost::function< int(int) > f1 = boost::bind( int_foobar, _1, 23 ) ;
    std::cout << f1(99) << '\n' ;

    double b = 56.2 ;
    boost::function< double(double,double) > f2 =
                        boost::bind( dbl_foobar, _1, boost::ref(b), _2 ) ;
    std::cout << f2( 17.4, 23.9 ) << ' ' << b << '\n' ;

    // same disambiguation is also needed for C++0x std::bind
    std::function< int(int) > f3 = std::bind( int_foobar, std::placeholders::_1, 23 ) ;
    std::cout << f3(99) << '\n' ;

    b = 56.2 ;
    // but in C++0x using a lambda function instead is so much easier
    auto f4 = [&b] ( const double a, const double c ) { return foobar(a,b,c) ; } ;
    std::cout << f4( 17.4, 23.9 ) << ' ' << b <<  '\n' ;
}

> The most easiest way for me now is changing the name of the function

Using lambda functions (with …

vijayan121 1,152 Posting Virtuoso

The second argument to RegisterHotKey() is the id of the hot key. If multiple WM_HOTKEY messages are received by the same thread, you need to examine the lParam of the message for the id of the hot key that was pressed.

enum { F9_KEYID = 1, F10_KEYID = 2 } ;
RegisterHotKey( 0, F9_KEYID, MOD_NOREPEAT, VK_F9 ) ;
RegisterHotKey( 0, F10_KEYID, MOD_NOREPEAT, VK_F10 ) ;

MSG msg ;
while( GetMessage( &msg, 0, 0, 0) )
{
    if(msg.message == WM_HOTKEY)
    {
        switch( HIWORD(msg.lParam) )
        {
            case F9_KEYID : MessageBox::Show("F9 was pressed") ; break ;
            case F10_KEYID : MessageBox::Show("F10 was pressed") ; break ;
            default: MessageBox::Show("some other hot key was pressed") ;
        }
    }
    // ...
}

Tip: avoid using magic numbers in your code.

triumphost commented: U ARE AMAZING! +2
vijayan121 1,152 Posting Virtuoso
int main()
{
    int a, b;
    char c ;

    // ...

    ins >> a >> c >> b;    
    cout <<a <<b;
}
vijayan121 1,152 Posting Virtuoso

> what should I know before I try to extend it?
> Should I know some metaprogramming language or the other's part of the boost?

You need to read up on the accumulator framework and concepts.
You also need to have a basic knowledge of the Boost.Parameter library.
For anything not very trivial, it would help if you understand Boost.MPL Lambda Expressions and Boost.MPL Metafunctions/Metafunction Classes.

The basics are straight forward as illustrated here: http://www.boost.org/doc/libs/1_46_0/doc/html/accumulators/user_s_guide.html#accumulators.user_s_guide.the_accumulators_framework.extending_the_accumulators_framework.defining_a_new_accumulator

1. Define your new accumulator (ideally in boost::accumulators::impl). It must derive from accumulator_base
2. In boost::accumulators::tag, define a tag for it. Your tag must inherit from depends_on<>.
3. In boost::accumulators::extract define an extractor for it. And hoist the extractor to the boost::accumulators namespace.


Here is a trivial example that accumulates the average of the last decimal digit of (integral) sample values:

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/type_traits.hpp>
#include <boost/mpl/assert.hpp>
#include <iostream>

namespace boost
{
    namespace accumulators
    {
        namespace impl
        {
            template< typename T > struct average_last_digit : accumulator_base
            {
                BOOST_MPL_ASSERT( ( is_integral<T> ) ) ;

                typedef typename boost::common_type< T, double >::type result_type ;

                template< typename ARGS >  average_last_digit( const ARGS& args )
                  : sum_of_last_digits( args[ sample | T() ] ) {}

                template< typename ARGS > void operator () ( const ARGS& args )
                { sum_of_last_digits += args[sample] % 10 ; 

                template< typename ARGS > result_type result( const ARGS& args ) const
                { return sum_of_last_digits / count( args[accumulator] …
vijayan121 1,152 Posting Virtuoso

I've found that often in my code I have a need for primitive variables protected with synchronization objects such as a boost::mutex

If by primitive variables you mean variables of types like int, double, pointer and so on, using heavy weight synchronization (using mutexes and so on) as a general purpose technique is ill-advised (performance).

If you have a compiler that supports C++0x atomics, use that. The <atomic> header is closely coupled to the innards of the compiler; and ideally results in highly optimized machine code being generated. Something that is not otherwise representable by higher level C or C++ constructs. See N3092 for details http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2010/n3092.pdf

For example,

#include <iostream>
#include <string>
#include <atomic>

int main()
{
    std::atomic<int> cnt(0) ; // specialization for int
    std::cout << ++cnt << '\n' ; // atomic increment
    std::cout << ( cnt += 6 ) << '\n' ;
    // etc

    std::string str[10] { "", "", "", "", "", "hello ", "", "", "", "" };
    std::atomic< std::string* > pointer( str ) ; // atomic pointer
    pointer += 2 ; // atomic increment
    pointer[3] += "world" ; // note: only the pointer operation is atomic here
    std::cout << pointer[3] << '\n' ;
}

If not you could use Boost.Atomic (not part of Boost release) if you are on a platform that it supports. http://www.chaoticmind.net/~hcb/projects/boost.atomic/

Other options include just::thread http://www.stdthread.co.uk/doc/headers/atomic.html, Intel TBB http://threadingbuildingblocks.org/

vijayan121 1,152 Posting Virtuoso

This is not Kadane's algorithm, is it? This algorithm makes multiple passes through the sequence including nested passes:

#include <limits>
#include <utility>

for (int j1=0;j1<=arraysize; j1++) // O(N)
{
     partial_sum(param2+j1,param2+arraysize,newSeq1+determine_start1); // O(N)

     for (int cycle_thru=0;cycle_thru<= length( newSeq1 ) ;cycle_thru++) // O( N*N)
     {
       // ...
     }
     
     // ...
}

Incidentally, this is not C++: int newSeq[summation(arraysize)]; The algorithm also used extra memory O(N*N); summation(N) yields N * (N+1) / 2.

Overall, it executes in cubic ( O(N*N*N) ) time and quadratic ( O(N*N) ) space.

Kadane's algorithm makes a single pass through the sequence, computing a running total of the maximum subsequence sum ending at that position. It executes in linear ( O(N) ) time and uses constant ( O(1) ) space.

Kadane's algorithm for an array of int:

// returns a pair of positions (the start and the end of the maximum sum subsequence) in array a
std::pair<std::size_t,std::size_t> find_max_sum_subsequence( const int a[], std::size_t N )
{
    int max_sum = std::numeric_limits<int>::min() ;
    std::size_t max_subseq_start_pos = 0 ;
    std::size_t max_subseq_end_pos = 0 ;

    int curr_max_sum = 0 ;
    std::size_t curr_subseq_start_pos = 0 ;
    std::size_t curr_subseq_end_pos = 0 ;
    for( ; curr_subseq_end_pos < N ; ++curr_subseq_end_pos )
    {
         curr_max_sum += a[curr_subseq_end_pos] ;

         if( curr_max_sum > max_sum )
         {
             max_sum = curr_max_sum ;
             max_subseq_start_pos = curr_subseq_start_pos ;
             max_subseq_end_pos = curr_subseq_end_pos ;
         }

         if( curr_max_sum < 0 )
         {
             curr_max_sum = 0 ;
             curr_subseq_start_pos = curr_subseq_end_pos + 1 ;
         }
    }
    return std::make_pair( max_subseq_start_pos, max_subseq_end_pos ) ;
}
vijayan121 1,152 Posting Virtuoso

Use a discriminated union.

struct int_or_char
{
    int_or_char( int ii = 0 ) : type(INT), i(ii) {}
    int_or_char( char cc ) : type(CHAR), c(cc) {}
    
    enum type_t { INT, CHAR } ;
    type_t type ;
    
    union
    {
        int i ;
        char c ;
    };

    // etc.
};

and now: Stack< int_or_char > stk ; stk.push(100) ; stk.push( 'a' ) ; etc.

vijayan121 1,152 Posting Virtuoso

My problem is, how to prevent reading so many lines from the file, especially if I have to return more than one line. If I have to return k lines, the complexity is theta(k n^2). I would rather prefer theta(k n log n) .

To select K lines from a population containing an unknown number of lines, you do not have to repeat the selection of one random line many times. A reservoir sampling algorithm can do this in one pass. (The earlier example of selecting one random line is a special case of reservoir sampling; where the reservoir size is just one.)

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
#include <random>
#include <stdexcept>

using namespace std ;

// simple(st) reservoir algorithm for random sampling without replacement
//
// algorithm R (credited to Alan Waterman) from:
//    Random Sampling with a Reservoir' by Jeffry Scott Vitter,
//         ACM Transactions on Mathematical Software, March 1985
//    http://www.ittc.ku.edu/~jsv/Papers/Vit85.Reservoir.pdf
//
// randomly select K (different) lines from an input stream opened in text mode
// time complexity is O(N)
template< typename RNG >
vector<string> random_lines( istream& stm, size_t K, RNG& engine )
{
    vector<string> sample ;
    std::string line ;

    while( sample.size() < K )
    {
        if( getline( stm, line ) ) sample.push_back(line) ;
        else throw range_error( "sample size too large" ) ;
    }

    for( size_t i = K ; getline( stm, line ) ; ++i )
    {
        size_t r = uniform_int_distribution<size_t>( 0, i )(engine) ; …
vijayan121 1,152 Posting Virtuoso

Just create a console application (linker option /SUBSYSTEM:CONSOLE) and write your normal gui code. (Both use the same Win32 or Win64 environment subsystem).

You will have a Console created for you and a main() with stdin, stdout and stderr initialized correctly. Use GetModuleHandle(), GetStartupInfo() etc. if you need the parameters that would have been passed to a WinMain.

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

long __stdcall WindowProcedure( HWND window, unsigned int msg, WPARAM wp, LPARAM lp )
{
    switch(msg)
    {
        case WM_DESTROY:
            std::cout << "\ndestroying window\n" ;
            PostQuitMessage(0) ;
            return 0L ;
        case WM_LBUTTONDOWN:
            std::cout << "\nmouse left button down at (" << LOWORD(lp)
                      << ',' << HIWORD(lp) << ")\n" ;
            // fall thru
        default:
            std::cout << '.' ;
            return DefWindowProc( window, msg, wp, lp ) ;
    }
}

int main()
{
    std::cout << "hello world!\n" ;
    const char* const myclass = "myclass" ;
    WNDCLASSEX wndclass = { sizeof(WNDCLASSEX), CS_DBLCLKS, WindowProcedure,
                            0, 0, GetModuleHandle(0), LoadIcon(0,IDI_APPLICATION),
                            LoadCursor(0,IDC_ARROW), HBRUSH(COLOR_WINDOW+1),
                            0, myclass, LoadIcon(0,IDI_APPLICATION) } ;
    if( RegisterClassEx(&wndclass) )
    {
        HWND window = CreateWindowEx( 0, myclass, "title",
                   WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
                   CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, GetModuleHandle(0), 0 ) ;
        if(window)
        {
            ShowWindow( window, SW_SHOWDEFAULT ) ;
            MSG msg ;
            while( GetMessage( &msg, 0, 0, 0 ) ) DispatchMessage(&msg) ;
        }
    }
}
vijayan121 1,152 Posting Virtuoso

will c++ let you open a .exe or any file for that matter in binary mode?

Yes.

what would be the most efficient way of scanning thru a file on disk

Don't do any conversion to hex or any other text format; just compare the raw bytes.

#include <fstream>
#include <iterator>
#include <algorithm>

typedef unsigned char byte ;

bool is_byte_seq_present_in_file( const char* file_path,
                        const byte* byte_array, std::size_t array_size )
{
    // 1. open the file in binary mode
    std::ifstream file( file_path, std::ios::binary ) ;

    // 2. create a pair of iterators to iterate over the sequence of bytes in the file
    std::istream_iterator<byte> begin(file), end ;

    // 3. use std::search() to search for the byte sequence in the file
    return std::search( begin, end, byte_array, byte_array+array_size ) != end ;
}
vijayan121 1,152 Posting Virtuoso

First, a couple of suggestions regarding your coding style. I'm taking int GetNumber(std::string number) as an exmple. The comments are inline, and some of them would apply to the rest of your code as well.

// for user defined types, prefer passing by reference-to-const over passing by value
int GetNumber( const std::string& number )
{
    // static - needs to be initialized only once
    // const - just being const-correct
    // avoiding magic numbers eg. words[31], for( int i=0 ; i<31; ++i ) etc.
    static const std::string words[] = {"one", "two", "three", "four", "five", 
        "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", 
        "fourteen", "fifteen", "sixteen", "seventeen", "eighteen","nineteen", 
        "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", 
        "ninety","hundred", "thousand", "million", "billion" } ;

    // an extra zero added at the end of numbers[] 
    // to avoid special casing when 'number' is not in 'words[]'.
    static const int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 
        15, 16, 17, 18, 19, 20,30, 40, 50, 60, 70, 80, 90, 100,
        1000, 1000000, 1000000000, 0 } ;

    enum { N = sizeof(words)/sizeof(*words), M = sizeof(numbers)/sizeof(*numbers) - 1 } ;

    // just making sure that we have not inadvertently omitted something
    // a compile-time assertion that the number of elements are in sync.
    typedef char N_must_be_equal_to_M_here[ N == M ] ; // C++98
    //static_assert( N==M, "N_must_be_equal_to_M_here") ; // C++1X

    // why write a loop (where it's easy to make a careless mistake or a typo)
    // when …
vijayan121 1,152 Posting Virtuoso

No instructor I know teaches vectors first.

Stroustrup for one does.

mike_2000_17 commented: epic pwnage! +1
vijayan121 1,152 Posting Virtuoso

void(*fnctn)(void(*)(int *,void **),int(*)(void**,int*)); is equivalent to:

typedef void first_arg_fn_type( int*, void** ) ;

   typedef int second_arg_fn_type( void**, int* ) ;

   typedef void function_type( first_arg_fn_type*, second_arg_fn_type* ) ;

   function_type* fnctn ;
vijayan121 1,152 Posting Virtuoso

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

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

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

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

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

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

Nick Evan commented: Nice one. +16
vijayan121 1,152 Posting Virtuoso
#include <iostream>

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

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

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

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

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

    // ...
};

// define the friend function normally

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

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

vijayan121 1,152 Posting Virtuoso

Do you mean something like this:

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

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

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

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

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