vijayan121 1,152 Posting Virtuoso

s[i] + s[i+1] + s[i+2]; would just do an integral addition of the three char values; instead you need to make a std::string of three chars.

I suppose for (int i=0; i < s.length() - 2; i+3) is a typo;
should be for( int i=0 ; i < s.length() - 2 ; i += 3 ).

Something like:

std::vector< std::string > strand_to_codons( const std::string& strand )
{
    std::vector< std::string > codons ;

    for( std::string::size_type i = 0 ; i < strand.size() - 2 ; i += 3 )
    {
        const char temp[] = { strand[i], strand[i+1], strand[i+2], 0 } ;
        codons.emplace_back(temp) ;
    }

    return codons ;
}

Another option would be to use the substr() member function of std::string:

std::vector< std::string > strand_to_codons( const std::string& strand )
{
    std::vector< std::string > codons ;

    for( std::string::size_type i = 0 ; i < strand.size() - 2 ; i += 3 )
            codons.push_back( strand.substr( i, 3 ) ) ;

    return codons ;
}

Yet another way is to construct the substring in situ into the std::vector<> via an emplace_back() (requires compiler support for variadic templates).

std::vector< std::string > strand_to_codons( const std::string& strand )
{

    std::vector< std::string > codons ;

    for( auto iter = strand.begin() ; iter < strand.end()-2 ; iter += 3 )
            codons.emplace_back( iter, iter+3 ) ;

    return codons ;
}
vijayan121 1,152 Posting Virtuoso

Put the class definition in a header file of its own and include that header in other translation units.

