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

> Is this safe?

Yes.

vijayan121 1,152 Posting Virtuoso

> i thought that template <typename T> is for fundamental types and template <class T> is for user defined types.
> ... what is the main difference between them?

There is no difference.

vijayan121 1,152 Posting Virtuoso

Your class should be something like this:

class phone
{
    public:
        // The type member is an enumeration of HOME, OFFICE, FAX, CELL, and PAGER
        enum phone_type_t = { HOME, OFFICE, FAX, CELL, PAGER } ; // *** added

        phone();
        //phone(int coCode, int arCode, int phNumber); // optional

        // A constructor that enables all of the values to be set should be provided as well.
        phone(int coCode, int arCode, int phNumber, phone_type_t phone_type ) ; // *** added

        // constructor that takes just the number and type as arguments, and sets the country and area codes to those of your location
        phone( int phNumber, phone_type_t phone_type ) ; // added

        int GetcoCode() const; //observer
        int GetarCode() const; //observer
        int GetphNumber() const; //observer
        // TODO: add observer for phone type

        // transformers that allow each data member to be changed
        void SetcoCode( int coCode ) ; // added
        // TODO: add other transformers.

        // Shouldn't comparison for equivalence should return a bool?
        /*Contact*/ bool /*ComparedTo*/ Equals( const phone& otherphone ) const ; // make const-correct

    private:
        int countryCode;
        int areaCode;
        int phoneNumber;

        phone_type_t type ; // *** added
};
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

It's not an OS or IDE issue.

#include "Queue.h"
#include "Queue.cpp"

