Boost::uuid (C++) http://www.boost.org/doc/libs/1_42_0/libs/uuid/index.html
or the GUID struct (C) in <windows.h> http://msdn.microsoft.com/en-us/library/aa373931%28VS.85%29.aspx
Boost::uuid (C++) http://www.boost.org/doc/libs/1_42_0/libs/uuid/index.html
or the GUID struct (C) in <windows.h> http://msdn.microsoft.com/en-us/library/aa373931%28VS.85%29.aspx
AFAIK, SDL event polling can't be done in a thread other than the thread that set the video mode.
You could do something like this: The main thread (which set the video mode) polls for events and when an input event is received, it pushes it into (an appropriately synchronized) queue. The event handling thread runs a loop which waits on the queue, picks up events from it and then handles it.
Don't boost::filesystem::remove_all and boost::filesystem::remove require a full path as the argument?
AFAIK, lines 20 and 28 should have checkAndRemove( dir_iter->path(), BAD_TYPES )
instead of checkAndRemove( dir_iter->path().leaf(), BAD_TYPES )
If you feel at home with templates, you might want to have a look at boost::multi_index<>. http://www.boost.org/doc/libs/1_42_0/libs/multi_index/doc/index.html
For example, a multi_index with two ordered non_unique keys would look something like this:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace ::boost ;
using namespace ::boost::multi_index ;
using namespace std ;
struct A
{
A( int i, const char* n, double d ) : id(i), _name(n), _data(d) {}
const int id ; // non-unique key
const string& name() const { return _name ; } // non-unique key
// tags for lookup
struct by_id {} ;
struct by_name {} ;
private :
string _name ;
double _data ;
// ...
friend inline ostream& operator<< ( ostream& stm, const A& a )
{
return stm << "{ " << a.id << ", " << a.name()
<< ", " << a._data << " }" ;
}
} ;
typedef multi_index_container
<
A,
indexed_by<
ordered_non_unique< tag<A::by_id>,
BOOST_MULTI_INDEX_MEMBER( A, const int, id ) >,
ordered_non_unique< tag<A::by_name>,
BOOST_MULTI_INDEX_CONST_MEM_FUN( A, const string&, name ) >
>
> dual_key_multimap ;
template< typename TAG, typename MULTI_INDEX_CNTR > inline
void print( MULTI_INDEX_CNTR& multi_index_cntr, ostream& stm = cout )
{
typename MULTI_INDEX_CNTR::template index<TAG>::type& seq =
multi_index_cntr.get<TAG>() ;
copy( seq.begin(), seq.end(),
ostream_iterator<typename MULTI_INDEX_CNTR::value_type>(stm,"\n") ) ;
}
template< typename TAG, typename MULTI_INDEX_CNTR, typename KEY > inline
void erase_all_with_key( MULTI_INDEX_CNTR& multi_index_cntr, const KEY& key )
{
typedef typename MULTI_INDEX_CNTR::template index<TAG>::type SEQ ;
SEQ& seq = multi_index_cntr.get<TAG>() ;
seq.erase( seq.lower_bound(key), seq.upper_bound(key) ) ; …
The value_type of a std::multimap<KEY,T>
is std::pair< const KEY, T >
. So,
std::multimap<SortKey,T> firstMap;
std::multimap<SearchKey, pair< const SortKey, T >* > secondMap;
// ...
std::multimap<SortKey,T>::iterator it = firstMap.insert( std::make_pair(key1,data) ) ;
std::pair< const SortKey, T >* mizi = &*it ;
secondMap.insert( std::make_pair(key2,mizi) ) ;
// ...
Either overload operator< for node or write a binary predicate to compare nodes. eg.
struct compare_cost
{
bool operator() ( const node& a, const node& b ) const
{ return a.cost < b.cost ; }
};
If you just need a priority queue, just use std::priority_queue<> std::priority_queue< node, std::deque<node>, compare_cost > node_pq ;
If you really need to keep a sorted sequence at all times (expensive), use a sequence container and the std::lower_bound algorithm.
void insert_ordered( std::list<node>& seq, const node& item )
{
seq.insert( std::lower_bound( seq.begin(), seq.end(),
item, compare_cost() ), item ) ;
}
Your build of the boost-thread library appears to be broken; built without MT support. MSVCRT and MSVCRTD are the single-threaded runtime libraries, you should not link to one of these libraries in any program that uses threads of any kind - native, Boost, POCO, ACE, wxWidgets, whatever.
Either use Boost.Build to rebuild the binary libraries correctly. Or download and install pre-built boost binaries for Windows by running this setup program from BoostPro http://www.boostpro.com/download/boost_1_44_setup.exe
> If POCO is easier than BOOST(for threading, i sure will try it.
POCO and Boost address different audiences. Boost gives general functionality that could conceivably be part of a standard library with flexibility and performance as overriding design goals. POCO is much more like ACE - more of a framework library giving you readily usable components (akin to the Java/J2EE library) with the attendant cost of having more dependencies between parts; it's more of a heavyweight 'all or nothing' library with higher run-time overheads.
Both ACE and POCO tend to use far less bleeding edge features of C++ than Boost - unlike with Boost, you don't have to be a C++/template guru to understand the source code for either of these. ACE is more mature and robust, but is somewhat dated in its coding style. POCO source code is very well written - quite easy to read and understand even for a beginner in C++.
If I just wanted a library for portable threading with some ipc mechanisms, I …
Add a const qualifier to the string in void *getfile( string url, const char *file );
CUROPT_URL requires a c-style string for the url. curl_easy_setopt(curl, CURLOPT_URL, url.c_str() );
Parse the type string (int, char, float etc.) and the data in text form into strings.
If the possible types are known before hand, a simple if/else if construct would do the job.
#include <string>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <stdexcept>
template< typename T >
void do_push_back( std::vector<T>& v, const std::string& text_data )
{ v.push_back( boost::lexical_cast<T>(text_data) ) ; }
void push_back( const std::string& type_name,
const std::string& text_data,
std::vector<int>& int_vec,
std::vector<char>& char_vec,
std::vector<float>& float_vec )
throw( boost::bad_lexical_cast, std::invalid_argument )
{
if( type_name == "int" ) do_push_back( int_vec, text_data ) ;
else if( type_name == "char" ) do_push_back( char_vec, text_data ) ;
else if( type_name == "float" ) do_push_back( float_vec, text_data ) ;
else throw std::invalid_argument( "unknown type" ) ;
}
#include <typeinfo>
template <typename MatTypeOne, typename MatTypeTwo>
void funct(MatTypeOne& m1, MatTypeTwo& m2)
{
if( typeid(m1) == typeid(m2) )
{
// objects m1 and m2 are of the same (run-time) type
}
}
> Would it be efficient to create separate lookup tables for, say, common functions
> (i.e., there is a group of ~40 with the same params etc, another group with ~20)
> and then use an if/else for the individual distinct functions?
Efficiency requirements are design constraints; efficiency per se is not a design goal. The idea would be to get to a design that is simple, maintainable and flexible within the constraints imposed by efficiency needs.
So, I'd suggest: go ahead with that for the individual distinct functions. Perhaps with a switch/case on the function id instead of a sequence of if/ else ifs. Profile the code, measure its performance, and leave it at that if the performance is acceptable.
Templating allows me to fill that vector with anything, not just classes derived from Node, which could screw things up. As such, this seems like a sloppy and potentially error-prone workaround.
Use SFINAE to restrict the types to just Node or derived classes of Node.
Also, in the example, AddValues() returns an int, whereas AddBetterValues() returns a double. My Node's Print() function is virtual, as that makes sense, but there will be cases that require me to define new functions for classes derived from the Node class which have no relationship to the existing ones: If I add a vector of values to the BetterNode class for example.
My main aim was just to reduce the amount of code I have to duplicate, by putting things common to all nodes in the base Node class, and likewise for the Base class.
For AddValues() to be polymorphic, the function must have the same name (but different implementations) in different classes. To make it (compile-time) polymorphic on the result type (int in one case and double in the other), have the node and its derived classes announce the type of the result.
An elided example (using boost::enable_if and boost::type_traits):
#include <boost/utility.hpp>
#include <boost/type_traits.hpp>
#include <iostream>
using boost::is_base_of ;
using boost::enable_if ;
struct node
{
typedef int value_type ;
explicit node( int i ) : v(i) {}
value_type value() const { return v ; }
int v ;
} ;
// generalization of base<T>; declared, not defined
template< typename T, …
> For a novice like me, do you think a long if/else would be more easily implemented?
More easily implemented right now, yes. But 200 if/else if statements would not be pretty to maintain, and code size would be larger than that for a look up table.
> Isn't there a lot of overhead in this?
> I have ~200 external DLL functions, so I'd need to write a wrapper for each one of them.
In terms of performance overhead, 100 string comparisons are not great for performance; you could give each function a unique integral id and use much faster integer comparisons instead.
In terms of programmer overhead:
You would not need to write a wrapper for each of them; if these 200 functions fall into, say, 5 different types of function parameters, you would need just five forwarding wrappers.
An alternative approach would be to have five different look up tables, one for each function type.
As a simplified example, let's say you have just two different types of functions in all:
typedef int function_type_foo( const char* cstr ) ;
typedef int function_type_bar( int, double ) ;
With many functions of the same type:
int foo_one( const char* arg )
{ return printf( "foo_one( '%s' )\n", arg ) ; }
int foo_two( const char* arg )
{ return printf( "foo_two( '%s' )\n", arg ) ; }
// ...
int bar_one( int arg1, double arg2 )
{ return printf( …
> The problem lies in the declaration of the lookup table.
> All the functions are already defined in an external DLL, and I can't touch them.
So write wrappers of your own that call the functions in the DLL.
> The problem now is that the "WriteMemory" commands take different arguments from the "ReadMemory" commands.
> Also there are many more variations of functions to follow. So issues arise with the declaration of the Lookup Table
Have wrapper variadic functions functions which unpack the arguments using <stdarg.h> then forward the call to the external function. And be extremely careful in doing this - make sure that you have no type errors.
#include <stdio.h>
#include <assert.h>
#include <stdarg.h>
int foo( const char* arg ) // external dll function
{ return printf( "foo( '%s' )\n", arg ) ; }
int bar( int arg1, double arg2 ) // external dll function
{ return printf( "bar( %d, %f )\n", arg1, arg2 ) ; }
typedef enum function_id_ { FOO = 1, BAR = 2 } function_id ;
int foo_wrapper( function_id id, ... )
{
typedef const char* arg_type ;
arg_type a ;
assert( id == FOO ) ;
va_list arg_list ;
va_start( arg_list, id ) ;
a = va_arg( arg_list, arg_type ) ;
va_end( arg_list ) ;
return foo(a) ;
}
int bar_wrapper( function_id id, ... )
{
typedef int arg1_type ;
typedef double arg2_type ;
arg1_type a ;
arg2_type b ;
assert( id == BAR ) …
> I want default value to be NULL so that whenever I encounter NULL
> I know that there is no implementation for this function.
> I wonder If NULL will be suitable for function that returns some type of value
There are two ways that you can simulate this behaviour.
1. Have the function return a discriminated union which could be null;
for example boost::any http://www.boost.org/doc/libs/1_42_0/doc/html/any.html
And have the default implementation return null.
2. The default implementation of the function does not return; it throws.
#include <iostream>
#include <boost/any.hpp>
#include <stdexcept>
struct not_implemented_error : std::runtime_error
{
explicit not_implemented_error()
: std::runtime_error( "function not implemented." ) {}
};
struct base
{
virtual boost::any foo() { return boost::any() ; }
virtual int bar() const
{
throw not_implemented_error() ;
return 0 ; // for compilers which may complain otherwise
}
protected : virtual ~base() = 0 ;
};
base::~base() {}
struct one : base // does not implement bar
{
virtual boost::any foo() { return 100 ; }
} ;
struct two : base // does not implement foo
{
virtual int bar() const { return 200 ; }
} ;
void test_it( base* object )
{
boost::any result = object->foo() ;
if( result.empty() )
std::cerr << "object->foo(): function not implemented\n" ;
else
std::cout << "object->foo() returns " << boost::any_cast<int>(result) << '\n' ;
try
{
std::cout << "object->bar() returns " << object->bar() << '\n' ;
}
catch( const std::exception& error )
{
std::cerr …
> I don't want the user to be able to do "cout << someClass << endl;" But I do want to be able to do "someStringStream << someClass;"
Is that a very good idea? Consider not overloading the stream insertion operator at all, and instead just providing a member function to_string() which can be used to stringify the object.
> However when I overload the << operator in my class, it wouldn't compile.
Modify the (original) overloaded operator to:
std::stringstream& operator<<( std::stringstream& stream, const A& someobject)
{
static_cast<std::ostream&>(stream) << someobject.num;
return stream;
}
Why would this compile, while the earlier form (without the cast) wouldn't?
See http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19
Also modify the code in main from
A a1(7);
std::stringstream stream1;
stream1 << "Hello world! " << a1;
To
A a1(7);
std::stringstream stream1;
stream1 << "Hello world! " ;
stream1 << a1;
Why is this change required? See my earlier post.
> now that I've opened my eyes, the crash happens when I try to handle the objects contained in the vector.
If you open your eyes a wee bit more, you would also notice that after delete temp ;
the vector contains (a copy of) a pointer which points to an object that does not exist any more - the object has been deleted.
Change std::stringstream& to std::ostream& in the overloaded operator and you would be ok.
class A
{
public:
int num;
A(int x) : num(x) {};
friend std::ostream& operator<<( std::ostream& stream, const A& someobject );
};
std::ostream& operator<<( std::ostream& stream, const A& someobject )
{
stream << someobject.num;
return stream;
};
Why is this so? Because in:
std::stringstream stream1;
stream1 << "Hello world! " << a1;
stream1 << "Hello world! "
returns a std::ostream&
For C++, you could base the course on Stroustrup's 'Software: Principles and Practice Using C++'. This is a book that is based on a course he designed for engineering freshmen at Texas A&M U. The support site for the book http://www.stroustrup.com/Programming/ also has some content for teachers - Instructor's Guide, Lecture slides etc. You should be able to get more help if needed in the google group for teachers using this book: http://groups.google.com/group/ppp-public/about
Another widely used source is the University of Groningen's C++ Annotations http://www.icce.rug.nl/documents/cplusplus/
IIRC, the a subsequent chapter of the book deals with completing this program. You would learn there about most of these issues (input and output, modulus operations, recovering from errors and so on), and be asked to refine the first draft of the program. So, perhaps the intent is to let you write some code right now, which may not be the final form of the program that you would write.
So, if the following does not make too much sense, don't bother too much right now. One thing that you might want to start do immediately is: consider giving somewhat more intuitive names for your varables. eg.
int set_sz = 0;
int subset_sz = 0;
char command = ' ';
int result = 0;
> I don't know how to put all the error exceptions into the same class.
Each exception indicates a different kind of error, and errors are discriminated based on the type of the exception. Putting everything into the same class may not be what you want to do. However, you could have a common base class from which all your exception types are derived. eg.
class program_error : public exception // base class for exceptions.
{
virtual const char* what() const throw()
{
return "A program specific error.\n" ;
}
} ;
class subsetset_size_too_large_error : public program_error
{
virtual const char* what() const throw()
{
return "The set size must be greater than the subset size.\n" ;
}
} ;
class …
If you are just starting out on C++, these two would be high on the list of books:
Stroustrup's 'Programming: Principles and Practice using C++'
http://www.stroustrup.com/Programming/
Koenig and Moo's 'Accelerated C++: Practical Programming by Example'
http://www.acceleratedcpp.com/
> That is the whole problem - I am not allowed to #include <vector> in any header file
You don't have to #include <vector> in any header file, you just have to declare std::vector<> in the header.
1. Declare std::vector<> in Myclass.h
2. #include <vector> (define std::vector<>) in MyClass.cc and MyDerivedClass.cc
3. provide a protected accessor to the vector for the benefit of derived class authors.
///////// MyClass.h ////////////
namespace std
{
template < typename T > struct allocator ;
template < typename T, typename A > class vector ;
}
class MyClass
{
// ...
private:
struct impl ;
impl* pimpl ; //consider using a std::tr1::unique_ptr instead of a raw pointer
protected:
std::vector< double, std::allocator<double> >& vector() ;
};
///////// MyDerivedClass.h ////////////
#include "MyClass.h"
class MyDerivedClass : MyClass
{
public:
void DoSomething();
};
///////// MyClass.cc ////////////
#include "MyClass.h"
#include <vector>
struct MyClass::impl
{
std::vector<double> v ;
// ...
// ...
};
// ...
// ...
std::vector< double, std::allocator<double> >& MyClass::vector()
{ return pimpl->v ; }
///////// MyDerivedClass.cc ////////////
#include "MyDerivedClass.h"
#include <vector>
void MyDerivedClass::DoSomething()
{
vector().push_back(1.3);
}
class Cat : public Animal{
double weight;
public:
Cat(string name, double weight)
: Animal(name), weight(weight) {this-> weight = weight;}
void print() const {
Animal::print() ; // *** added ***
cout << "Weight = " << weight << endl;
}
In this simple case, const doesn't have an effect on the program in terms of the code generated. The compiler can easily figure out that the variables are not changed.
However, it is still a good idea to always use 'const' where ever appropriate; it is just programming hygiene, and it's worth making it a habit.
> The math problem is ((20+x) & 1234)=1000 as an example.
The equality may have no solution. For (A+x) & B == C, if any bit in B is 0 while the same bit in C is 1, there is no solution.
((20+x) & 1234)==1000 does not have a solution.
> needs to get both the highest possible value of x and the lowest possible value of x
For (A+x) & B == C, if there is a solution, the highest possible value for (A+x) is ~( B ^ C )
And the smallest possible value for (A+x) is C.
#include <iostream>
#include <limits>
#include <bitset>
#include <string>
int main()
{
const unsigned long A = 20UL, B = 11247UL, C = 1000UL ;
// find min and max values for x when ( (A+x) & B ) == C
enum { NBITS = std::numeric_limits<unsigned long>::digits } ;
std::bitset<NBITS> b(B), c(C) ;
// if any bit in B is 0 when the corrosponding bit in C is 1,
// there is no solution
for( std::size_t i = 0 ; i < NBITS ; ++i )
if( c[i] && !b[i] )
{
std::cerr << "( (" << A << "+x) & " << B << ") = " << C
<< " has no solution.\n" ;
return 1 ;
}
// if there is a solution, highest possible value of (A+x) is ~( B ^ C )
std::bitset<NBITS> max_A_plus_x = ~( b ^ c ) …
> you have to make sure is the the second thread is not just constantly checking the state
The efficient (and elegant) way to do this is to use a condition_variable.
http://www.boost.org/doc/libs/1_42_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref
> My first question is why is static used?
> My understanding is that static objects are instantiated once and persist untill the end of the program
In this particular case specifying a static storage duration does not make any perceptible difference.
int main()
{
int a[] = { 7, 8, 9 } ; // automatic storage duration; a exists till main returns
// static storage duration; b exists till end of program - ie. till main returns
static int b[] = { 7, 8, 9 } ;
// because b is a POD type placed in the SDA, and initialized with compile-time
// constants, it does not require dynamic initialization. a does.
}
In C++0x, we could just use its uniform initialization syntax via std::initializer_list<>.
With C++98, using Boost::Assign is equally nifty. http://www.boost.org/doc/libs/1_43_0/libs/assign/doc/index.html
#include <map>
#include <string>
#if __cplusplus > 199711L // C++0x
#include <initializer_list>
#else // C++98
#include <boost/assign/list_of.hpp>
#endif // C++0x
int main()
{
#if __cplusplus > 199711L // C++0x
std::map< int, std::string > map =
{ {9,"sheep"},{2,"cow"},{3,"horse"},{0,"chicken"},{5,"dog"} } ;
#else // C++98
std::map< int, std::string > map = boost::assign::map_list_of
(9,"sheep")(2,"cow")(3,"horse")(0,"chicken")(5,"dog") ;
#endif // C++0x
}
#include <iostream>
template < int N > struct S : S<N-1>
{
S() { if( std::cout << N << ". Hello World\n" ) {} }
};
template <> struct S<0> {} ;
int main()
{
S< sizeof("twenty Hello Worlds") >() ;
}
> Try this one on for size...
That's trivial too; reduces to computing Euler's totient function.
http://en.wikipedia.org/wiki/Euler's_totient_function
int eulers_totient_function( int number )
{
if( number < 1 ) return 1 ;
int totient = 1 ;
for( int factor = 2; number != 1; ++factor )
{
int power = 1 ;
while( number%factor == 0 )
{
number /= factor;
power *= factor ;
}
totient *= ( power - (power/factor) ) ;
}
return totient ;
}
//set<*Node> neighbours;
set<Node*> neighbours;
> As far as I understand, each node in a list contains an element as well as pointers to both the following and preceding elements.
> Both an integer and a pointer to an integer are 4 bytes, so one would think that a node would use up 12 bytes,
> and therefore a list with 5M elements should use 60MB, not 118MB.
That is rather too simplistic a view.
When you allocate memory using a new, C++ guarantees that the memory pointed to will be correctly aligned for *any* complete object type whose size is no greater than the requested size.
The allocation function attempts to allocate the requested amount of storage. If it is successful, it shall return the address of the start of a block of storage whose length in bytes shall be at least as large as the requested size.
...[elided]...
The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type and then used to access the object or array in the storage allocated
...[elided]... - IS
For example, if the alignment requirement for an 8-byte double is 8 bytes, a 12-byte block would be aligned on an 8-byte boundary.
For performance reasons, every allocator maintains available chunks in bins, grouped by size. Because of alignment requirements, these chunk sizes are a multiple of 8 on 32-bit platforms. So a request for 12 bytes will consume …
> Out of curiosity, is this even possible?
Something like this would be possible in C++0x (after a constructor that takes a std::initializer_list<>
is added to the ublas matrix). boost::numeric::ublas::matrix mtx { {1,1,1}, {2,2,2}, {3,3,3} } ;
Right now, one work around would be to put the initializers for the matrix in a text file and write a function void load_from_stream( boost::numeric::ublas::matrix& mtx, std::istream& stm ) ;
This is a very flexible approach; you can run your program on many different data sets by specifying different input files, without having to modify and recompile the code each time.
To enable initialization akin to that for C-style arrays, you have to customize the storage for the matrix. For example,
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/exception.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <iterator>
using boost::numeric::ublas::matrix ;
// custom ublas storage_array (immutable);
// implemented using a user-supplied c-style 2d array for storage
template< typename T, std::size_t M, std::size_t N >
struct c_array_2d : boost::numeric::ublas::storage_array< c_array_2d<T,M,N> >
{
typedef std::size_t size_type ;
typedef std::ptrdiff_t difference_type ;
typedef const T value_type ;
typedef const T& reference ;
typedef const T* pointer ;
typedef const T& const_reference ;
typedef const T* const_pointer ;
typedef const_pointer iterator ;
typedef const_pointer const_iterator ;
typedef std::reverse_iterator<iterator> reverse_iterator ;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator ;
explicit inline c_array_2d( T(&a)[M][N] ) : array(a) {}
inline size_type max_size () const { return size() ; }
inline bool empty() const { return false ; }
inline size_type size() const { return M*N ; }
inline const_reference operator …
> Is that a good idea?
Yes, if the situation is as the OP posted:
>> There is a bug in my program and I'm trying to check what is wrong.
>> I don't want to remove elements. just want to check the content of the queue.
That is, what is really needed by the design is a queue, but for debugging purposes we need to spy into it's contents. Either when it is convenient for the debugging scaffold to use standard algorithms like std::find_if and getting iterators would be handy. Or the error occurs only when the queue is very big, and using a secondary queue every time we want to examine it is somewhat impractical on the very big queue.
It would be wrong if the const was missing in template< typename T > void foobar( const std::queue<T>& queue ) ;
. It would also be wrong if the design called for a queue, and we use a list instead just because we want to debug our code.
> man setsockopt
Or if you are not on Unix, see: http://www.freebsd.org/cgi/man.cgi?query=setsockopt&apropos=0&sektion=0&manpath=FreeBSD+8.1-RELEASE&format=html
And then look for the option SO_RCVTIMEO
> Is there any way of checking all elements in a queue without calling pop().
Yes, if you have used a std::queue<T>
with the default std::deque<>
for the second template parameter.
template< typename T > void foobar( const std::queue<T>& queue )
{
typename std::deque<T>::const_pointer begin = &queue.front() ;
typename std::deque<T>::const_pointer end = begin + queue.size() ;
// [begin,end) iterates over elements of the queue. for example,
std::copy( begin, end, std::ostream_iterator<T>( std::cout, "\n" ) ) ;
}
else
{
if(j >= i) //this small section makes sure that 'i' cant breed with itself and the selection is corrected for array re-arrangement
// Don't we need to recalibrate the roulette wheel here?
iPopulation[iPopDensity - 1][iChromeLength + 2] = j + 1;
else
// ...
}
> can we pass arrays to functions
You couldn't pass arrays to functions in C, and couldn't pass them in C++98 either.
And you won't be able to do that in C++0x too. However, in C++0x you could pass a std::initializer_list<>
to a function;
that is what someFunction({{1,2},{3,4},{5,6}});
attempts to do.
#include <iostream>
#include <vector>
template< typename SEQ > void foobar( const SEQ& s )
{
for( auto iter = s.begin() ; iter != s.end() ; ++iter )
std::cout << *iter << ' ' ;
std::cout << '\n' ;
}
template< typename T > void foobar( const std::initializer_list<T>& a )
{
for( auto iter = a.begin() ; iter != a.end() ; ++iter )
std::cout << *iter + 10 << ' ' ;
std::cout << '\n' ;
}
struct A { int a ; int b ; } ;
struct B { B( int x ) : b(x) {} private: int b ; } ;
struct C
{
A aa[2] ;
B bbb[3] ;
operator int() const { return aa[0].a ; }
} ;
int main()
{
foobar( { 0, 1, 2, 3, 4, 5 } ) ;
std::vector<int> seq{ 0, 1, 2, 3, 4, 5 } ;
foobar( seq ) ;
foobar( { C{ { {1,2}, {3,4} }, {5,6,7} },
C{ { {7,8}, {9,0} }, {1,2,3} },
C{ { {4,5}, {6,7} }, {8,9,0} } } ) ;
}
> i am not understanding about ,Preprocessor,Compiler ,linker , Loader ,CPU
If you are just starting out, don't bother all that much about the gory details of what these different entities are right now. Just get a rough idea of what #include means, write the first hello world program, compile it and get it running, write a few more simple programs and so on. In due course of time, as you program, you would get to understand each of these.
Here is a simple tutorial: (simple, but just use it to get a rough idea; don't even try to digest all of it before you have written a few programs)
http://www.redantigua.com/c-compiler-behind-the-scenes-index.html
Something you could look at after a while: http://www.tenouk.com/ModuleW.html
AFAIK, the main advantage of nested functions in languages that have them is to provide support for closures. http://en.wikipedia.org/wiki/Closure_%28computer_science%29
Closures typically appear in languages that allow functions to be first-class values, in other words, such languages allow functions to be passed as arguments, returned from function calls, bound to variable names, etc., just like simpler types such as strings and integers. - Wiki
C++ already had function objects, which look like functions but are really first class values, they can be stored, mutated, passed as arguments and returned and bound to variable names. And therefore C++ already had a mechanism for supporting closures - several libraries eg. Boost::bind, Boost::spirit, Boost::phoenix do exploit closures extensively.
To define a function object, the programmer has to go outside the current scope, and these names cannot be declared close to their first (and often only) use. Lambda functions have been added in C++0x to increase the expressive power and ease of use of the language - anything that could be done using lambda functions could also be done using function objects, albeit in a more verbose manner.
In C, gcc has had an extension which provides limited support for nested functions and closures for quite some time now. http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html One can only call these functions (with closures) as long as the containing stack frame is alive:
If you try to call the nested function through its address after the containing function has exited, all hell will break …
> Thats exactly What I meant. put the declarations in the *.cpp file and it'll work.
For starters, that will be a gross violation of ODR. see: http://en.wikipedia.org/wiki/One_Definition_Rule
You could of course write your own string class, and use it in any way that you please, as long as you don't put it into the namespace std. (Or if you do not use anything from the namespace std anywhere in your entire program; very difficult indeed - how do you get rid of std::bad_alloc?)
Don't really know what you are up to, but are you looking for something like this?
#include <iostream>
#include <string>
#include <cassert>
#include <stdint.h> // C99, <cstdint> in C++0x
uint64_t as_number( const std::string str )
{
const unsigned int MAX_BYTES = sizeof(uint64_t) ;
assert( str.size() <= MAX_BYTES ) ;
union
{
char cstr[ MAX_BYTES ] ;
uint64_t number ;
};
std::fill_n( cstr, MAX_BYTES, 0 ) ;
//copying in reverse is slightly saner for little-endian architectures
std::copy( str.rbegin(), str.rend(), cstr ) ;
return number ;
}
int main()
{
std::cout << as_number("hello2") << '\n' ;
}
Typically it doesn't, unless you force it to. For example:
> g++44 -Wall -std=c++98 -pedantic -Werror -fomit-frame-pointer -fstrict-aliasing -fconserve-stack -fno-defer-pop
The frame of a function is transient, and the memory is reclaimed as soon as the function returns. It could also cause most debuggers to stumble.
> which kinds of constructors can be applied during compile time ?
None in C++98; though constructors can be elided as in the case of RV optimization.
Objects constructed via the the constexpr mechanism in C++0x.
http://www2.research.att.com/~bs/C++0xFAQ.html#constexpr
class Test{
public:
Test()=default;
Test(char in1,char in2):char1(in1),char2(in2){}
char char1;
private:
char char2;
};
Test obj={'a','b'};//invalid in c++0x
It is valid in C++0x.
The final proposal is here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2640.pdf