vijayan121 1,152 Posting Virtuoso

You seem to be implying that the behavior will definitely be that of one of the possible orderings, but that's not the case. It's just not unspecified, which increment happens first - the behavior is completely undefined. As far as the standard is concerned, the code may print "23 42" or even crash.
...
Speaking of function calls, I need to correct my earlier answer: The fact that the built-in << operator does not introduce a sequence point is irrelevant because here we're using an overloaded << operator and overloaded operators behave like function calls.

Yes.

Because an int is a scalar.

If a was an object of a user defined type (with increment operators),
std::cout << ++a << ' ' << a++ ; would not result in UB; it is still bad because the evaluations of ++a and a++ would be 'indeterminately sequenced'

...

C++11 version just change the language that expresses the rules (which is definitely clearer)?

C++11 does make the rules clearer. The canonical pedantic (unclear in C++98) example being:
int k = ( f(), g() ) + h() ;

Sequence-point rules had to be discarded and replaced by sequenced-before rules because C++11 is thread and concurrency aware, while C++98 was not. The new rules allow implementations to generate extremely efficient code and at the same time precisely specify the behaviour of the abstract machine.

vijayan121 1,152 Posting Virtuoso

Does this mean that if I have a .h file with a templated class in it I don't need to have inclusion guards on it?

No.

Long story short, templates are not subject to the linkage part of the One-Definition Rules. The same is true for functions that are marked as inline or as static (or appear in unnamed namespaces), which all have internal linkage.

The linkage rules do not change for either templates or inline functions (or both). For instance, by default an inline function, or a function template instantiation has external linkage.

Instead, the IS has a special proviosion in the ODR rules for inline functions and templates.

3.2/5 There can be more than one definition of a class type, enumeration type, inline function with external linkage, class template, non-static function template, static data member of a class template, member function of a class template, or template specialization for which some template parameters are not specified in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements.

Given such an entity named D defined in more than one translation unit, then
- each definition of D shall consist of the same sequence of tokens; and
- etc. ...

Note: because of the proviso: 'provided that each definition appears in a different translation unit', include guards are still required.

A simple way to check this is to have two different translation …

vijayan121 1,152 Posting Virtuoso

Depending on the character set that is being used internally, either char / std::string or wchar_t / std::wstring as appropriate.

To communicate with the outside world (for instance performing file i/o or communicating over the network), ideally use utf8 encoded chars and std::string or char16_t and std::std::u16string (which are utf16 encoded).

See: http://en.cppreference.com/w/cpp/header/codecvt
http://en.cppreference.com/w/cpp/locale/wbuffer_convert
http://en.cppreference.com/w/cpp/locale/wstring_convert

vijayan121 1,152 Posting Virtuoso

Enable all warnings and the compiler will point you in the right direction.

#include <iostream>

int main()
{
    int a=3;
    std::cout<< a++ << " " << ++a ; 
    // *** warning: operation on 'a' may be undefined
}

It is undefined behaviour in both C++98 (which has the old sequence point rules) and C++11 (which does not have sequence points, but uses sequenced-before rules instead).
See: http://en.cppreference.com/w/cpp/language/eval_order

vijayan121 1,152 Posting Virtuoso

... lose a lot of precision as x moves away from zero since 1E6f/(2*pi) has very few sigfigs after the zero subtracting 1E6f leaves me with 1 or 2 sigfigs when doing the rest of the calculation.

If you haven't done so already, you might want to have a look at the section on cancellation in this paper:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

I suppose you are already using a compensated summation algorithm.
http://en.wikipedia.org/wiki/Kahan_summation_algorithm

vijayan121 1,152 Posting Virtuoso

Can anyone show me a few examples or pseudocode of implementation of closest pair algorithm O(n^2), O(n log^2 n), O(n log n)?

The assignment states that a simple linear search (quadratic time) is all that is required:

if the closest distance is less than 500 feet, the system will sound an alarm. .. Implement the straightforward closest pair algorithm which runs in O(n^2).

If you are interested in exploring a faster O( N log N ) algorithm, this illustrates one such algorithm (using a partition tree):
http://www.drdobbs.com/a-template-for-the-nearest-neighbor-prob/184401449?pgno=1

vijayan121 1,152 Posting Virtuoso

boost::interprocess::message_queue is portable.

For redirecting standard streams on Windows, see:
http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx

vijayan121 1,152 Posting Virtuoso

You need top move ALL of the data one character toward the head of the string, not just one. This requires another loop inside the first one. I think your teacher is trying to instruct you on nested loops...

std::remove() is O(N)

void remove_space( char* cstr )
{
    int next = 0 ; // position of next non-space char

    for( int i = 0 ; cstr[i] != 0 ; ++i ) // for every char till the null char
        if( cstr[i] != ' ' ) cstr[ next++ ] = cstr[i] ;

    cstr[next] = 0 ; // null terminate
}
vijayan121 1,152 Posting Virtuoso

OP doesn't have an array of strings where he wants to check each element string. He has one string of which he wants to check every substring. Iterating over all possible substrings and calling is_palindrome on each of them (which is basically what the OP is doing now - albeit in a needlessly complicated -- and apparently in some cases broken -- way) leads to a O(n^3) runtime. The question is whether this is possible in a faster way.

Ah!

Googling for "Manacher's algorithm" (and then applying a simple enough extension to that algorithm) would lead one towards discovering an efficient solution.

A suffix tree based approch is an alternative. The algorithm is described in Gusfield's book. http://www.amazon.com/Algorithms-Strings-Trees-Sequences-Computational/dp/0521585198

