vijayan121 1,152 Posting Virtuoso

once you get into a mindset of using const keyword like that it just becomes natural no matter how non or complex the method is.

Yes. Yes.

In this example, the notion that the const-qualification may somehow 'allow the compiler to perform some extra optimisations' was true in some prehistoric era. If the entire context of use of an object is visible to the compiler (ie. the const-qualified object is not aliased, is not at namespace scope with external linkage, is not a parameter of a non-inline, non-template function with external linkage, etc.), it knows everything about what is going on with that object. It is a lot better at static-flow analysis than most programmers; and the "as-if" rule allows it to rewrite the code.
http://en.cppreference.com/w/cpp/language/as_if

C++11 deprecated the use of the keyword register - compilers know what would be optimally placed in a register better than programmers; for about twenty years or so, they have been just ignoring the register keyword as an optimisation hint. Just as they have been ignoring inline as an optimisation hint.

const in a purely local context is for the programmer; it makes no difference to the optimiser.

As an example, with optimisations enabled, this code

namespace
{
    unsigned int at_namespace_scope_with_internal_linkage = 0 ;
}

int foobar()
{
    at_namespace_scope_with_internal_linkage -= 100 ;

    /* const omitted */ auto a = 52 ;
    auto b = a / 2 ;
    auto c = a + 5 ;

    if( b < …
vijayan121 1,152 Posting Virtuoso
15. Use const proactively.

Summary

const is your friend. Immutable values are easier to understand, track, and reason about, so prefer constants over variables wherever it is sensible and make const your default choice when you define a value. It's safe, it's checked at compile time,
and it's integrated with C++'s type system.  ...


Discussion

Constants simplify code because you only have to look at where the constant is defined to know its value everywhere. Consider this code:

void Fun( vector<int>& v)
{  //...
   const size_t len = v.size();
   //... 30 more lines ...
}

When seeing len's definition above, you gain instant confidence about len's semantics throughout its scope (assuming the code doesn't cast away const, which it should not do). It's a snapshot of v's length at a specific point. Just by looking up one line of code, you know len's semantics over its whole scope. Without the const, len might be later modified, either directly or through an alias. Best of all, the compiler will help you ensure that this truth remains true.

...

From: 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices' by Sutter and Alexandrescu

vijayan121 1,152 Posting Virtuoso

Use an enumeration http://en.cppreference.com/w/cpp/language/enum

Something like:

#include <iostream>
#include <string>

enum class choice_t : std::size_t { one = 1, two = 2 /* ... */, invalid = std::size_t(-1) };

std::ostream& operator << ( std::ostream& stm, choice_t c )
{
    std::cout << "choice_t::" ;

    static const std::string text[] = { "invalid", "one", "two", /* ... */ } ;

    std::size_t v = std::size_t(c) ;
    if( v >= sizeof(text) / sizeof( text[0] ) ) v = 0 ; // invalid choice

    return stm << text[v] ;
}

std::istream& get_choice( std::istream& stm, choice_t& choice )
{
    std::string c ;
    if( stm >> c )
    {
        if( c == "1" || c == "one" || c == "choice1" ) choice = choice_t::one ;
        else if( c == "2" || c == "two" || c == "choice2" ) choice = choice_t::two ;
        // else if ...
        else
        {
            choice = choice_t::invalid ; // invalid input
            stm.clear( std::ios::failbit ) ; // force the stream into a failed state
        }
    }
    return stm ;
}

int main()
{
    std::cout << "\nPlease enter 'choice1' for pattern A or 'choice2' for pattern B: " ;
    choice_t choice ;
    get_choice( std::cin, choice );

    switch(choice)
    {
        case choice_t::one:
            std::cout << "your choice is: " << choice << " => pattern A\n" ;
            // ...
            break ;

        case choice_t::two:
            std::cout << "your choice is: " << choice << " => pattern B\n" ;
            // ...
            break ;

        // case ...

        default: std::cout << "this is an invalid choice (" << …
vijayan121 1,152 Posting Virtuoso

This is an infinite loop: for( int i = 0, n = 2; ; ++i ) { /* ... (no break statement) */ }
A missing condition makes the implied while clause equivalent to while(true).

At some point of time, when i becomes equal to std::numeric_limits<int>::max(), ++i will cause a signed integer overflow.
When n becomes equal to std::numeric_limits<int>::min(), n -= 1 will also trigger a signed integer overflow.

Don't know what happens in Java, but in C++, signed integer overflow engenders undefined behaviour.

Change the type of i and n to unsigned int and the program is well-formed (though the infinite loop still remains). Unsigned integers obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of the unsigned integer.

jamesjohnson25 commented: Thanks for the info. +0
vijayan121 1,152 Posting Virtuoso

The keys in the map are const objects: const std::string; they can't be modified directly inside the map.

Something like this, perhaps:

#include <iostream>
#include <map>
#include <string>
#include <cctype>

std::string to_lower( const std::string& str )
{
    std::string lc ;
    for( char c : str ) lc += std::tolower(c) ;
    return lc ;
}

std::map< std::string, std::string > to_lower( const std::map< std::string, std::string >& map )
{
    std::map< std::string, std::string > lc ;
    for( const auto& pair : map ) lc.emplace( to_lower(pair.first), to_lower(pair.second) ) ;
    return lc ;
}

int main()
{
     std::map< std::string, std::string > the_sms_codes
     {
        { ".02",  "Your (or my) two cents worth" },
        { "10X",  "Thanks" },
        { "2MI",  "Too much information"},
        { "2U2",  "To You Too" },
        { "4COL", "For Crying Out Loud" }
     };

     the_sms_codes = to_lower(the_sms_codes) ;

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

http://coliru.stacked-crooked.com/a/a8002a215a00beca

Or initialise them as lower case strings:

std::map< std::string, std::string > the_sms_codes
{
    { to_lower(".02"),  to_lower("Your (or my) two cents worth") },
    { to_lower("10X"),  to_lower("Thanks") },
    // ...
};
vijayan121 1,152 Posting Virtuoso

<cerrno> defines several standard integer error codes (integer constant expressions with type int).
For instance, ENOENT for 'No such file or directory'
http://en.cppreference.com/w/cpp/error/errno_macros

<system_error> gives us the scoped enum std::errc
For instance, std::errc::no_such_file_or_directory
http://en.cppreference.com/w/cpp/error/errc

<system_error> also has the class std::error_code. Objects of this type can be created from an error code enum and std::error_code::::message() returns a string containing the error message.
http://en.cppreference.com/w/cpp/error/error_code/message

vijayan121 1,152 Posting Virtuoso

ScheduleFile mySchedule();
This is the declaration of a nullary function returning a prvalue of type ScheduleFile
See: https://en.wikipedia.org/wiki/Most_vexing_parse

int main() {

    // ScheduleFile mySchedule(); // declare a function

    ScheduleFile mySchedule ; // define a default initialised object
}
vijayan121 1,152 Posting Virtuoso

The canonical C++ way is to use templated callbacks in conjunction with:
wrapping the call in a polymorphic call wrapper std::function<>
and currying with std::bind()
http://en.cppreference.com/w/cpp/utility/functional/function
http://en.cppreference.com/w/cpp/utility/functional/bind

Sample code:
http://coliru.stacked-crooked.com/a/8d4283e68de561cf
http://rextester.com/VBNT79084

vijayan121 1,152 Posting Virtuoso

compile error : no matching member function for call to 'insert'

There is no error in the posted code (once the missing headers are added).
Since C++11, insert() and erase() on standard constainers accept const_iterators.
http://en.cppreference.com/w/cpp/container/vector/insert
http://en.cppreference.com/w/cpp/container/vector/erase

Note: this does not break legacy code. The IS requires that for a standard container, there must be an implicit converstion from iterator to const_iterator.

You appear to be using an old version of libstdc++ which is still in legacy mode wrt this.

LLVM and GNU: http://coliru.stacked-crooked.com/a/51d6e6b2a90106fc

Microsoft: http://rextester.com/JRJP63287

vijayan121 1,152 Posting Virtuoso

Book: The C++ Standard Library: A Tutorial and Reference (2nd Edition) by Josuttis
http://www.amazon.com/Standard-Library-Tutorial-Reference-2nd/dp/0321623215

Online reference: http://en.cppreference.com/w/

Offline archive: http://en.cppreference.com/w/File:html_book_20141118.zip

vijayan121 1,152 Posting Virtuoso

GNU specific, and worth studying merely for the elegance of the design.
(Note: it violates ODR, but the implementation is allowed to provide well-defined semantics for undefined behaviour.)

<begion quote>

The following goals directed the design of the libstdc++ debug mode:

Correctness: <...>
Performance: <...>
Usability: <...>

Minimize recompilation: While it is expected that users recompile at least part of their program to use debug mode, the amount of recompilation affects the detect-compile-debug turnaround time. <...>
There are several levels of conformance to this requirement, each with its own usability and implementation characteristics. In general, the higher-numbered conformance levels are more usable (i.e., require less recompilation) but are more complicated to implement than the lower-numbered conformance levels.

  1. Full recompilation: <...>
  2. Full user recompilation: <...>
  3. Partial recompilation: <...>

4. Per-use recompilation: The user must recompile the parts of his or her application and the C++ libraries it depends on where debugging should occur, and any other code that interacts with those containers. This means that a set of translation units that accesses a particular standard container instance may either be compiled in release mode (no checking) or debug mode (full checking), but must all be compiled in the same way; a translation unit that does not see that standard container instance need not be recompiled. This also means that a translation unit A that contains a particular instantiation (say, std::vector<int>) compiled in release mode can be linked against a translation unit B that contains the same …

mike_2000_17 commented: That's cool! +14
vijayan121 1,152 Posting Virtuoso

is it used to substitute constructor?

Yes. An exception-safe and (usually) more efficient substitute.

This function is typically used to replace the construction std::shared_ptr<T>(new T(args...)) of a shared pointer from the raw pointer returned by a call to new.

In contrast to that expression, std::make_shared<T> typically allocates memory for the T object and for the std::shared_ptr's control block with a single memory allocation (this is a non-binding requirement in the Standard), where std::shared_ptr<T>(new T(args...)) performs at least two memory allocations.

Moreover, code such as f(std::shared_ptr<int>(new int(42)), g()) can cause a memory leak if g throws an exception because g() may be called after new int(42) and before the constructor of shared_ptr<int>. This doesn't occur in f(std::make_shared<int>(42), g()), since two function calls are never interleaved.
- http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared

vijayan121 1,152 Posting Virtuoso

The input consists of two numbers X and Y ( - 10^12 <x, y< 10^12).

Well, then the essence of this exercise is to ask the student to determine and use a suitable signed integer type that can hold integers having 13 decimal digits.
(The types int or long int may be inadequate.)

#include <iostream>

int main()
{
    constexpr auto upper_bound = 1'000'000'000'000 ; // C++14 literal
    // constexpr auto upper_bound = 1000000000000 ; // C++11

    constexpr auto lower_bound = -1'000'000'000'000 ;

    // integer_type is an alias for a signed integer type
    // which can hold integers with 13 decimal digits
    // http://www.stroustrup.com/C++11FAQ.html#decltype
    using integer_type = decltype(9'999'999'999'999) ;

    integer_type x = 0 ;
    std::cin >> x ; // if input fails, x would be set to zero
    integer_type y = 0 ;
    std::cin >> y ; // do nothing if std::cin is in a failed state

    if( x > lower_bound && y < upper_bound )
    {
        char relation = '=' ;
        if( x < y ) relation = '<' ;
        else if( y < x ) relation = '>' ;
        std::cout << x << ' ' << relation << ' ' << y << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/38a38ef80b3c857c

vijayan121 1,152 Posting Virtuoso
#include <iostream>

int main()
{
    int x ;
    std::cin >> x ; // if input fails, x would be set to zero

    int y = 0 ;
    std::cin >> y ; // do nothing if std::cin is in a failed state

    // there is no need to check that x and y are valid integers

    char relation = '=' ;
    if( x < y ) relation = '<' ;
    else if( y < x ) relation = '>' ;

    std::cout << x << ' ' << relation << ' ' << y << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

The file is not huge (molecules); consider reading the entire file into a data structure in memory. Perform the look ups in memory, and if the data is modified, write it back into the file at the end.

For instance: http://coliru.stacked-crooked.com/a/30d9483adc21fb9a

vijayan121 1,152 Posting Virtuoso

The Microsoft implementation includes the draft TR2 filesystem library.
(With other compilers, boost::filesystem which privides like functionality can be used.)

#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
namespace fs = std::tr2::sys ;

std::vector<std::wstring> files_in_directory( fs::wpath path = L".", bool recursive = true )
{
    std::vector<std::wstring> files ;

    try
    {
        if( fs::exists(path) ) files.push_back( fs::system_complete(path) ) ;

        if( fs::is_directory(path) )
        {
            using iterator = fs::basic_directory_iterator < fs::wpath > ;
            for( iterator iter(path) ; iter != iterator() ; ++iter )
            {
                files.push_back( fs::system_complete( iter->path() ) ) ;
                if( recursive ) 
                    for( const std::wstring& p : files_in_directory( iter->path() ) )
                        files.push_back( std::move(p) ) ;
            }
        }
    }

    catch( const std::exception& ) { /* error */ }

    return files ;
}

int main()
{
    for( const std::wstring& path : files_in_directory( L"C:\\Windows", false ) ) 
        std::wcout << path << '\n' ;
}

http://rextester.com/MVQND35610

NathanOliver commented: Very Nice +13
vijayan121 1,152 Posting Virtuoso

f i have like getline and if it cant get anything, the program will obviously crash/not build

No. std::getline() first clears the string and if no characters were extracted (not even the discarded delimiter), sets the failbit on the stream.

if( std::getline( stm, line ) ) \\ if at least one character was extracted

#include <iostream>
#include <fstream>

int main()
{
    const char* const path_to_file = __FILE__ ; // put the actual path here 
    std::ifstream file(path_to_file) ;

    if( !file.is_open() ) std::cerr << "could not open file\n" ;
    else if( file.peek() == EOF ) std::cout << "file is empty\n" ;
    else std::cout << "file contains at least one character\n" ;
}
vijayan121 1,152 Posting Virtuoso

I think it must be since it all occurs between sequence points.

Sequence point rules were there prior to C++11. Now, those rules have been superceded by sequenced-before rules.

The question: does i++ + ++i; engender undefined behaviour is of relevance if and only if i is of a scalar type.

If i is of a user-defined type, ++i and i++ are function calls; the evaluations of the sub-expressions are indeterminately sequenced. This means that they may be evaluated in any order; but the two evaluations will never interleave even on a multi-core processor. Indeterminately sequenced does not imply undefined behaviour.

If i is a scalar, the evaluations are unsequenced and unsequenced side effects on a scalar leads to undefined behaviour.

Is double pre-incrementing undefined behavior? Like ++++x or even ++++++++x.

Assuming that x is a scalar, these are of interest:

If x is not of type bool, the expression ++x is equivalent to x+=1 - IS

The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.

AFAIK:

#include <iostream>

int main()
{
    int i = 1 ;
    struct A 
    { 
        int i ; 
        int j ; 
        A( int a, int b ) : i(a), j(b) {} 
        A& operator++() { return *this ; };
        A operator++(int) { return *this ; };
        A operator+ (A) { return *this ; }
    };

    ///////////  well-defined behaviour //////////////////////

    i = i + …
vijayan121 1,152 Posting Virtuoso

am trying to generate prime numbers well in excess of 1Gbyte of mem.

It does not matter what knid of contortions we go thrugh to allocate memory - new, malloc, HeapAlloc, GlobalAlloc, VirtualAlloc, MapViewOfFile ... - we are fundamentaly limited by the virtual address space that we have. With MinGW32, the total amount of memory available for user land use is 2 GB (could have been 3 GB if MinGW was built with /largeaddressaware). Of this 2GB, a chunk is taken away by the executable image, system and language libraries etc.

Repeat: If dynamic memory requirements are well in excess of 1 GB, and you are on a 64-bit windows platform, switch to MinGW64.

マーズ maazu commented: I need time to think about it. Right now, mingw32 is fine. +0
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
#include <iostream>

int main()
{
    std::cout << "GCC version is: " << __GNUC__ // major version
              << '.' << __GNUC_MINOR__ // minor version
              << '.' << __GNUC_PATCHLEVEL__ // patch 
              << '\n' ;
}

http://coliru.stacked-crooked.com/a/6fa59c0dc4089745

vijayan121 1,152 Posting Virtuoso

The problem with

{
    Game g;
    g.addtoHallofFame(*this);
}

is that g is a local variable at block scope (automatic storage duration); it will be destroyed when the scope is exited from.

One option would be to make vector<PlayerScore> scores; a static member of Game; this is logical if there can be only one game in progress at a time.

Another is to keep a reference to the associated Game as a member in the Adventure object.

Or to pass a reference to the associated Game as a parameter to update()

// favour a std::vector<std::string> or std::array< std::string, N > over raw arrays
// void Adventure::update( string arr[], Game& g )
void Adventure::update( const vector<string>& arr, Game& g )
{       
    if ( !arr.empty() && arr[0] == "quit" ) // ideally avoid the magic constant "quit"  
    {           
        g.addtoHallofFame(*this);
    }
}
vijayan121 1,152 Posting Virtuoso

can someone help knowing the difference between

> char *st="myname"; 
> char st[]="myname";

"myname" is a narrow string literal; in C++, A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration. - IS

So, with "myname" we have an an lvalue of type array of 7 const char. The life-time of this array is the duration of the program.

This array can be implicitly converted to a prvalue of of type “pointer to const char”; the result of the conversion is a pointer to the first element of the array. For compatibility with C code, C++98 specified:

A string literal that is not a wide string literal can be converted to an rvalue of type “pointer to char” ... [Note: this conversion is deprecated.]

C++11 simply dropped the above clause from the IS, and has this in Annex C (Compatibility):

Change: String literals made const

The type of a string literal is changed from “array of char” to “array of const char.” The type of a char16_t string literal is changed from ...

Rationale: This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument.

Effect on original feature: Change to semantics of well-defined feature.

Difficulty of converting: Syntactic transformation. The fix is to add a cast:

> char* p = "abc"; // valid in C, invalid in …
mike_2000_17 commented: Very complete! And I didn't know C++11 deprecated this construct, cool! +14
vijayan121 1,152 Posting Virtuoso
#include <vector>
#include <string>
#include <iostream>

struct A
{
    // see: http://www.stroustrup.com/C++11FAQ.html#uniform-init
    // see: http://www.stroustrup.com/C++11FAQ.html#member-init
    std::vector<std::string> activities {1} ; // vector with initial size 1 (contains one empty string)

    // see: http://www.stroustrup.com/C++11FAQ.html#init-list
    std::vector<std::string> animals { "panda", "lynx", "ibex" } ; // vector with 3 animals (strings)

    std::vector<std::string> colours ;

    // see: http://www.stroustrup.com/C++11FAQ.html#uniform-init
    A() : colours { "cyan", "magenta", "yellow", "black" } {} // colours initialised with 4 colours (strings)
};

template < typename SEQUENCE >
void print( const SEQUENCE& seq, const char* name = "", std::ostream& stm = std::cout )
{
    stm << name << ":  [ " ;

    // see: http://www.stroustrup.com/C++11FAQ.html#auto
    // see: http://www.stroustrup.com/C++11FAQ.html#for
    for( const auto& v : seq ) stm << '"' << v << "\" " ;

    stm << "]\n" ;
}

int main()
{
    A a ;
    print( a.activities, "activities" ) ; // activities:  [ "" ]
    print( a.animals, "animals" ) ; // animals:  [ "panda" "lynx" "ibex" ]
    print( a.colours, "colours" ) ; // colours: [ "cyan" "magenta" "yellow" "black" ]
}

http://coliru.stacked-crooked.com/a/6e298710d3d520cf

vijayan121 1,152 Posting Virtuoso

Why the warning doesn't occur in C++?

The IS does not require that undefined behaviour must be diagnosed.

The macro #define msizeof(type) ((char*)(&type) - (char*)(&type - 1))
engenders undefined behaviour when used this way:

int main()
{
    int x;

    // msizeof(x) attempts to evaluate &x - 1 
    // *** this engenders undefined behaviour
    printf("%u %u\n", msizeof(x), sizeof(x));  
}

When an expression that has integral type is added to or subtracted from a pointer ...
<elided for brevity>
... If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

In contrast, changing the macro to: #define msizeof(type) ((char*)(&type + 1) - (char*)(&type))
which attempts to evaluate &x + 1 eschews undefined behaviour because of the special provision:

For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

mike_2000_17 commented: Makes a lot more sense! +14
vijayan121 1,152 Posting Virtuoso

sprout::string from the Sprout C++ Libraries may be of interest.
https://github.com/bolero-MURAKAMI/Sprout

#include <iostream>
#include <sprout/string.hpp>

int main()
{
    constexpr auto hello = sprout::to_string( "hello" ) ;
    constexpr auto world = sprout::to_string( "world" ) ;
    constexpr auto hello_world = hello + " " + world ;

    static_assert( hello_world[5] == ' ', "" ) ;
    static_assert( hello_world.find( "llo worl" ) == 2, "" ) ;
    static_assert( hello_world.rfind( 'l' ) == hello_world.size() - 2, "" ) ;
    static_assert( hello_world.find_first_of( "ord" ) == 4, "" ) ;
    static_assert( hello_world.find_last_not_of( "old" ) == hello_world.size() - 3, "" ) ;
    static_assert( hello_world.back() == *hello_world.rbegin(), "" ) ;


    std::cout << hello_world.substr( 3, 5 ) << '\n' ; // lo wo

    constexpr auto s137 = sprout::to_string( 137 ) ;
    constexpr auto pi = sprout::to_string( double(22) / 7 ) ;
    constexpr auto eqn = s137 + " * " + pi + " = " + sprout::to_string( 137 * double(22) / 7 ) ;

    std::cout << eqn << '\n' ; // 137 * 3.142856 = 430.571429

    static_assert( eqn <= hello_world, "" ) ;
    constexpr auto hash = sprout::to_hash(eqn) ;
    std::cout << hash << '\n' ; // 13698126077260970431
}
vijayan121 1,152 Posting Virtuoso

i tried this simple function but it won't compile
constexpr int multiply( int x, int y ){ return x*y ; }

The November 2013 CTP will compile it.
http://www.microsoft.com/en-us/download/details.aspx?id=41151&751be11f-ede8-5a0c-058c-2ee190a24fa6=True&fa43d42b-25b5-4a42-fe9b-1634f450f5ee=True

vijayan121 1,152 Posting Virtuoso

This is a canonical way to flatten out arrays of more than one (runtime) dimension. (The code below is for three dimensions):

#include <vector>
#include <memory>

template < typename T > struct array_3d_flat
{
    array_3d_flat( std::size_t i, std::size_t j, std::size_t k,
                   const T& v = T() ) : data( i*j*k, v )
    {
        for( std::size_t m = 0 ; m < data.size() ; m += k )
            inner.push_back( std::addressof( data[m] ) ) ;

        for( std::size_t m = 0 ; m < inner.size() ; m += j )
            outer.push_back( std::addressof( inner[m] ) ) ;
    }

    // moveable, non-copyable
    array_3d_flat( const array_3d_flat<T>& ) = delete ;
    array_3d_flat<T>& operator= ( const array_3d_flat<T>& ) = delete ;
    array_3d_flat( array_3d_flat<T>&& ) noexcept = default ;
    array_3d_flat<T>& operator= ( array_3d_flat<T>&& ) = default ;

    T** operator[] ( std::size_t i ) { return outer[i] ; }
    T& operator() ( std::size_t i, size_t j, size_t k )
    { return outer[i][j][k] ; }

    const T** operator[] ( std::size_t i ) const ; // elided for brevity
    const T& operator() ( std::size_t i, size_t j, size_t k ) const ; // elided

    private:
         std::vector<T**> outer ;
         std::vector<T*> inner ;
         std::vector<T> data ;
};

Compiled code is here: http://coliru.stacked-crooked.com/a/7c570672c13ca3bf

vijayan121 1,152 Posting Virtuoso
int main(){

    vector<user> userDetails;
    // string line;
    string userName;
    string password;

    {
        // local scope: we do not want to keep 
        // the stream for longer than necessary
        ifstream readFile("userInfo.txt");

        // while(getline(readFile,line))   {
        // a line consists of just two ws-seperated tokens
        // we can directly read them into userName and password
        while( readFile >> userName >> password )   {
            // stringstream iss(line);
            // iss >> userName >> password;
            // user userInfoDetails(userName,password);

            // using the object anonymously makes for clearer code
            userDetails.push_back( user(userName,password) );
        }
        // readFile.close();
        // the destructor of the stream will close it
    }

    cout << "Before Deletion" << endl;
    for ( /*int*/ std::size_t i =0; i<userDetails.size(); i++) {
       cout << userDetails[i].getUserName() << " " 
            << userDetails[i].getPassword() << "\n";
    }

    cout << " " << endl;
    string name;
    cout << "Enter User Name to delete: ";
    cin >> name;
    cout << " " << endl;

    for (/*int*/ std::size_t i = 0; i<userDetails.size(); /* i++ */ ) {

            if(userDetails[i].getUserName() == name){
                 // userDetails.erase(userDetails.begin() + i);

                 // if we do not need to maintain an ordered sequence
                 // this is the canonical way to remove an element
                 // cheaper than: userDetails.erase(userDetails.begin() + i);
                 std::swap( userDetails[i], userDetails.back() ) ;
                 userDetails.pop_back() ;
                 // break ; // uncomment if there are no duplicated names
            }

            else ++i ; // increment only if the element at i is not erased
                 // if we have erased the element at position i,
                 // a new element has come into that position;
                 // and we …
Ancient Dragon commented: nice solution :) +14
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

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

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

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

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

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

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

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

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

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
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
};
vijayan121 1,152 Posting Virtuoso

Visual Studio 2012 (November update).

Way ahead of GCC (the other major contender) in C++11 conformance - Microsoft has implemented almost everything in the standard.

clang 3.2 with its libc++ is on par with VS 2012; and it is somewhat more mature and stable in comparison. But it has to be built from sources; and installing it is not an easy task for everyone.

vijayan121 1,152 Posting Virtuoso

I want to give the customer a 'CurrentAccount' which is inherited from Account; and then store it in an array of Accounts.
How do I go about doing this?

You can't. Account acnts[10]; holds objects of type Account by value.
When you try to store an object of type CurrentAccount into that array it gets sliced.
http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c

Use an array of pointers to Account instead: Account* ptr_accts[10];

Note: Ideally std::shared_ptr<Account> or std::reference_wrapper<Account> depending on the storage duration; but this may be beyond what you have learned till now.