int main()
{
	Queue <int> q;	// q is an object

	q.showQ();
	q.insert(72);
   
        // ...
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> At first, I wrote something like this

template<typename T, size_t size>
inline size_t const sizeof_array(T const [size]){return size;}

> but if failed...Why version one fail?


The reason is extremely simple:

1. These three are different ways of declaring the same function - one which takes a single parameter of type int*

void function( int a[100] ) ;
void function( int a[] ) ;
void function( int* a ) ;

2. Top level references are dropped during deduction. Try this:

#include <iostream>
#include <typeinfo>
#include <cxxabi.h> // GNU C++ specific
#include <string>

template< typename T > std::string type_name() // GNU C++ specific
{
    enum { MAX_LEN = 2048 } ;
    char name[MAX_LEN] = "" ;
    std::size_t sz = MAX_LEN ;
    int status ;
    __cxxabiv1::__cxa_demangle( typeid(T).name(), name, &sz, &status ) ;
    return status==0 ? name : "__cxa_demangle error" ;
}

template< typename T > void foo( T arg )
{
    std::cout << "foo - type T is: " << type_name<T>() << '\n' ;
}

template< typename T > void bar( T& arg )
{
    std::cout << "bar - type T is: " << type_name<T>() << '\n' ;
}

int main()
{
    int i = 100 ;
    int& ref = i ;
    foo(ref) ; // type T is: int (top-level reference is dropped)

    int a[100] = {0};
    int (&ref_array)[100] = a ;
    foo(ref_array) ; // type T is: int* (top-level reference is dropped)
    foo<int(&)[100]>(a) ; // type T is: int[100]
    bar(a) ; // type T …
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

Oh yeah will this work in ofstream?

Yes. std::ofstream is a std::ostream.

C++11: Just use raw string literals.

std::cout << R"---(The path is "C:\Equation_MinGW\bin\g++.exe". (C++11))---" << '\n' ;

   std::cout << R"(menu
----
   1. one
   2. two
   3. three
   )" ;

See: http://www2.research.att.com/~bs/C++0xFAQ.html#raw-strings

vijayan121 1,152 Posting Virtuoso

> why they needed to make 2 types of strings, char string and w_char string?

A few years down the line, they realized that two types of strings are nowhere near enough; so now we have five.

std::string str = "hello world\n" ; // string where char_type is char
    std::wstring wstr = L"hello world\n" ; // string where char_type wchar_t
    std::string utf8str = u8"hello world\n" ; // utf-8 encoded UNICODE string
    std::u16string u16str = u"hello world\n" ; // utf-16 encoded UNICODE string
    std::u32string u32str = U"hello world\n" ; // utf-32 encoded UNICODE string

You might want to read this:
http://www.joelonsoftware.com/articles/Unicode.html

vijayan121 1,152 Posting Virtuoso

> i am using windows 7 64 bit OS, Dev C++ compiler.
> which compiler should i use?

Dev C++ is the IDE; you are probably using an archaic version of the Mingw port of GNU compiler (g++ 3.4 or so).

This would be a more reasonable choice of IDE and compiler:
http://prdownload.berlios.de/codeblocks/codeblocks-10.05mingw-setup.exe

This is another:
http://sourceforge.net/projects/codelite/files/Releases/codelite-3.0/codelite-3.0.0.5041-mingw4.4.1.exe/download

Or this:
http://go.microsoft.com/?linkid=9709949

If you are using the GNU compiler (g++), set the options which would make g++ become a C++ compiler: --std=c++0x --pedantic-errors

preferably along with: -Wall -Wextra -Werror

vijayan121 1,152 Posting Virtuoso
int i=0,a[length],j=0; // *** error: ISO C++ forbids variable length array 'a'
vijayan121 1,152 Posting Virtuoso

I would suggest that you study the fundamental concepts involved in concurrent programming. Understanding that is the harder and the important part.

Learning to use thread facilities provided by a particular platform or library is the easy part; it gives you the tools, but you need to know when and how to use those tools.

Here are two references to get you started:
http://www.amazon.com/Synchronization-Algorithms-Concurrent-Programming-Taubenfeld/dp/0131972596
http://www.amazon.com/Art-Multiprocessor-Programming-Maurice-Herlihy/dp/0123705916

vijayan121 1,152 Posting Virtuoso

> why it is not in the std::tuple or boost::tuples::tuple class since other operators are already defined (comparison).

IIRC, there was a suggestion to overload the + operator for std::tuple<>. Not for element by element arithmetic plus, but for concatenation of tuples a la std::string.

There would be a similar ambiguity in the case of operator- (element by element minus or symmetric difference?), operator* ( element by element multiply, vector cross product or scalar dot product?).

IMHO, it was best that none of these operators were overloaded by the standard.

vijayan121 1,152 Posting Virtuoso

It would be hard to beat the blitz::TinyVector for performance.

http://www.oonumerics.org/blitz/docs/blitz_7.html#SEC131

vijayan121 1,152 Posting Virtuoso

> there are 2 common ways to loop through a vector

Perhaps four.

#include <vector>
#include <algorithm>

void one( std::vector<int>& seq ) { for( auto& i : seq ) ++i ; }

void two( std::vector<int>& seq )
{ for( auto iter = seq.begin() ; iter != seq.end() ; ++iter ) ++*iter ; }

void three( std::vector<int>& seq )
{ for( std::vector<int>::size_type i = 0 ; i < seq.size() ; ++i ) ++seq[i] ; }

void four( std::vector<int>& seq )
{ std::for_each( seq.begin(), seq.end(), []( int& i ) { ++i ; } ) ; }

It is clearly a quality of implementation issue; but one could expect the generated code to be almost identical for all four.

Well not quite.

The GNU compiler generates identical code for one, two and four, but trips up on three (array subscript).

#include <vector>
#include <algorithm>

/**********************************************************************
>g++ --std=c++0x -Wall -Wextra -Werror --pedantic -c -S -O3 -fomit-frame-pointer
**********************************************************************/


void one( std::vector<int>& seq )
{ for( auto& i : seq ) ++i ; }
/*********************************************************************
    movl    4(%esp), %edx
    movl    (%edx), %eax
    movl    4(%edx), %edx
    cmpl    %edx, %eax
    je  L1
L3:
    addl    $1, (%eax)
    addl    $4, %eax
    cmpl    %eax, %edx
    jne L3
L1:
    rep
    ret
**********************************************************************/


void two( std::vector<int>& seq )
{ for( auto iter = seq.begin() ; iter != seq.end() ; ++iter ) ++*iter ; }
/*********************************************************************
    movl    4(%esp), %edx
    movl    (%edx), %eax
    movl    4(%edx), %edx
    cmpl    %edx, %eax
    je  L6
L8:
    addl    $1, (%eax)
    addl    $4, %eax
    cmpl    %eax, %edx …
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
#include <sstream>
#include <exception>

class ConversionException: public std::exception
{
    virtual const char* what() const throw()
    {
        return "Bad Conversion";
    }
} convertError;

template<typename To, typename From>
const To Convert(const From & convertFrom)
{
    To convertTo;
    std::stringstream ss;
    ss << convertFrom;
    if(ss >> convertTo)
        return convertTo;
    throw convertError;
}

int main()
{
    double d = 1.0e+8 ;
    std::cout << int(d) << ' ' << Convert<int>(d) << '\n' ; 
    // prints 100000000 1
}

If there is a direct convertible, you should use that instead of performing the conversion via a stringstream. At best it could be inefficient; in many cases it can yield an incorrect result.

Some thing like this would be required:

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

struct bad_conversion : public std::logic_error
{
    bad_conversion() : std::logic_error( "bad conversion" ) {}
};

template< typename TO, typename FROM > inline TO convert( const FROM& from,
    typename std::enable_if<std::is_convertible<FROM,TO>::value,void>::type* = nullptr )
{ return TO(from) ; }

template< typename TO, typename FROM > inline TO convert( const FROM& from,
    typename std::enable_if< !std::is_convertible<FROM,TO>::value, void >::type* = nullptr )
{
    TO to ;
    std::stringstream stm ;
    if( stm << from && stm >> to ) return to ;
    else throw bad_conversion() ;
}

int main()
{
    double d = 1.0e+8 ;
    std::cout << int(d) << ' ' << convert<int>(d) << '\n' ;
    // prints 100000000 100000000
}
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 used getline to read the first line and to check for spaces

By default, formatted input ignores whitespaces. input >> nextChar ; // nextChar contains the next non-whitespace char So,

#include <fstream>
#include <cctype>

// good if there are digits at the beginning and end of file
bool good_file( const char* const path )
{
    std::ifstream file(path) ;

    // try to read the first non-ws char and check if it is a digit
    char first_non_ws ;
    if( file >> first_non_ws && std::isdigit(first_non_ws) )
    {
        char last_non_ws = first_non_ws ;
        while( file >> last_non_ws ) ; // read till the last non-ws char
        return std::isdigit(last_non_ws) ;
    }
    else return false ;
}
vijayan121 1,152 Posting Virtuoso
//while(!str_number.eof())
//     {
//     str_number >> str_description;
//     ...

while( str_number >> str_description ) // while attempt to extract a string has succeeded 
     {
       ...
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

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

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

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

Something like this:

name = fName + ":" + lName;
        
        // find the first free position
        int free_pos = -1 ;
	for(int i = 0; i < size; i++) 
            if( nameList[i].length() == 0 ) 
            {
                free_pos = i ;
                break ;
            }
        
        if( free_pos != -1 ) nameList[free_pos] = name ; 
        else cout << "Namnlistan är full\n" ;
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

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

> Because not every statistical data could be computed without saving the input values

Boost.Accumulators is a library for incremental statistical computation.

Incremental computation means that the statistic is updated each time new data arrives. Incremental computation of statistics use algorithms that are quite different from static computation algorithms.

For an example, see: http://www.johndcook.com/standard_deviation.html

For incremental computation of statistics like median, which would otherwise require the entire data set, estimators are used. http://www.boost.org/doc/libs/1_46_1/doc/html/accumulators/user_s_guide.html#accumulators.user_s_guide.the_statistical_accumulators_library.median

vijayan121 1,152 Posting Virtuoso

> Is accumulator_set using dynamic memory?

It shouldn't matter either way, should it?

vijayan121 1,152 Posting Virtuoso

> oops,the answer is 3.5 again, but the answer I want is 13.5

The simplest way would be to use a new accumulator_set<> for the fresh calculations.

If you want to reuse the same accumulator_set<> from scratch, just reinitialize it.

#include <iostream>
#include <new>
#include <boost/utility.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>

template< typename DEFAULT_INITIALIZABLE >
inline void clear( DEFAULT_INITIALIZABLE& object )
{
    object.DEFAULT_INITIALIZABLE::~DEFAULT_INITIALIZABLE() ;
    ::new ( boost::addressof(object) ) DEFAULT_INITIALIZABLE() ;
}

int main()
{
    using namespace boost::accumulators ;

    accumulator_set< double, features< tag::count, tag::sum, tag::mean > > ac ;
    ac(123) ; ac(456) ; ac(789) ; ac(1234) ;
    std::cout << sum(ac) << '/' << count(ac) << " == " << mean(ac) << '\n' ;

    clear(ac) ;
    ac(1) ; ac(22) ; ac(333) ;
    std::cout << sum(ac) << '/' << count(ac) << " == " << mean(ac) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

A simple, reasonably fast algorithm to find the smallest prime factor of a number N would be:

a. generate all prime numbers up to the square root of N using a sieve algorithm.

b. the first (smallest) generated prime number that divides N is the smallest prime factor.

For example:

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

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

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

int smallest_prime_factor( int N )
{
    if( N < 2 ) return N ;
    
    std::vector<int> primes = primes_upto( std::sqrt(N) + 1 ) ;
    for( std::vector<int>::size_type i = 0 ; i < primes.size() ; ++i )
        if( ( N % primes[i] ) == 0 ) return primes[i] ;
        
    return N ;
}

For large numbers (up to about 2^70 or so), the Brent-Pollard Rho algorithm is said to be the fastest.
http://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm#Variants
http://www.remcobloemen.nl/2009/12/brent-pollard-%CF%81-factorisation/

vijayan121 1,152 Posting Virtuoso

The general rule is that a file in a directory named 'temp' or 'tmp' is a temporary file; one that is required only for the duration of the execution of the program that uses it. By convention, these can be safely deleted; no reasonable program is expected to break if a temporary file is removed.

vijayan121 1,152 Posting Virtuoso

The catch() does not match the type of the exception that is thrown.

Either:

try 
    {
        std::ifstream somefile(argv[1], std::ios::in|std::ios::binary ) ;
        if( !file ) throw "Error opening file!" ; 

        // no error
        // ...
    }

    catch( const char* cstr )
    {
        std::cerr << cstr << '\n' ;
    }

or

try 
    {
        std::ifstream somefile(argv[1], std::ios::in|std::ios::binary ) ;
        if( !file ) throw std::ios::failure( "Error opening file!" ) ; 
        
        // no error
        // ...
    }
    catch( const std::exception& e )
    {
        std::cerr << e.what() << '\n' ;
    }

would be ok.

vijayan121 1,152 Posting Virtuoso

Consider making your print functions const-correct. void cProg3::Print_s() const etc.

There are many ways to print out the elements in an STL sequence.
You could iterate through the sequence (as you have done). You could use a standard algorithm along with a function object (or a lambda function if you are using a newer compiler eg. Microsoft 2010).

#include <list>
#include <algorithm>
#include <functional>

struct cProg3 { /*...*/ void print_s() const { /*...*/ } /*...*/ } ;