vijayan121 1,152 Posting Virtuoso
#include <string>
#include <cctype>
#include <algorithm>
#include <iostream>

bool is_palindrome( const std::string& str )
{
    std::string s ;
    for( char c : str ) if( std::isalpha(c) ) s += std::toupper(c) ;
    return !s.empty() && std::equal( s.begin(), s.begin() + s.size()/2, s.rbegin() ) ;
}

int main()
{
    const char* const phrases[]
    {
        "A man, a plan, a canal - Panama!", // yes
        "not palindrome", // no
        "No lemon, no melon", // yes
        "Not lemon, not melon", // almost, but no
        "Never odd or even" // yes
    };
    for( auto cstr : phrases ) if( is_palindrome(cstr) ) std::cout << cstr << '\n' ;
}

http://ideone.com/fhsyFy

vijayan121 1,152 Posting Virtuoso

swap random elements as many times as you want.

The canonical way to generate an unbiased random permutation in linear time is the Fisher-Yates shuffle
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Using the standard library:

#include <algorithm>
#include <random>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <iomanip>

int main()
{
    constexpr std::size_t N = 6 ;
    int a[N][N] ;
    auto begin = std::begin( a[0] ) ;
    auto end = std::end( a[N-1] ) ;

    std::iota( begin, end, 1 ) ;
    std::srand( std::time(nullptr) ) ;
    std::seed_seq seed_seq { std::rand(), std::rand(), std::rand(), std::rand() } ;
    std::shuffle( begin, end, std::mt19937(seed_seq) ) ;

    for( const auto& row : a )
    {
        for( int i : row ) std::cout << std::setw(3) << i ;
        std::cout << '\n' ;
    }
}

http://ideone.com/LBVPbt

vijayan121 1,152 Posting Virtuoso

Canonical:

#include <memory>

namespace restricted
{
    struct A
    {
        virtual ~A() {}
        virtual int value_a() const { return a ; }

        protected:
            int a = 0 ;
            virtual void value_a( int i ) { a = i ; }
    };

    struct B : A
    {
        virtual int value_b() const { return b ; }

        protected:
            int b = 0 ;
            virtual void value_b( int i ) { b = i ; }
    };
}

namespace exposed
{
    struct A : restricted::A
    {
        using restricted::A::value_a ;
    } ;

    struct B : restricted::B
    {
        using restricted::B::value_a ;
        using restricted::B::value_b ;
    } ;
}

int main()
{
    auto exposed_a = std::make_shared<exposed::A>() ;
    int v = exposed_a->value_a() ;
    exposed_a->value_a(v) ; // fine, exposed

    auto exposed_b = std::make_shared<exposed::B>() ;
    v = exposed_b->value_a() ;
    exposed_b->value_a(v) ; // fine, exposed
    v = exposed_b->value_b() ;
    exposed_b->value_b(v) ; // fine, exposed

    std::shared_ptr<restricted::A> restricted_a(exposed_a) ; // fine, exposed::A => restricted::A

    v = restricted_a->value_a() ; // fine
    // restricted_a->value_a(v) ; // *** error **** restricted::A::value_a(int) is protected

    restricted_a = exposed_b ; // also fine, exposed::B => restricted::A

    std::shared_ptr<restricted::B> restricted_b(exposed_b) ; // fine, exposed::B => restricted::B

    v = restricted_b->value_a() ; // fine
    // restricted_b->value_a(v) ; // *** error **** restricted::B::value_a(int) is protected
    v = restricted_b->value_b() ; // fine
    // restricted_b->value_b(v) ; // *** error **** restricted::B::value_b(int) is protected
}

http://ideone.com/k0cA1O

vijayan121 1,152 Posting Virtuoso

given that it created the && move constructor, why couldn't it create some kind of reference re-assign operator?

C++11 did that with std::reference_wrapper<>. A small class provided by the library, which fills the syntactic gap. Without having to redefine C++98 references; without causing existing code to break.
http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper

#include <vector>
#include <list>
#include <functional>
#include <algorithm>
#include <iostream>

int main()
{
    const std::list<int> lst { 5, 4, 9, 3, 1, 8, 0 } ;
    for( const int& i : lst ) std::cout << i << " (" << &i << ") "  ;
    std::cout << '\n' ;

    std::vector< std::reference_wrapper< const int > > vec( lst.begin(), lst.end() ) ;
    std::sort( vec.begin(), vec.end() ) ;
    for( const int& i : vec ) std::cout << i << " (" << &i << ") "  ;
    std::cout << '\n' ;
}

http://ideone.com/ldNu1U

vijayan121 1,152 Posting Virtuoso

how to disable this non standard exention Vla to get to correct results?

Compile with g++ -std=c++11 -pedantic-errors

With GCC 4.9:

    #include <stdexcept>
    #include <iostream>

    int foo( int arg )
    {
        int a[arg] = { 1, 2, 3, 4 } ;
        int s = 0 ;
        for( int v : a ) s += v ;
        return s ;
    }

    void bar( int arg )
    {
        try
        {
            std::cout << "try foo( " << arg << " ): " ;
            foo(arg) ;
            std::cout << "ok\n" << std::flush ;
        }
        catch( const std::exception& e ) { std::cerr << "exception - what: " << e.what() << '\n' ; }
    }

    int main()
    {
        bar(1) ;
        bar(4) ;
        bar(10) ;
        bar(-1) ;
    }

.

g++ -std=c++11 -pedantic-errors -Wall -Wextra test.cc && ./a.out
temp.cc: In function 'int foo(int)':
temp.cc:6:14: error: ISO C++ forbids variable length array 'a' [-Wvla]
      int a[arg] = { 1, 2, 3, 4 } ;
               ^  