See: http://www.informit.com/articles/article.aspx?p=26039

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
void foo( boost::asio::ip::tcp::iostream& stm )
{
    std::size_t bytes_available = stm.rdbuf()->available() ;
    // ...

    // the native socket descriptor can be retrieved for platform specific 
    // socket functionality not available through asio. for example:
    auto fd = stm.rdbuf()->native_handle() ; // version 1.48. 
    // IIRC, used to be stm.rdbuf()->native() earlier
    ::ifreq interface_request ;
    ::ioctl( fd, SIOCGIFNETMASK, &interface_request ) ;
    // ...
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

SetConsoleScreenBufferSize() to a size that is not larger than the console window size.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686044%28v=vs.85%29.aspx

vijayan121 1,152 Posting Virtuoso

> My professor said this is useful in the event that your program is being "attacked."

Useful, only if you are using C-style arrays of char.

Don't create a problem that did not exist in the first place, and then try to solve it; just use std::string instead. std::string is not vulnerable to buffer overflow exploits on user input; if you use the member function at() instead of [] for element access, it is safe even if there are programming errors. Unless you decide to use its buffer as a C-style array of modifiable chars, in which case you deserve to be subject to every bad thing that could possibly happen.

The second problem with restricting the number of characters that can be entered is that if the input is too long, crud is left in the stream buffer which has to be than read and discarded prior to the next input. Just reading in whatever is entered, and then truncating the string if it turns out to be too long is simpler.

Something like:

std::string name ;
    constexpr std::string::size_type MAX_CHARS = 20 ;

    if( std::cout << "name (max " << MAX_CHARS << " chars)? " && std::getline( std::cin, name  ) )
    {
        if( name.size() > MAX_CHARS )
        {
            std::cerr << name << " is too long; truncating it\n" ;
            name = name.substr( 0, MAX_CHARS ) ;
        }
        // use name
    }

    // else i/o error
vijayan121 1,152 Posting Virtuoso

> My intentions are to first take everything from the file into a variable,
> then save everything from Start to the first comma minus the comma to a second variable,
> and so on so forth till EOF where each string or value between commas is saved as a separate variable

To split a std::string into separate tokens using a single delimiter, std::getline() and std::istringstream turn out to be quite handy.

std::vector< std::string > split( const std::string& str, char delimiter = ',' )
{
    std::vector< std::string > result ;
    std::istringstream stm(str) ;
    std::string token ;
    while( std::getline( stm, token, delimiter ) ) result.push_back(token) ;
    return result ;
}
Xaviorin commented: I have no rep power so here is a +zero thank you! +0
vijayan121 1,152 Posting Virtuoso

> Alternative once you have the index of the decimal point in the string, remove it,
> reverse the string, and insert the decimal point back into the string

Yes, Lerner. The simple way is the best way - if you want to manipulate text, treat it as text; if you want to perform arithmetic, treat it as a number.


> before using a stringstream to convert the string back to a floating point value

Just read it in as a string. Also sidestep the murky area of floating point rounding errors. Something like:

bool reverse_amounts( const char* in_path, const char* out_path )
{
    std::ifstream input(in_path) ;
    std::ofstream output(out_path) ;
    std::string id, amount ;
    while( input >> id >> amount ) output << id << ' ' << reverse_amount(amount) << '\n' ;
    return input.eof() && output.good() ;
}

> Such a mess. Much easier if file format restricted to known number of digits
> to the right of the decimal point.

It is a known number of digits to the right of the decimal point. Just that it is not a constant known at compile-time.

std::string reverse_amount( std::string amount )
{
    constexpr char DOT = '.' ;
    auto dot_pos = amount.find( DOT ) ; // locate the dot
    bool found_dot = dot_pos != std::string::npos ;
    if(found_dot) amount.erase( dot_pos, 1 ) ; // remove it
    std::reverse( amount.begin(), amount.end() ) ; // reverse the string
    if(found_dot) amount.insert( dot_pos, 1, DOT ) ; …
vijayan121 1,152 Posting Virtuoso

> Is there any other way to make the system identify and pass the return type also ?
> So that return type can also change dynamically depending on input.

Ask the compiler to deduce what the appropriate return type is:

template< typename A, typename B > inline
auto max_of( const A& a, const B& b ) -> decltype( a<b ? b : a )
{ return a<b ? b : a ; }

std::common_type<> in <type_traits> would do it for you:

template< typename A, typename B > inline
typename std::common_type<A,B>::type max_of( A a, B b )
{ return a>b ? a : b ; }

Which extends quite nicely to (if the implementation is conforming wrt variadic template parameters):

template< typename FIRST, typename... REST > inline
typename std::common_type<FIRST,REST...>::type max_of( FIRST first, REST... rest )
{ return max_of( first, max_of( rest... ) ) ; }

int main()
{
    std::cout << std::showpoint << max_of( 2UL, 56LL, 'a', 17.9f, 78, 89.4 ) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

> ... then instead of inserting the (key, value) pairs in a map, insert the (value, key) pairs into a multimap.

Would have to programmatically take care of the keys being unique, which makes it a bit messy.


Use Boost Bimap, perhaps?
http://www.boost.org/doc/libs/1_48_0/libs/bimap/doc/html/index.html

Something like:

#include <iostream>
#include <boost/bimap/bimap.hpp>
#include <boost/bimap/multiset_of.hpp>

int main()
{
    using namespace boost::bimaps ;
    typedef bimap< char, multiset_of< int, std::greater<int> > > map_type ;
    typedef map_type::value_type value_type ;

    map_type alphabet ;
    alphabet.insert( value_type( 'a', 30 ) ) ;
    alphabet.insert( value_type( 'b', 50 ) ) ;
    alphabet.insert( value_type( 'c', 40 ) ) ;
    alphabet.insert( value_type( 'd', 70 ) ) ;
    alphabet.insert( value_type( 'e', 40 ) ) ;

    const auto& map_char_to_int = alphabet.left ;
    for( auto iter = map_char_to_int.begin() ; iter != map_char_to_int.end() ; ++iter )
        std::cout << iter->first << ' ' << iter->second << "  " ;
    std::cout << '\n' ;
    // a 30  b 50  c 40  d 70  e 40

    const auto& map_int_to_char = alphabet.right ;
    for( auto iter = map_char_to_int.begin() ; iter != map_char_to_int.end() ; ++iter )
        std::cout << iter->first << ' ' << iter->second << "  " ;
    std::cout << '\n' ;
    // 70 d  50 b  40 c  40 e  30 a
}
vijayan121 1,152 Posting Virtuoso

> Is it possible to have my table centered?

Yes. See: http://www.cprogramming.com/tutorial/iomanip.html

> would it be possible to simply enter this data into my template at the bottom?
> If so, how would I go about doing that?

The standard C++ library provides no facilities for doing this. You would need to use a library like curses.
http://en.wikipedia.org/wiki/Curses_%28programming_library%29

Don't think you should be bothering about this right now.

vijayan121 1,152 Posting Virtuoso

Or (slightly more efficient if there are a fair number of questions) generate a random sequence to determine the order in whick questions are to be asked.

int random_sequence[QUEST] ;
for( int i=0 ; i<QUEST ; ++i ) random_sequence[i] = i ;
std::random_shuffle( random_sequence, random_sequence+QUEST ) ; // <algorithm>
for( int i=0 ; i<QUEST ; ++i )
{
     int choice = random_sequence[i] ;
     // ...
}
thines01 commented: Excellent suggestion! +9
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

Use std::istringstream

std::string str = "I have a dog" ;
std::istringstream stm(str) ;
string word ;
while( stm >> word ) // read white-space delimited tokens one by one 
{
   // put word into array
}
vijayan121 1,152 Posting Virtuoso

The value_type of your stack (the type of elements it contains) is a fixed-size array. Define a member in your stack class to hold up to some max number of such elements, and keep track of the current logical size programmatically.

Something like:

template< typename T, std::size_t ARRAY_SIZE, std::size_t MAX_STACK_SIZE = 1024 >
struct stack_of_arrays
{
    typedef T value_type[ ARRAY_SIZE ] ;

    stack_of_arrays() : curr_size(0) {} // initialize to empty stack

    void push( const value_type& a ) // push an array T[ARRAY_SIZE]
    {
        if( curr_size == MAX_STACK_SIZE ) throw "stack is full" ;
        for( std::size_t i = 0 ; i < ARRAY_SIZE ; ++i ) stk[curr_size][i] = a[i] ;
        ++curr_size ;
    }

    void pop( const value_type& a ) // pop the array on top of the stack
    {
        if( curr_size == 0 ) throw "stack is empty" ;
        --curr_size ;
        //for( std::size_t i = 0 ; i < ARRAY_SIZE ; ++i ) stk[curr_size][i] = T() ; // if required
    }

    value_type stk[MAX_STACK_SIZE] ;
    std::size_t curr_size /* = 0 */ ;

    // TODO: add other stack operations like size, empty, top etc.
};
vijayan121 1,152 Posting Virtuoso

The header <vector> already defines

template< typename T, typename A >
bool operator< ( const std::vector<T,A>& , const std::vector<T,A>& ) ;
//performs a lexicographical comparison of the sequences (uses std::less<T>)

and

template< typename T, typename A >
bool operator== ( const std::vector<T,A>& , const std::vector<T,A>& ) ;

So this would suffice. Subject to comparing two float values f1 and f2 by f1<f2 or f1==f2 being ok for your program.

typedef std::vector<float> Vec_float ;
typedef std::vector<Vec_float> matrix_float ;

void make_unique( matrix_float& m )
{
    std::sort( m.begin(), m.end() ) ;
    m.erase( std::unique( m.begin(), m.end() ), m.end() ) ;
}
LopezGG commented: Simple and efficient solution +0
vijayan121 1,152 Posting Virtuoso

> Is the member variable from the base class renamed?

No. There is no need to rename it; the fully qualified name of x in A is A::x and the fully qualified name of x in B is B::x.

Normal scoping rules apply for name look up; if a name is not found in an inner scope, the outer scope is looked up. The name of the base class behaves in a way similar to an outer scope.

#include <iostream>

struct A
{
    int x ;
    int y ;
};

struct B : A
{
    int x ;
    void foo( int x ) ;
};

void B::foo( int x )
{
    std::cout << x << ' ' // local variable 'x'
              << B::x << ' ' // member variable 'x' in B
              << A::x << '\n' ; // member variable 'x' inherited from A

    std::cout << y << ' ' // no local variable 'y', this->y
              << B::y << ' ' // no member variable 'y' in B, so A::y
              << A::y << '\n' ; // member variable 'y' in A (inherited by B)
}

> but how would this be implemented in C let's say ...? How would the class D as struct look ?
> To make it short , how is actually INHERITANCE IMPLEMENTED?
> ..my guess is that all compilers somehow go the same way ...

Compilers implement it by having an anonymous base class sub-object in the derived class …

vijayan121 1,152 Posting Virtuoso

Use std::result_of<> instead of boost::result_of<>

#include <functional>

struct S
{
    double operator() ( char, int& ) const ; // omitting const here is a (very) bad idea
};

int main()
{
    return sizeof( std::result_of< S(char, int&) >::type ) == sizeof(double) ;
}

From Boost documentation:
"If decltype is not enabled, then automatic result type deduction of function objects is not possible. Instead, result_of uses the following protocol to allow the programmer to specify a type. When F is a class type with a member type result_type, result_of<F(T1, T2, ..., TN)> is F::result_type. When F does not contain result_type, result_of<F(T1, T2, ..., TN)> is F::result<F(T1, T2, ..., TN)>::type when N > 0 or void when N = 0. Note that it is the responsibility of the programmer to ensure that function objects accurately advertise their result type via this protocol"

vijayan121 1,152 Posting Virtuoso

This is the typical producer-consumer scenario.
http://simpy.sourceforge.net/producer_consumer.htm

The most efficient way would be to use a wait-free or lock-free fifo or ringbuffer.

You could use one of

Boost Lockfree http://tim.klingt.org/boost_lockfree/
(Recently voted into Boost, but not yet part of the distribution. Download from http://tim.klingt.org/boost_lockfree.tar.gz

Herb Sutter's implementation presented in DDJ
http://drdobbs.com/high-performance-computing/210604448

Microsoft's (VC++10) Concurrency::concurrent_queue<> in <concurrent_queue.h>
{Windows/Intel/Microsoft specific).

vijayan121 1,152 Posting Virtuoso

> Is this kind of assignment well defined?

yes; it is well-defined and well-behaved. Calls release() on the auto_ptr.

vijayan121 1,152 Posting Virtuoso

Have a look at RapidXML, perhaps? Extremely good as long as DTD support is not required.
http://rapidxml.sourceforge.net/

From the Boost Property Tree documentation:
"The XML format is an industry standard for storing information in textual form. Unfortunately, there is no XML parser in Boost as of the time of this writing. The library therefore contains the fast and tiny RapidXML parser (currently in version 1.13) to provide XML parsing support. RapidXML does not fully support the XML standard; it is not capable of parsing DTDs and therefore cannot do full entity substitution."

There was a discussion about this in lib.boost.devel and the consensus there was to use RapidXML.

vijayan121 1,152 Posting Virtuoso

> a technically correct answer isn't always the best answer to a question.

I realize that a question that is asked is not always the most appropriate one. Though in this case there is no evidence to suggest that that is the case. No matter what, deliberately giving a misleading answer is never right, let alone repeatedly insisting that that wrong answer is the right one.


> That doesn't warrant any attacks on his technical knowledge.

I have been careful throughout not to introduce personal elements into a technical discussion. I wasn't the one who introduced them; and even then I restricted by response to contesting the patently absurd claim that number of posts and being a moderator here is proof of undeniable technical eminence.

You are entitled to your opinions of course, just as much as I am to mine. And in my opinion, it is your presumptuous comment that is completely unwarranted.

vijayan121 1,152 Posting Virtuoso

> (note my post count and Mod status -- I do know something )

Your post count is a number that says absolutely nothing about the quality of your posts.

A moderator here performs two roles - that of a policeman and that of a sanitation worker. Your moderator status implies that you are adept at those two tasks. As a member of this community, I'm very grateful to you for that. However, it too says absolutely nothing about the quantum of your knowledge.

A stalwart member of the constabulary, who is also an accomplished janitor to boot, is someone to be admired. Be that as it may, that alone does not make him eminently qualified to teach differential calculus.


> It was to make the OP think about his question.

Ah, I see. The OP wanted a Unix timestamp - an unsigned 32-bit value which held the number of seconds elapsed since midnight UTC, January 1, 1970 (not counting leapseconds). Informing him that this is just what time() returns on any non-posix implementation must be the best way to make him think long and hard.

WaltP commented: Stop being pedantic. You've been here long enough to know hacks don't become moderators. Basically, you have less cred than I do in that case. -4
vijayan121 1,152 Posting Virtuoso

> What should we set for the template parameter of the packaged_task?#1 or #2?

#1 if the packaged_task is boost::packaged_task<> which is defined this way:

template< typename RESULT_TYPE > class packaged_task
{
    public:
        // construction and destruction
        template< typename FUNCTION_TYPE > explicit packaged_task( const FUNCTION_TYPE& f ) ;

        explicit packaged_task( RESULT_TYPE(*f)() ) ;

        template< typename FUNCTION_TYPE > explicit packaged_task( FUNCTION_TYPE&& f ) ;

        // ...

#2 if the packaged_task is std::packaged_task<> which is defined this way:

template<typename> class packaged_task ; // generalization is undefined

template< typename  RESULT_TYPE,  typename... ARG_TYPES >
class packaged_task< RESULT_TYPE( ARG_TYPES... ) > // what we use is this specialization
{
public:
    typedef RESULT_TYPE result_type;

    // construction and destruction
    packaged_task();

    template <typename FUNCTION_TYPE > explicit packaged_task( const FUNCTION_TYPE& f ) ;

    explicit packaged_task( RESULT_TYPE(*f)() ) ;

    template <typename FUNCTION_TYPE > explicit packaged_task( FUNCTION_TYPE&& f ) ;

    // ...

Using std::packaged_task<>

struct my_task : std::binary_function< bool, double, int >
{
    result_type operator() ( double d, int i ) const
    {
       return std::cout << "my_task: { " << d << ", " << i << " }\n" ;
    }
};

void test_it()
{
  std::packaged_task < bool( double, int ) > atask( my_task, 7.84, 6789 ) ;
  std::unique_future<bool> future( atask.get_future() ) ;
  std::thread( std::move( atask ) ) ;
  // do something
  future.wait() ;
}
vijayan121 1,152 Posting Virtuoso

> I'm trying to pass fout between functions.

You cannot pass a stream object to a function by value - the copy constructor is private / deleted.

Pass by reference instead: void my_function( std::ostream& fout ) ;

vijayan121 1,152 Posting Virtuoso

See http://www.daniweb.com/software-development/cpp/threads/393577

You can specify a hash function for std::unordered_set in a similar way.

For all of the words in a dictionary, the default hash function for std::string would work quite well, though.

vijayan121 1,152 Posting Virtuoso

Hint:
Each element in {3,5,7,9,11} is the corresponding element in {2,4,6,8,10} plus one.
Each element in {6,10,14,18,22} is the corresponding element in {3,5,7,9,11} multiplied by two.

vijayan121 1,152 Posting Virtuoso

> The question is will calling time() on Unix give a different time than on Windows?
> In other words, would Unix give Mar 10, 2009 10:13AM and Windows give Mar 11, 2009 10:18AM ?

time() is a C function; so what it returns depends on the implementation of the C runtime library. For instance, on Windows the Cygwin library and Microsoft CRT will return completely different values.

The result type of time() is an implementation-defined time_t. In every conforming implementation, time_t holds the representation of an abstract time point (a point in the abstract time continuum defined by the implementation).

Mar 10, 2009 10:13AM etc are wall-clock times specific to a calendar system and a time system. (An approximate mapping between the abstract time point and wall-clock times belonging to two calendar time systems are also part of the standard C library.)

> I want to get unix time in my program....
> Is there an easy (can fit in less than 20 lines of non-system dependent functions
> and without any API or WIN32 [unless simple] functions) way to do this?

IMHO, mike_2000_17's suggestion - use Posix Time from Boost Date_Time library - is by far the best.

If you want to do it yourself, this is the kind of thing that is normally done when a mapping between Windows time and Unix time is required. (The code is based on that from Citrix.)

#include <cstdint>
#include <windows.h> …
vijayan121 1,152 Posting Virtuoso
class telnumber
{
public:
	telnumber();
	telnumber (string i_npa, string i_nxx, string i_line);
	virtual ~telnumber(); // the destructor must be virtual
	void setnpa (string newnpa);
	void setnxx (string newnxx);
	void setline (string newline);
	string getnpa();
	string getnxx();
	string getline();
        
        // This must be defined or it should be declared as a pure virtual 
	virtual void printtostream(ostream& out);  
	
private:
	string npa;
	string nxx;
	string line;
	
};

And on line 190:

void < a class name here? >::printtostream(ostream& out)

Implement every non-pure virtual function in a class with at least one of them being defined out of line.
See: http://www.daniweb.com/software-development/cpp/threads/114299

vijayan121 1,152 Posting Virtuoso

> Seriously, what is the difference between calling time() on Unix vs Windows?

Seriously? It depends. Entirely on the C library implementation that is being used.

POSIX requires that time() returns a 32-bit integral type holding the number of seconds elapsed since midnight (UTC) of January 1, 1970, not counting leap seconds since 1970. C/C++ implementations on Unix adhere to the POSIX specification.

On a non-posix system, using an implementation where the particular compiler vendor does not guarantee POSIX conformance, things are far more nebulous. The C standard itself doesn't specify anything more than time_t being an arithmetic type capable of representing calendar time. It doesn't specify the epoch; or for that matter that there should be an epoch at all or that leap seconds exist. It also doesn't specify the granularity of time_t other than that it is implementation-dependent. On one implementation, time_t could be a signed integral type holding one hundreths of a second since some epoch foo. On another, it might be a double representing seconds, with fractional milliseconds, since some other epoch bar.

Hence, the C standard also has:
double difftime( time_t time1, time_t time0 ) ;
"The difftime() function shall return the difference between two calander time values expressed in seconds as a type double."

And C++ felt the need to add <chrono>.

mike_2000_17 commented: it was about time in this thread for a real answer to come! nice! +14
vijayan121 1,152 Posting Virtuoso

> Well I know what a unwary function is.

Good.

> I don't know why we use it here. What if we don't use it?

Read the third post in this thread once again; this time paying attention to the comment at line number six of the code snippet. And thou shalt be enlightened.

vijayan121 1,152 Posting Virtuoso

> What are the cases would make us like to use std::promise rather than std::package?

std::future and std::promise are fairly low level, primitive constructs. AFAIK, these are expected to be the building blocks used to create high level abstractions (like lock-free data structures).

The basic idea is a good one - separate the communication channel (std::promise) from the thread creation and synchronization mechanisms. This allows a lot of flexibility in the creation of higher level constructs.


> What is the meaning of ...

typedef int result_type ;
std::packaged_task<result_type> // #1. is std::packaged_task<int>  
std::packaged_task< result_type() > // #2. is std::packaged_task< int() >

In #1, the template parameter is an int.
In #2, the template parameter is a nullary function which returns an int.

vijayan121 1,152 Posting Virtuoso

> What is the "path" in the parameters for the CreateProcess function?

The complete path to the executable file.
For example, "C:\\windows\\system32\\notepad.exe"

An option is to leave the lpApplicationName as NULL and put both the application name and the command line parameters in a modifiable string and pass that as lpCommandLine (The search path could be used in this case).
For example, "notepad.exe myfile.txt"

vijayan121 1,152 Posting Virtuoso

> But I used <td(.*)</td> .. and it finds one match.. Any Ideas?

With the given text, it should find just one match. That repeat operator is greedy; it will consume as much input as possible.

Use the non-greedy repeat operator instead: <td.*?/td>

Repeat: Use boost::sregex_iterator, perhaps?

Like this:

#include <string>
#include <vector>
#include <boost/regex.hpp>

std::vector<std::string> preg_match_all( const std::string& str, const boost::regex& regex )
{
    std::vector<std::string> matches ;
    boost::sregex_iterator begin( str.begin(), str.end(), regex ), end ;
    for( ; begin != end ; ++begin ) matches.push_back( begin->str() ) ;
    return matches ;
}
vijayan121 1,152 Posting Virtuoso

> I just didn't understand what this does
> std::unary_function< const std::string&, std::size_t >

Google for std::unary_function, perhaps?

Might, just might, throw up results like this: http://www.sgi.com/tech/stl/unary_function.html

vijayan121 1,152 Posting Virtuoso

std::future<> and std::promise<> form a pair; together they provide an asynchronous inter-thread communication channel through which a value (or an exception) can be passed from one thread to another. std::promise<> is used by the function which wants to set a value, which can then be retrieved by another thread through the associated std::future<>.

std::packaged_task gives an easy to use wrapper over this: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2709.html

vijayan121 1,152 Posting Virtuoso

Use boost::sregex_iterator, perhaps?

http://www.boost.org/doc/libs/1_47_0/libs/regex/doc/html/boost_regex/ref/regex_iterator.html
(There is an example at the end of the page.)

vijayan121 1,152 Posting Virtuoso

> The idea of policy based class design is very attractive,
> yet it is not so popular in the real world.

I think it is widely used in the real world; the idea of separating policy from infrastructure is fairly old. Goes under several names - strategy pattern, policy parameterization and so on.

Some real life examples would be:

  • locales (which contain facets) composed with iostreams.
  • allocators providing memory management policy for containers.
  • character traits providing policy for std::basic_string<>
  • the desktop environment providing ui policy and the X-server providing infrastructure.
  • lsass.exe providing the security policy and the NT kernel providing the infrastructure.
vijayan121 1,152 Posting Virtuoso

Ah! Didn't know that.

Thank you.

vijayan121 1,152 Posting Virtuoso

The number of entries at each level in a binary heap is a power of two; 1, 2, 4, 8, ...and so on ( 2^N starting with N==0 ).

So you need to put a new line to start the next level after 1, 3, 7, 15 and so on. ie. after every 2^(N-1) entries starting with N==1.

vijayan121 1,152 Posting Virtuoso
template < typename ITERATOR, typename T >
void iota( ITERATOR begin, ITERATOR end, T value ) ;

is part of (SGI) STL; it is not part of the standard C++ library.

Unless you are using SGI STL (or one of its derivatives), it is likely that this function is not there at all. It is trivial to implement it on your own, though:

template < typename ITERATOR, typename T >
inline void iota( ITERATOR begin, ITERATOR end, T value )
{
   for( ; begin != end ; ++begin, ++value ) *begin = value ;
}
vijayan121 1,152 Posting Virtuoso

Make the code const-correct.
http://www.parashift.com/c++-faq-lite/const-correctness.html

template <class Entry>
class HashTable
{
public:
    HashTable(); //constructor

	Key hash_function( const Entry &x ) const ;
	void insert( const Entry &k );
	std::vector<list<Key>> my_vec[97];
};

// also in the definitions
vijayan121 1,152 Posting Virtuoso

You might first want to learn using a game programming library; for instance Allegro.
http://alleg.sourceforge.net/

And then learn to use a library for 3D graphics; for instance OpenGL.

Ideally, post your questions on boards that specializes in game programming; for instance GameDev
http://www.gamedev.net/index

vijayan121 1,152 Posting Virtuoso

Looks good to me.

Test it out to make sure it's working.

With variadic templates (using the earlier 'indexof'):

template< typename T > struct unique ;

template<> struct unique< typelist<> > { typedef typelist<> type ; } ;

template< typename FIRST, typename ...REST > struct unique< typelist<FIRST,REST...> >
{
    typedef typename unique< typelist<REST...> >::type urtype ;
    typedef typename std::conditional<
                        indexof< FIRST, typelist<REST...> >::value == -1,
                        typename push_front< FIRST, urtype >::type, urtype >::type type ;
};
vijayan121 1,152 Posting Virtuoso

> is there any way to do something like that?

The short answer is: No.

vijayan121 1,152 Posting Virtuoso

> I found a solution from
> htp://stackoverflow.com/questions/6032089/position-of-a-type-in-a-variadic-template-parameter-pack

Needlessly over-elaborate, isn't it? This would suffice:

template< typename T, typename U, int N = 0 > struct indexof ;

template< typename T, int N > struct indexof< T, typelist<>, N > { enum { value = -1 } ; };

template< typename T, typename FIRST, typename ...REST, int N >
struct indexof< T, typelist<FIRST,REST...>, N >
            : std::conditional< std::is_same<T,FIRST>::value,
                                std::integral_constant<int,N>,
                                indexof< T, typelist<REST...>, N+1 > >::type {} ;

All that we need to do is recursively unpack the parameters one by one, keeping a count of how many have been unpacked so far, and ending the recursion if the type has been found (or the last parameter has been unpacked).

vijayan121 1,152 Posting Virtuoso

First read up on what a good hash function should do, and choose a hash algorithm.
http://en.wikipedia.org/wiki/Hash_table#Hash_function

Then implement the hash function keeping in mind what C++ requires of the hash function.
For example, if you have opted for the UNIX 32-bit ELF hash,

#include <functional>
#include <string>

//  C++ requirements:
//  must be a function object type that is default_constructible, copy_assignable and swappable
//  must have the nested types 'argument_type' and 'result_type' (std::size_t)
struct elf_hash_32bit : std::unary_function< const std::string&, std::size_t >
{
    // should not throw any exceptions
    std::size_t operator() ( const std::string& key ) const /* can add noexcept or throw() here */
    {
       std::size_t hash = 0U ;
       const std::size_t mask = 0xF0000000 ;

       for( std::string::size_type i = 0 ; i < key.length() ; ++i )
       {
          hash = ( hash << 4U ) + key[i] ;
          std::size_t x = hash & mask ;
          if( x != 0 ) hash ^= ( x >> 24 ) ;
          hash &= ~x ;
       }

       return hash;
    }
};

Instantiate the unordered_map<> with your hash function.

#include <unordered_map>
std::unordered_map< std::string, std::string, elf_hash_32bit > m ;
vijayan121 1,152 Posting Virtuoso

The absence of variadic templates is the fundamental problem with Microsoft C++. It surfaces in several different places posing as different problems.

This is (in effect) what the IS says:

template< typename... TYPES > tuple<TYPES...> std::make_tuple( TYPES&&... args ) ;

returns std::tuple<TYPES...>( std::forward<TYPES...>(args...) ) ;

with std::reference_wrapper<T> unwrapped to T&

Microsoft does not have variadic templates, so they implemented it using a bunch of preprocessor macros and in the process replaced the r-value references with l-value references to const.
http://msdn.microsoft.com/en-us/library/bb982346.aspx

vijayan121 1,152 Posting Virtuoso