void print_list_one( const std::list<cProg3>& lst )
{
    for( std::list<cProg3>::const_iterator iter = lst.begin() ;
          iter != lst.end() ; ++iter ) iter->print_s() ;
}

void print_list_two( const std::list<cProg3>& lst )
{ std::for_each( lst.begin(), lst.end(), std::mem_fun_ref(&cProg3::print_s) ) ; }


void print_list_three( const std::list<cProg3>& lst )
{ std::for_each( lst.begin(), lst.end(), []( const cProg3& c ) { c.print_s() ; } ) ; }
vijayan121 1,152 Posting Virtuoso

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

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

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

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

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

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

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

        size_type a = …
vijayan121 1,152 Posting Virtuoso

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

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

For example C++98 with boost:

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

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

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

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

    function_t function ;
};

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

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

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

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

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

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

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

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

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

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

vijayan121 1,152 Posting Virtuoso

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

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

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

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

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

Cast the expression to a FILE*.

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

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

vijayan121 1,152 Posting Virtuoso

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

vijayan121 1,152 Posting Virtuoso

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

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

For example,

file /tmp/pp.h

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

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

#ifndef BOOST_PP_IS_ITERATING
# ifndef PP_H_INCLUDED
# define PP_H_INCLUDED

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

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

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

#endif

file check_it_out.cc

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

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

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

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

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

Yes.

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

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

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

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

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