.

g++ -std=c++1y -pedantic-errors -Wall -Wextra test.cc && ./a.out
try foo( 1 ): exception - what: std::bad_array_length
try foo( 4 ): ok
try foo( 10 ): ok
try foo( -1 ): exception - what: std::bad_array_length
vijayan121 1,152 Posting Virtuoso

Local runtime-sized arrays with automatic storage duration (with the undesirable features of C99 VLAs excluded, and support for aggregate initialization and range-based for loops included) will be part of C++14. http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3639.html

Note: Implementation support for VLAs has been made optional in C (C11).

C++14 wiil also have std::dynarray<> http://en.cppreference.com/w/cpp/container/dynarray

vijayan121 1,152 Posting Virtuoso

What would be the call if I did not use a typedef (and using only the new operator)?

int main()
{
    std::size_t n = 15 ; // curves.size()
    double (*corner_points)[4][3] = new double [n][4][3] ;

    // using corner_points is perfectly natural; use it as you
    // would use any array of three dimensions

    // for instance
    double d = 1.0 ;
    for( std::size_t i = 0 ; i < n ; ++i )
        for( auto& row : corner_points[i] )
             for( double& v : row )
                 v = d += 1.0 ;

    // this is the messy part. you must delete the array, delete it once
    // and only once, not use it after it is deleted etc.
    delete[] corner_points ;
}
vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <memory>
#include <vector>

int main()
{
    typedef double corner_points_t[4][3] ;
    // using corner_points_t = double[4][3] ;

    std::size_t n = 15 ; // curves.size()

    // option one: low-level memory management - raw pointer sematics, messy
    {
        corner_points_t* corner_points = new corner_points_t[n] ; // { {0} } ;

        // use corner_points

        // once we are done
        delete[] corner_points ;
    }

    // option two: smart pointer - owned (or shared) pointer semantics
    {
        std::unique_ptr< corner_points_t[] > corner_points( new corner_points_t[n] ) ;
        // std::shared_ptr<corner_points_t> corner_points( new corner_points_t[n], 
                                                 // []( corner_points_t* p ) { delete[] p ; } ) ;

        // use corner_points
    }

    // option three: std::vector<> - simple value seantics
    {
        std::vector< std::vector< std::vector<double> > > corner_points( n,
                                   std::vector< std::vector<double> >( 4, std::vector<double>(3) ) ) ;

        // use corner_points
    }
}
vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map< int, std::string > map { {  1, "one" }, { 3,"three" }, { 5,"five" },
                                       { 7, "seven" }, { 9, "nine" }, { 11, "eleven" } } ;

    std::map<int,std::string>::key_type two = 2 ;
    std::map<int,std::string>::key_type ten = 10 ;

    // iterate from two to ten inclusive
    // see: http://en.cppreference.com/w/cpp/container/map/upper_bound
    // see: http://en.cppreference.com/w/cpp/container/map/lower_bound
    auto end = map.upper_bound(ten) ;
    for( auto iter = map.lower_bound(two) ; iter != end ; ++iter )
        std::cout << '{' << iter->first << ',' << iter->second << "} " ;
    std::cout << '\n' ;

    // iterate from two up to not including ten
    end = map.lower_bound(ten) ;
    for( auto iter = map.lower_bound(two) ; iter != end ; ++iter )
        std::cout << '{' << iter->first << ',' << iter->second << "} " ;
    std::cout << '\n' ;

    map[2] = "two" ;
    map[10] = "ten" ;

    // iterate from two to ten inclusive
    end = map.upper_bound(ten) ;
    for( auto iter = map.lower_bound(two) ; iter != end ; ++iter )
        std::cout << '{' << iter->first << ',' << iter->second << "} " ;
    std::cout << '\n' ;

    // iterate from two up to not including ten
    end = map.lower_bound(ten) ;
    for( auto iter = map.lower_bound(two) ; iter != end ; ++iter )
        std::cout << '{' << iter->first << ',' << iter->second << "} " ;
    std::cout << '\n' ;
}

http://ideone.com/goG6Nj

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

In C/C++, the char type is just that, an integer type (with values between -128 and 127) with some special semantics.

The default char type may be an unsigned integral type.

It is implementation-defined whether a char object can hold negative values. - IS

.
.
.

'5' - '0' is always true (not strictly required to be true AFAIK ..)

Strictly required to be true in every conforming implementation.

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous. - IS

.
.
.

you can be pretty sure that numerical digits and lower-case and upper-case letters of the basic alphabet will be all placed sequentially in the encoding table.

Lower-case and upper-case letters need not contiguous in a conforming encoding; for instance the EBCDIC encoding (still in use today, in mainframes and minis from IBM and a few others).

mike_2000_17 commented: thanks for the precisions! +14
vijayan121 1,152 Posting Virtuoso

A class that has a constructor that accepts a range:

#include <iostream>
#include <initializer_list>
#include <iterator>
#include <array>
#include <vector>
#include <sstream>

struct A
{
    template < typename ITERATOR > A( ITERATOR begin, ITERATOR end )
    {
        std::cout << "A::constructor - " ;
        for( ; begin != end ; ++begin ) std::cout << *begin << ' ' ;
        std::cout << '\n' ;
    }

    template < typename T >
    A( std::initializer_list<T> range ) : A( std::begin(range), std::end(range) ) {}

    template < typename RANGE >
    A( const RANGE& range, decltype( std::begin(range) )* = nullptr )
                          : A( std::begin(range), std::end(range) ) {}
};

int main()
{
    double carray[] { 10.1, 20.2, 30.3, 40.4 } ;
    A a1(carray) ; // construct from C-array (range)

    std::array<long,5> array { { 12, 13, 14 } } ;
    A a2(array) ; // from std::array (range)

    std::vector<short> vector { 91, 92, 93 } ;
    A a3(vector) ; // from sequence container (range)

    A a4( { 1, 2, 3, 4, 5 } ) ; // from initializer list

    std::istringstream stm( "50 60 70 80" ) ;
    // from pair of iterators
    A a5( (std::istream_iterator<int>(stm)), std::istream_iterator<int>() ) ;
}

http://ideone.com/O5wfAv

vijayan121 1,152 Posting Virtuoso

For std::regex_search() with iterators, the iterators must be for iterating over a sequence of characters.

Iterator through the vector tokens, pick up each std::wstring and then apply std::regex_search() on the sequence of characters in the string.

#include <fstream>
#include <vector>
#include <string>
#include <boost/regex.hpp> // testing with GCC 4.8, broken std::regex

int main()
{
    std::vector< std::wstring > tokens { L"abcd", L"eacchij", L"kmlnop", L"qrbcccst" } ;

    boost::wregex regex { L"[ab]c+" } ;

    for( const auto& wstr : tokens )
    {
        std::wcout << wstr ;
        boost::wsmatch results ;
        if( regex_search( wstr, results, regex ) ) std::wcout << L": " << results[0] ;
        std::wcout << L'\n' ;
    }
}

Output:

abcd: bc
eacchij: acc
kmlnop
qrbcccst: bccc

vijayan121 1,152 Posting Virtuoso

But, since I am a newbie, I decided to start learning about reading binary files first

Yes. Learn by taking one small step at a time.

And while you are learning, learn good idioms. This is rarely right: char * buffer = new char [length];
Instead, use std::vector<>
or if you must, use a smart pointer - for instance:
std::unique_ptr< char[] > buffer( new char [length] ) ;

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

using byte = unsigned char ;

std::vector<byte> read_bytes( const std::string& path_to_file )
{
    std::ifstream file( path_to_file, std::ios::binary ) ;
    return { std::istream_iterator<byte>(file), std::istream_iterator<byte>() } ;
}

int main()
{
    std::cout << "dump of bytes in this file:\n" << std::hex ;
    for( byte b : read_bytes( __FILE__ ) ) std::cout << int(b) << ' ' ;
    std::cout << '\n' ;
}

Or, if the compiler is an old one (C++98):

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

typedef unsigned char byte ;

std::vector<byte> read_bytes( const char* path_to_file )
{
    std::ifstream file( path_to_file, std::ios::binary ) ;
    return std::vector<byte>( std::istream_iterator<byte>(file),
                              std::istream_iterator<byte>() ) ;
}

int main()
{
    std::vector<byte> bytes = read_bytes( __FILE__ ) ;
    std::cout << "dump of bytes in this file:\n" << std::hex ;
    for( std::size_t i = 0 ; i < bytes.size() ; ++i  ) std::cout << int( bytes[i] ) << ' ' ;
    std::cout << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

The IS is the place where something about C++ is "officially" said.

2.14.7 The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t.

Oitside of that, this is about as close as one can get:
http://www.stroustrup.com/C++11FAQ.html#nullptr

vijayan121 1,152 Posting Virtuoso

can't we use a string function pls?

Not functions in <string>, but a couple of functions in <ctime>

#include <iostream>
#include <ctime>

int main()
{
    int  month, day, year ;
    std::cin >> month >> day >> year ;
    // validate

    std::tm tm ;
    tm.tm_mon = month - 1 ;
    tm.tm_mday = day ;
    tm.tm_year = year - 1900 ;
    tm.tm_hour = tm.tm_min = tm.tm_sec = 0 ;
    tm.tm_isdst = -1 ;

    static const char* const wdays[] =
    { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday" } ;

    std::time_t t = std::mktime( &tm ) ;
    const std::tm* ptm = std::localtime( &t ) ;

    if( ptm ) std::cout << wdays[ ptm->tm_wday ] << '\n' ;
    else std::cout << "invalid date\n" ;
}
vijayan121 1,152 Posting Virtuoso

Though n is very large, n-m is quite small (n-m) < 100000.
You do not need a full sieve; a partial sieve with a size of n-m+1 would suffice.

#include <iostream>
#include <vector>
#include <cmath>

// copy all prime numbers between m and n to stm
void copy_primes_between( int m, int n, std::ostream& stm )
{
    // invariant: m >1, m < n , n <= 1000000000
    // invariant: (n-m) <= 100000

    // generate a partial sieve from m to n

    std::vector<bool> sieve( n-m+1, true ) ;

    // knock off all the even numbers
    for( int i = m%2 ? m+1 : m ; i <= n ; i += 2 ) sieve[i-m] = false ;
    if( m == 2 ) sieve[0] = true ;

    // and then multiples of odd numbers
    const int rootn = std::sqrt(n) + 1 ;
    for( int p = 3 ; p <= rootn ; p += 2 )
      for( int i = (m/p)*p ; i<=n ; i += p ) if( i != p && i>=m ) sieve[i-m] = false ;

    // write the prime numbers them out
    for( std::size_t i = 0 ; i < sieve.size() ; ++i )
      if( sieve[i] ) stm << m+i << '\n' ;

}

int main()
{
    std::cout.sync_with_stdio(false) ;
    copy_primes_between( 990000000, 990000100, std::cout ) ;
}
vijayan121 1,152 Posting Virtuoso

Well, brace-enclosed initialization solves the 'most vexing parse' problem quite nicely.

struct A { A() ; /* ... */ } ;
struct B { B(A) ; /* ... */ } ;

B b1 ( A() ) ; // declares a function b1
B b2 { A{} } ; // defines an object b2
B b3 ( ( A() ) ) ; // defines an object b3

.
.
Uniform initialization syntax is extremely useful in generic code. For instance T is a template type parameter and we want to use T(), uniform initialization with T{} takes the intricacies of C++'s parsing rules out of the equation. Also, we can now deal with types logically - 'T is a type that can be initialized with four integers' - without having to special case for aggregate initialization, constructor initialization, initializer_list initialization.

template < typename T > T foo() { return T{ 0, 1, 2, 3 } ; }

auto vec = foo< std::vector<int> >() ;
auto tup = foo< std::tuple<int,long,double,double> >() ;
struct A { int a, b ; long c, d ; } ;
A a = foo<A>() ;

.
.

it seems like the intended purpose is to be completely pervasive

It can't be completely pervasive. For that to be possible, brace-enclosed initialization would have to be a drop-in replacement for all older initialization constructs, and it isn't that.
For one, uniform initialization and initialization via initializer lists use the …

vijayan121 1,152 Posting Virtuoso
#include <chrono>
#include <type_traits>

struct timer
{
    typedef typename std::conditional< std::chrono::high_resolution_clock::is_steady,
                                       std::chrono::high_resolution_clock,
                                       std::chrono::steady_clock >::type clock_type ;

    // ...

    private: clock_type::time_point start_time /* = clock_type::now() */ ;
};
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

A far better list than anything you would find on this site:
http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list

tux4life commented: Very useful :) +13
vijayan121 1,152 Posting Virtuoso

This seems simple and to fix the temporary variable problem, and I am using VS2010, but I'm building a library, so not supporting a popular compiler like GCC seems sad.

I've some good news.

Was playing around with the GCC 4.8 snapshot release, and libstdc++ streams are now moveable.
Just took a cursory look; from what I saw, it seemed to work flawlessly.

(The GCC 4.8.0 trunk is in the release branch now.)

vijayan121 1,152 Posting Virtuoso

It's a personal thing...

Yes, it is.

A tuple would support genericity, it is a general-purpose metaprogrammable composite type.
For instance, a tuple can be used as it is with standard algorithms, as a key in an assiciative container.

A struct is an abstractor, a hider of information; a tuple is just an aggregator. For instance, this would be possible with tuples:

std::tuple< int, double > one { 23, 4.5 } ;
std::tuple< short, int > two = one ;
one = two ;

With structs, we would need to write special-purpose boilerplate code for all these. In general, a tuple is not a drop-in replacement for a struct, and vice versa. (Though boost fusion allows as to view a struct as a tuple when the occasion demands).

.
.

Subsequent code is then more decipherable:
v[i]._y = 20;
versus
std::get< 2 >( v[i] ) = 20;

Syntactic sugar is always possible; just that sometimes it requires a wee bit of knowledge/ingenuity.
(Libraries provide it as a matter of routine.)

#include <tuple>
#include <utility>
#include <iostream>

template < std::size_t POS > struct get_tuple_element
{
    template < typename T >
    auto operator() ( T&& t ) const -> decltype( std::get<POS>( std::declval<T>() ) )
    { return std::get<POS>( std::forward<T>(t) ) ; }
};

int main ()
{
    {
        using point = std::tuple<double,int,int> ; // ( polar_angle, x, y)
        constexpr auto polar_angle = get_tuple_element<0>() ;
        constexpr auto x = get_tuple_element<1>() ;
        constexpr auto …
vijayan121 1,152 Posting Virtuoso

x,y are coordinates of a point and double is their polar angle. and i am doing this sorting so that after sorting the points are in the order which will make a polygon.

For a sort using the default operator< for std::pair<> to result in an ordering of the points of a polygon,

  • The polygon must a a convex polygon
  • The polar angle must be the polar angle based on a point which is within the convex polygon.

Note: You could also use std::vector< std::tuple< double, int, int > > instead of the vector of nested pairs.

vijayan121 1,152 Posting Virtuoso

lol what is this ???

It is the mnemonic form of the low level code generated by the compiler.
Don't bother about it right now.

What you need to understand is fairly simple:

  • Performance is a design constraint, not a design goal.
  • Programmer time is more expensive than machine time.
  • People who write compilers are experts at low level optimizations; a typical application programmer is not.

So concentrate on the high-level data structures and algorithms; write the simplest, most transparent kind of code that you can; do your part well, and let the compiler do its part well.

If you want to multiply an unsigned int value by 8, write:
value *= 8 ; and not value <<= 3 ;
You may know that strength reduction is possible, that a shift is faster than a multiply on this particular platform; the writer of the compiler will know at least as much as you do.

vijayan121 1,152 Posting Virtuoso

Any specific reason why you chose to recurse on Problem 1 - Line 11?

I thought the 'if the attempt to read a valid number fails, clean up and try again' logic bacomes more obvious with recursion.

.
.

If the user enters a wrong input 5 times, then that function will return 6 times. I would suggest a do while to avoid that.

Performance is irrelevant in this situation; in the time it takes the user to enter one number, a million instructions can be executed.

But just for the sake of argument, let us say that performance is absolutely critical.
The last line in the function is: return int_in_range_from_stdin( min, max ) ;
This is classic tail call recursion, and every mainstream compiler knows how to perform TCO.

For example, with gcc, the tail recursive version of a function typically produces slightly tighter code than the iterative version. For instance, 13 instructions vs. 15 for:

// invariant: cstr is a string of decimal literals
int recursive_decimal_string_to_number( const char* cstr, int n = 0 )
{
    if( cstr[0] == 0 ) return n ;
    return recursive_decimal_string_to_number( cstr+1, n*10 + cstr[0] - '0' ) ;

    /* g++ 4.8 -O3
    __Z34recursive_decimal_string_to_numberPKci:
        movl    4(%esp), %ecx
        movl    8(%esp), %eax
        movsbl  (%ecx), %edx
        testb   %dl, %dl
        je  L2
    L6:
        addl    $1, %ecx
        leal    (%eax,%eax,4), %eax
        leal    -48(%edx,%eax,2), %eax
        movsbl  (%ecx), %edx
        testb   %dl, %dl
        jne L6
    L2:
        rep
        ret
    */
}

// invariant: cstr is a …
tux4life commented: Thanks for clearing up :-) +13
vijayan121 1,152 Posting Virtuoso

You would find it a lot easier if you factor the code into small functions, each function doing just one thing, and doing it well.

Problem one: get validated numeric input from user

int int_in_range_from_stdin( int min, int max )
{
    int number ;
    std::cout << "enter an integer in the range [ " << min << ", " << max << " ]: " ;

    if( std::cin >> number && number >= min && number <= max ) return number ;

    std::cout << "error in imput.\n" ;
    std::cin.clear() ; // clear ia possible error state
    std::cin.ignore( 1000, '\n' ) ; // and throw away cruft in the input buffer
    return int_in_range_from_stdin( min, max ) ;
}

.
.
Problem two: roll the dice multiple times

int generate_random_roll()
{
    static const int init_once = ( std::srand( std::time(nullptr) ), 0 ) ;
    int roll ;
    while( ( roll = int( ( std::rand() / ( RAND_MAX + 1.0 ) ) * 6 ) + 1 ) == 7 ) ;
    return roll ;
}

.
.
etc...

vijayan121 1,152 Posting Virtuoso

either way, the first code produce type error which should not be there if the second code is working. :/

Each element of a two-dimensional array is a one-dimensional array.
Not a pointer to a one-dimensional array.

int a[20] ;
for( int& i : a ) i = 0 ; // fine; the type of element of 'a' is 'int'

for( int* pi : a ) *pi = 0 ; // *** error ***
// the type of element of 'a' is not 'pointer to int'

Likewise,

int b[10][4] ;

// fine; the type of element of 'b' is 'int[4]', 'array of 4 integers'
for( int (&row)[4] : b ) for( int& i : row ) i = 0 ;

// the type of element of 'b' is not 'int(*)[4]', 'pointer to array of 4 integers'
for( int (*ptr_row)[4] : b ) for( int& i : *ptr_row ) i = 0 ; // *** error ***
Vasthor commented: tyvm!!! +2
vijayan121 1,152 Posting Virtuoso

The strange thing is, I did do just that, the line in question compiled fine, until I tried to copy a type that had an instance variable of one.

There are two different phases of compilation when templates are involved. In somewhat simplistic terms,

The first phase is when a template definition is seen, and it is initially parsed. This takes place before the template is instantiated; the compiler only looks up "non-dependent" names during this phase. A name is a "non-dependent" name if the results of name lookup do not depend on any template parameters; the name referes to the same entity in all template instantiations.

The second phase is when when the template is instantiated; in phase two the compiler looks up "dependent" names. Obviously, the result of this lookup may vary from one template instantiation to another.

For instance:

template < typename T > struct A
{
    void bar( T& first, int second )
    {
        first[0] = 0 ; // first is a "dependent" name; looked up during second phase
        // this is not an error if the template function is not instantiated
        // it may or may not be an error for a particular template instantiation;
        // depends on what the type T is

        second = 0 ; // 'second' is a "non-dependent" name; looked up during first phase
        // second[0] = 0 ; // *** error during first phase look up
    }
};

Instantiate it, and:

template struct A<std::string> ; …
vijayan121 1,152 Posting Virtuoso

if there is a more efficient way of doing what I am doing.

O(N) time, O(N) space; preserves the order.

But the O(N) space for std::unordered_set<> is larger than the O(N) space for std::vector<> if the percentage of duplicate lines is not large.

#include <fstream>
#include <string>
#include <unordered_set>

void copy_unique_lines( const char* srce_file, const char* dest_file )
{
    std::ifstream fin(srce_file) ;
    std::ofstream fout(dest_file) ;

    // http://en.cppreference.com/w/cpp/container/unordered_set
    std::unordered_set<std::string> unique_lines ;  

    std::string line ;
    while( std::getline( fin, line ) )
        if( unique_lines.insert(line).second ) fout << line << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

I find it more likely that it is my fault than the compilers.

Yes. Always start with the axiom 'The problem is in my code; not in the compiler/library'. And stick with it till you reach reductio ad absurdum. Get into the habit of checking the documentation; Visual Studo 2010 help or msdn would have lead you to this page: http://msdn.microsoft.com/en-us/library/bb982967(v=vs.100).aspx
Test with the example code there, and if it works, you would know for sure that the problem is not with the library.
.
.

FOUND IT! turns out the error was caused by line 17 of the declarations

Get into the habit of: write a few lines of code, just enough so that it is compilable, compile and test it, write some more code, compile, test etc. The earlier an error is discovered, the easier is it to identify the cause and rectify it. The smaller the scope in which an error is discovered, the easier is it to identify the cause and rectify it. Use explicit instantiation of templates during the development phase; this will ensure that all the template code is compilable.

.
.
Prefer std::dynamic_pointer_cast<> over std::static_pointer_cast<> for polymorphic types. And where required, check the result of the cast. If, and only if, there is a measurable performance problem with this, should we resort to std::static_pointer_cast<>, and that, after the code is tested, and debugged.

vijayan121 1,152 Posting Virtuoso

i put the seed in side the function. the int main is only calling the function.

void my_function()
{
    static const int seed_once = ( std::srand( std::time(0) ), 0 ) ;
    // ...
}

I want to pick a random number from 60,000 to 200,000.

#include <iostream>
#include <random>
#include <chrono>

int NNNNNN_algo( int min = 60000, int max = 180000 )
{
    // if the implementation has a random device
    // static std::random_device rdev ; static std::mt19937 rng( rdev() ) ;

    // else
    static std::mt19937 rng(
        std::chrono::high_resolution_clock::now().time_since_epoch().count() ) ;

    return std::uniform_int_distribution<int>( min, max )( rng ) ;
}

int main()
{
    while( std::cin.get() ) std::cout << NNNNNN_algo() << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

There is no reason for that dynamic_pointer_cast to fail to compile, or the push_back to the vector for that matter. Whatever is causing this error is not your responsibility, it is that of Microsoft developers. Either file a bug report or see if they fixed it in VS2012 (november update).

Please don't file a bug report; std::dynamic_pointer_cast<> works as specified by the IS in VS 2010.
(IIRC correctly, it also worked correctly in VS 2008)

This last example is much more realistic to my actual code, is this not allowed? Is there any way I can do this? Does the non-concrete-ness of derived make any real difference at all?

It is allowed; there is nothing special that you have to do to make it work; and, no, non-concrete-ness of the class does not make any difference.

This code compiles (and runs) cleanly with VS 2011:

#include <memory> 
#include <iostream> 
#include <vector>

struct base { virtual ~base() {} virtual std::shared_ptr<base> clone() const = 0 ; } ;

struct derived_abstract : base {} ;

struct more_derived : derived_abstract
{ 
    virtual std::shared_ptr<base> clone() const 
    { 
        return std::make_shared<more_derived>( *this ) ; 
    }
};

int main() 
{ 
    std::shared_ptr<base> pb = std::make_shared<more_derived>() ; 
    std::shared_ptr<base> pb2 = pb->clone() ; 

    std::shared_ptr<derived_abstract> pd =
                          std::dynamic_pointer_cast<derived_abstract>(pb) ; 
    std::cout << pd.get() << '\n' ;

    std::shared_ptr<derived_abstract> pd2 = 
                          std::dynamic_pointer_cast<derived_abstract>(pb2) ; 
    std::cout << pd2.get() << '\n' ;

    std::vector< std::shared_ptr<derived_abstract> > seq ;
    seq.push_back( std::dynamic_pointer_cast<derived_abstract>( pb->clone() ) ) ; 
    seq.push_back( std::dynamic_pointer_cast<derived_abstract>( seq[0]->clone() ) ) ; 
    std::cout << seq.back().get() …
vijayan121 1,152 Posting Virtuoso

This seems simple and to fix the temporary variable problem, and I am using VS2010, but I'm building a library, so not supporting a popular compiler like GCC seems sad.

Yes. GCC is a mainstream compiler, and are several situations where it is indispensable. It certainly shouldn't be ignored while writing a portable library.

However, if you are prepared to wait for some time, kludging work-arounds for GCC would not be needed. The GCC developers are aware of this issue, it is in their bugzilla, and libstdc++ streams will be moveable, as they should be, in some future release.

I would guess that vijayan121 is referring to the streams not yet being moveable in the libstdc++ library (something I haven't verified). But this is only required in order to make your class moveable too

This is required for a lot of reasons, one of them being, if required, making class holding a stream object moveable.

(or grab a stream rvalue-reference in the constructor, which is a rather useless feature in my opinion).

Grab a stream rvalue-reference reference? The move constructor does more than just grab a reference. And the move-constructor is the mechanism; it is not the goal. There are many reasons why the C++ community came to the conclusion that making streams movable would not be a useless feature:

Hinnant, Stroustrup, and Kozicki have one example of their utility in the article quoted earlier - writing factory functions:

By making such types …

vijayan121 1,152 Posting Virtuoso
while(!inputFile.eof()) 
{
    getline(inputFile, myString); // what happens if this fails?
    list.push_back(myString); // push_back the previous line one more time?
}

Instead, write:

while( getline( inputFile, myString ) ) list.push_back(myString) ; 
vijayan121 1,152 Posting Virtuoso

proper way to pass a temporary stream...
I'm disliking the std::stream's lack of copy constructors.
I know exactly what the problem is, but I don't know what I can do about it

The proper way is to move the temporary stream. Stream classes in C++ are moveable, but not copyable.

Some types are not amenable to copy semantics but can still be made movable. For example:

  • fstream
  • unique_ptr (non-shared, non-copyable ownership)
  • A type representing a thread of execution

By making such types movable (though still non-copyable) their utility is tremendously increased. Movable but non-copyable types can be returned by value from factory functions:

...
ifstream find_and_open_data_file(/* ... /);
...
ifstream data_file = find_and_open_data_file(/
... */); // No copies!
...

In the above example, the underlying file handle is passed from object to object, as long as the source ifstream is an rvalue. At all times, there is still only one underlying file handle, and only one ifstream owns it at a time.
.
Movable but non-copyable types can also safely be put into standard containers. If the container needs to "copy" an element internally (e.g. vector reallocation) it will move the element instead of copying it.
...
- http://www.artima.com/cppsource/rvalue.html

A simple example:

#include <iostream>
#include <fstream>
#include <string>
#include <utility>

struct push_back_reader
{
    // stm referes to an input file stream opened (and owned) by this object
    push_back_reader( const std::string& path2file ) 
                    : …
vijayan121 1,152 Posting Virtuoso

Can C++11's Mutexes be used for Inter-Process Communication? In other words, can it be used for shared memory and signalling an event?

C++11 does not have any inter-process functionality.

C++11 threading primitives (mutexes, atomics, etc) are just that - threading primitives. They know nothing about processes, and they are not a means of achieving inter-process communication. The IS makes no mention of processes or inter-process communication; the behaviour of C++11 objects when placed in trans-process shared memory is undefined.

I wanted a cross-platform way of doing so without doing #ifdef windows and ifdef linux, etc..

So I'm stuck with events?

No.
Boost.Interprocess http://www.boost.org/doc/libs/1_52_0/doc/html/interprocess.html
is portable across Windows and POSIX, and has a wide range of higher-level interprocess mechanisms.

vijayan121 1,152 Posting Virtuoso

But, i didn't understand what other memory is needed for.
Could anyone please explain what this excess memory is needed for?

There are very few people who could explain this better than Doug Lea.

...
This approach leads to fixed bookkeeping overhead per chunk. Because both size information and bin links must be held in each available chunk, the smallest allocatable chunk is 16 bytes in systems with 32-bit pointers and 24 bytes in systems with 64-bit pointers. These minimum sizes are larger than most people would like to see -- they can lead to significant wastage for example in applications allocating many tiny linked-list nodes. However, the 16 bytes minimum at least is characteristic of any system requiring 8-byte alignment in which there is any malloc bookkeeping overhead. - http://g.oswego.edu/dl/html/malloc.html

The article (written in 1996) is dated (particulary after the proliferation of multi-core systems); but it is still a very good read if one wants to understand dynamic memory allocation.

For objects with small footprint, and large number of dynamic allocations, overloading the new and delete operators, with custom memory allocation can do much better. The archetypical example being Loki's small object allocator.

An example using Boost pool:

    #include <boost/pool/object_pool.hpp>

        struct small
        {
            int i = 4 ;

            static boost::object_pool<small> pool ;

            inline static void* operator new( std::size_t n )
            {
                void* p = nullptr ;
                if( n == sizeof(small) ) p = pool.malloc() ;
                return p ? p …
vijayan121 1,152 Posting Virtuoso

I've found that Boost Python works best with C++
http://www.boost.org/doc/libs/1_52_0/libs/python/doc/
Perhaps, you would want to use it in conjunction with py++
http://pypi.python.org/pypi/pyplusplus/

The other major option is SWIG.
http://www.swig.org/

vijayan121 1,152 Posting Virtuoso

Visual Studio 2010 was already ahead of GCC as far as the library was concerned - the Microsoft compiler already had UNICODE support (utf-8, UCS-2 and UCS-4 codecvt facets), basic C++11 threads, atomics amd fences, locales, regular expressions. All these important features are stil missing in GCC (though locales are avalable on linux). What Micrsoft lagged behind was in support for important core C++11 language features. As of November 2012, they have made rapid progress and are on par on those too.

Some six months back, when a like question was raised in Daniweb, I had enthusiastically recommended GCC over MIcrosoft (both were behind clang, 3.1 at that time, but clang with libc++ is not particularly easy for a breginner to build and install).

Today, the landscape has changed; both clang 3.2 with libc++ and VS 2012 (November update) are far ahead of GCC 4.8. This is politically unpalatable to many I am sure - it is disagreeable to an open source afficianado like me, who had consistently preferred GCC over VC++ till now. But however unpleasant it may be, that VC++ is ahead of GCC by some distance (as as a C++ compiler on Windows) happens to be the bitter truth.

vijayan121 1,152 Posting Virtuoso
struct A // non-copyable, moveable
{
    A() { /* ... */ }
    ~A() { /* ... */ }

    A( const A& ) = delete ;
    A& operator= ( const A& ) = delete ;

    A( A&& ) { /* ... */ }
    A& operator= ( A&& ) { /* ... */ return *this ; }
};

struct B // copyable, non-moveable
{
    B() { /* ... */ }
    ~B() { /* ... */ }

    B( const B& ) { /* ... */ }
    B& operator= ( const B& ) { /* ... */ return *this ; }

    B( B&& ) = delete ;
    B& operator= ( B&& )  = delete ;
};

struct C // non-copyable, non-moveable
{
    C() = default ;
    ~C() = default ;

    C( const C& ) = delete ;
    C& operator= ( const C& ) = delete ;

    C( C&& ) = delete ;
    C& operator= ( C&& )  = delete ;
};

why the example in the link shows a base class, and another class derived from it

Syntactic sugar.

struct non_copyable_non_moveable
{
    non_copyable_non_moveable() = default ;
    ~non_copyable_non_moveable() = default ;

    non_copyable_non_moveable( const non_copyable_non_moveable& ) = delete ;
    non_copyable_non_moveable& operator= ( const non_copyable_non_moveable& ) = delete ;

    non_copyable_non_moveable( non_copyable_non_moveable&& ) = delete ;
    non_copyable_non_moveable& operator= ( non_copyable_non_moveable&& )  = delete ;
};

struct my_class : private non_copyable_non_moveable
{
    // we do not have to do anything more to make my_class non-copyable and non-moveable
};