vijayan121 1,152 Posting Virtuoso

>> here is the only line where i allocate space in the program q.push(new LeftistHeap(vec[i]) ); the leak is because of that line; sizeof(LeftistHeap) == sizeof(pointer) + sizeof(int), adds up to 8 bytes on i386. the leak reported by valgrind is

80 bytes in 10 blocks are definitely lost in loss record 1 of 2
==1599== at 0x3C03D2F3: operator new(unsigned) (in /usr/local/lib/valgrind/vgpreload_memcheck.so)
==1599== by 0x804936E: LeftistHeap::initializeHeap(std::vector<int, std::allocator<int> >&) (LeftistHeap.cpp:206)

and in main.cpp we have enum { HOW_MANY_ELEMENTS = 10, TEST_ITERATIONS = 1, DISTRIBUITION_AREA=1024*1024 }; the blocks lost are the 10 LeftistHeap objects that you allocate using new and never delete.

change HOW_MANY_ELEMENTS to 1000 and valgrind will report 8000 bytes in 1000 blocks as definitely lost.
the dynamically allocated LeftistHeap objects are leaking; not the nodes

>> if i test this programm with valgrind, i don't get any errors.... which is weird...

valgrind automagically knows about memory that is still reachable. node_pool (has a static storage duration; still not destroyed at the point main returns) has references the the blocks it has allocated; so the memory is not *definitely* lost. in fact, the destructor of node_pool will free this memory.
you could verify this by using the valgrind switch --show-below-main=yes (continue stack traces below main)

vijayan121 1,152 Posting Virtuoso

check the function LeftistHeap::initializeHeap . valgrind is reporting 80 bytes in 10 unreachable blocks of memory allocated in this function. this is a leak.
the 2 reachable blocks are not memory allocated from your code (they are allocations by libc.so and will be released on program exit) and do not constitute a leak.

vijayan121 1,152 Posting Virtuoso

for merely notifying another process that some event has occurred, you could use an event object.
http://msdn2.microsoft.com/en-us/library/ms682655.aspx
http://www.codeproject.com/csharp/interopevents.asp

to also pass additional information, you would need to use an ipc mechanism.
http://msdn2.microsoft.com/en-us/library/aa365574.aspx

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

create an Xcode C++ tool project. http://www.meandmark.com/xcodeintro.pdf

vijayan121 1,152 Posting Virtuoso

>> .. really mad. It,s not displays as a binary code, I mean bunch of zeros and ones.

if all you want to do is display the contents of a file as a sequence of bits (i presume that is what you mean by bunch of zeros and ones),

#include <fstream>
#include <limits>
#include <bitset>
#include <iostream>
using namespace std;

int main()
{
  ifstream file( __FILE__ ) ; file >> noskipws ;
  typedef bitset< numeric_limits<unsigned char>::digits > bitset ;
  unsigned char byte ;
  while( file >> byte ) cout << bitset(byte) ;
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

>> what is the corresponding standard lib function of Win32's WideCharToMultiByte()?
there are two options available; use the ctype<> facet or the codecvt<> facet. the following example uses ctype<> for conversion.

#include <locale>
#include <iostream>
#include <string>
#include <sstream>
using namespace std ;

wstring widen( const string& str, const locale& loc = locale::classic() )
{
    wostringstream wstm ;
    wstm.imbue(loc) ;
    const ctype<wchar_t>& ctfacet = 
                        use_facet< ctype<wchar_t> >( wstm.getloc() ) ;
    for( size_t i=0 ; i<str.size() ; ++i ) 
              wstm << ctfacet.widen( str[i] ) ;
    return wstm.str() ;
}

string narrow( const wstring& str, const locale& loc = locale::classic() )
{
    ostringstream stm ;
    stm.imbue(loc) ;
    const ctype<char>& ctfacet = 
                         use_facet< ctype<char> >( stm.getloc() ) ;
    for( size_t i=0 ; i<str.size() ; ++i ) 
                  stm << ctfacet.narrow( str[i], 0 ) ;
    return stm.str() ;
}

int main()
{
  {
    const string str = "abcdefghijkl" ;
    const wstring wstr = widen(str) ; // use clasic C locale
    wcout << wstr << L'\n' ;
  }
  {  
    const wstring wstr = L"mnopqrstuvwx" ;
    const string cstr = narrow( wstr, locale("POSIX") ) ;
    cout << cstr << '\n' ;
  } 
}

>> In addition the CreateEvent() function.
there is no threading support in c++98. a proposal for a thread library (based on boost.thread) is part of TR2, yet to be accepted into c++0x. for a portable solution, you could use boost.thread. but the equivalent of win32 Event mechanism is not provided by the library; instead java style condition variables are available. this …

vijayan121 1,152 Posting Virtuoso

>> ...I don't think I'm smart enough to understand template metaprogramming....

it is not as difficult as you make it out to be. strange? yes, initially. hard to understand? not really. a lisper would feel quite at home with this kind of programming. and it would look somewhat eerie to someone with only a c (read classical c++, C#, java) background

>> ...made me wonder if it was practical. All of the examples that look useful to me are too complicated to understand. All of the examples I can grok are kind of pointless

ok, let us try again. here is a useful example. we want to write a (generic, meta) function which copies one sequence to another like std::copy. however, if the source and destination sequences are c-style arrays which can be correctly copied using a memcpy, we want to call memcpy. otherwise, we would iterate and copy element by element. compilers (icc, vc++ 7 or later, gcc 4.1 or later) recognize a call to memcpy and can generate mmx/sse instructions for a fast block copy; we do not want to lose this advantage. but we do not want to break our code if the implementation of the sequence we are copying is modified at some time in the future. we just recompile, safe in the knowledge that our metaprogram will generate either a call to memcpy or do an element by element copy depending on what we are copying.
the code is fairly elaborately …

vijayan121 1,152 Posting Virtuoso

for simple round-robin scheduling, add the jobs to the back of a simple queue (use a std::queue for this). to schedule a job, pick the one at the front of the queue. if a job blocks (goes into a wait state) or its time-slice is over, put it back (at the back) of the queue.
for short job first cpu scheduling, use a std::priority_queue instead. with the shorter the (estimated) time to finish, the higher the priority.

vijayan121 1,152 Posting Virtuoso

>> looks cool, but is it really practical?

you have already seen one practical use for it; perhaps you have forgotten about it. see thread http://www.daniweb.com/forums/thread82213.html posts #7 and #10 where a trivial metafunction (rebind) was used to solve a genuine programming problem.

though the idea of using c++ as a metalanguage is faily old (see http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html - originally published in1994) and there has been high excitement among C++ experts about these capabilities of the language, it is true enough that it has not reached the c++ community at large.

here are some references to help you get started
http://safari.oreilly.com/0201704315
http://safari.oreilly.com/0321227255
http://en.wikipedia.org/wiki/Loki_(C++)
http://en.wikipedia.org/wiki/Boost_C++_Libraries
http://www.oonumerics.org/blitz/whatis.html
and something that (astonishingly; this certainly is not comp.lang.c++.moderated) turned up in daniweb yesterday): http://www.daniweb.com/forums/thread88328.html

vijayan121 1,152 Posting Virtuoso

>> I took a course in JAVA and learned about exceptions...I'm not sure how to throw and catch in C++.

the fundamental difference is the use of the 'resource acquisition is initialization' technique in resource management. the c++ philosophy is
a. error handling code must be clearly seperate from normal code
b. you should not have to write error handling code (read no finally scattered all around the place to clean up when exceptions are thrown) except at the place where you attempt to handle the error.
c. the possibility of an error is not deemed to be an error. (exceptions are not checked at compile-time; if exception specifications are not violated at runtime there is no error).
d. the exception mechanism (as the name suggests) is designed to handle exceptional situations; (for example, when you iterate over a sequence, there is nothing exceptional about reaching its end (i would say that never being able to reach the end would be exceptional).
e. exceptions are expensive at runtime (stack unwind is required), but should cause minimum overhead if no exceptional situation occurs. exceptions are the exception rather than the rule.

so your java experience might in some ways be a disadvantage; you should be willing to unlearn a few things.

here are a few links which deal with the conceptual (rather than syntactic) differences between java and c++ exceptions.
http://www.hackcraft.net/raii/
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
http://www.informit.com/articles/article.aspx?p=30642&seqNum=8&rl=1
http://www.artima.com/intv/modern3.html

vijayan121 1,152 Posting Virtuoso

there seems to be nothing much happening in the c++ forum today. so here is something to chew on for programmers who are relatively new to templates: c++ can also be used as a metalanguage.

#include <iostream>
using namespace std ;

// compile-time computation of fibonacci numbers
template < int N > struct fibonacci
{
   char error_negetive_N[ N + 1 ] ; // c++0x => use static_assert
   enum { value = fibonacci<N-1>::value + fibonacci<N-2>::value } ;
   char error_integer_overflow[ value ] ; // c++0x => use static_assert
};
template<> struct fibonacci<0> { enum { value = 0 } ; } ;
template<> struct fibonacci<1> { enum { value = 1 } ; } ;

// compile-time if statement
template<bool> struct _if { static inline void new_line() {} };
template<> struct _if<true> 
{ static inline void new_line() { cout << '\n' ; } };

// compile-time for loop
template< int N, int MAX, size_t N_PER_LINE > struct _for
{
  static inline void print_fibonacci_number()
  {
      cout << fibonacci<N>::value << '\t' ;
      _if< N%N_PER_LINE == (N_PER_LINE-1) >::new_line() ;
      _for< N+1, MAX, N_PER_LINE >::print_fibonacci_number() ;
  }
};
template< int MAX, size_t N_PER_LINE > struct _for<MAX,MAX,N_PER_LINE>
{
   static inline void print_fibonacci_number()
   { _if< MAX%N_PER_LINE >::new_line() ; }
} ;

int main()
{
   enum { FROM = 0, TILL = 32, LINE_SZ = 8 } ;
   _for< FROM, TILL, LINE_SZ >::print_fibonacci_number() ;
}
// to see generated assembly along with c++ source code (gcc):
// c++ -c -g -Wa,-a,-ad -Wall -std=c++98 -O3 fib.cpp > fib.asm
/** …
josolanes commented: great thread idea...working through it now to get a better understanding of TMP now +1
vijayan121 1,152 Posting Virtuoso

and here are some books.
1. Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (Addison-Wesley Professional)
2. Design Patterns Explained: A New Perspective on Object-Oriented Design (2nd Edition) by Alan Shalloway, James Trott (Addison-Wesley Professional)
3. Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts (Addison-Wesley Professional )
4. Head First Design Patterns by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra (O'Reilly Media)
5. Refactoring to Patterns by Joshua Kerievsky (Addison-Wesley Professional )
6. Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu (Addison-Wesley Professional )
7. Pattern-Oriented Software Architecture, Volume 1: A System of Patterns by Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, Michael Stal (John Wiley & Sons)
8. Pattern-Oriented Software Architecture, Volume 2, Patterns for Concurrent and Networked Objects by Douglas Schmidt, Michael Stal, Hans Rohnert, Frank Buschmann (John Wiley & Sons)
9. Pattern-Oriented Software Architecture, Volume 3, Patterns for Resource Management by Michael Kircher, Prashant Jain (John Wiley & Sons)
10. Pattern-Oriented Analysis and Design: Composing Patterns to Design Software Systems by Sherif M. Yacoub, Hany H. Ammar (Addison-Wesley Professional)

Dave Sinkula commented: Nice list. +11
vijayan121 1,152 Posting Virtuoso

you would be better off using icc for processor-specific optimizations. even without processor-specific optimizations, icc generates better optimized code than vc++ 8; and it blows gcc away. http://www.intel.com/cd/software/products/asmo-na/eng/276615.htm

SpS commented: Right suggestion +4
vijayan121 1,152 Posting Virtuoso

using boost.spirit may be much easier: http://www.boost.org/libs/spirit/doc/quick_start.html

#include <boost/spirit/core.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <boost/assign.hpp>
using namespace std ;
using namespace boost ;
using namespace boost::spirit ;
using namespace boost::assign ;

struct parse_it
{ 
  void operator() ( const string& str ) const
  {
    vector<string> tokens ;
    const char* cstr = str.c_str() ;
    size_t n = 0 ;
    while( n < str.size() )
      n += parse( cstr + n,
                  (+space_p) [  push_back_a( tokens, "SPACE" ) ] |
                  str_p("daniweb") [ push_back_a( tokens, "WEB" ) ] |
                  str_p("lexer") [ push_back_a( tokens, "LEX" ) ] |
                  str_p("tokenizer") [ push_back_a( tokens, "TOK" ) ] |
                  (+~space_p) [ push_back_a( tokens, "STRING" ) ]
                ).length ;
    cout << '\n' << "parsed: " << str << "\ntokens: " ;      
    copy( tokens.begin(), tokens.end(), 
               ostream_iterator<string>(cout," ") ) ;
    cout << '\n' ;      
  }
};
int main()
{
  vector<string> test_cases = list_of
                ( "test daniweb lexer xyz tokenizer lexer" )
                ( "daniweblexer tokenizerlexer abcd lexerlexer" )
                ( "daniwebtest lexerdaniweblexertest tokenizerxxx" ) ;
  for_each( test_cases.begin(), test_cases.end(), parse_it() ) ;
}
/**
>g++ -Wall -std=c++98 -I/usr/local/include keyword.cpp && ./a.out

parsed: test daniweb lexer xyz tokenizer lexer
tokens: STRING SPACE WEB SPACE LEX SPACE STRING SPACE TOK SPACE LEX

parsed: daniweblexer tokenizerlexer abcd lexerlexer
tokens: WEB LEX SPACE TOK LEX SPACE STRING SPACE LEX LEX

parsed: daniwebtest lexerdaniweblexertest tokenizerxxx
tokens: WEB STRING SPACE LEX WEB LEX STRING SPACE TOK STRING
*/
vijayan121 1,152 Posting Virtuoso

>> If i start with 1000 uniformly distributed random numbers and then convert them into Normally ditributed numbers, and have 38 such sets, there is no guarantee that the 1000 corresponding sets of 38 numbers shall be uniformly distributed. It does not matter what range they are within.

could this work? generate 38000 uniformly distributed random numbers. take the largest 1000 of these and convert them to normally ditributed numbers, repeat for the next largest 1000 and so on till you have 38 sets. don't know enough statistics to say for sure. but it does look intuitive.

vijayan121 1,152 Posting Virtuoso

You might as well change the name from join to join_unsigned_int while you're at it. ;)

not really, signed int types are ok if b is not negetive. join( -22, 789 ) gives -22789. however, join( 22, -789 ) would fail an assertion. perhaps, join_integral_types?

vijayan121 1,152 Posting Virtuoso

here is a safer version which performs sanity checks

#include <sstream>
#include <limits>
#include <cassert>

// returns 0 on overflow
template< typename T > inline T join( T a, T b )
{
  typedef std::numeric_limits<T> limits_type ;
  assert( limits_type::is_specialized && limits_type::is_integer ) ;
  assert( !limits_type::is_signed || ( b>=0 ) ) ;
  std::stringstream stm ;
  stm << a << b ;
  T ab = 0 ;
  stm >> ab ;
  return ab ;
}
vijayan121 1,152 Posting Virtuoso

main is a function written by the user, but it is special in several ways. as per ISO/IEC 14882(E):
3.6.1-1a program shall contain a global function called main, which is the designated start of the program. ...
3.6.1-2 an implementation shall not predefine the main function. this function shall not be overloaded. it shall have a return type of type int, but otherwise its type is implementation-defined. all implementations shall allow both of the following definitions of main: int main() { /* ... */ } and int main(int argc, char* argv[]) { /* ... */ }
3.6.1-3 the function main shall not be used (called) within a program. The linkage of main is implementation-defined

so it is a function defined by the user; but unlike other user defined functions, it must be in the global namespace, it can not return anything other than an int, it cannot be overloaded, it cannot be called (implementation defined linkage, usually different from the linkage for other functions) and it need not contain a return statement (assumed return 0).

vijayan121 1,152 Posting Virtuoso

>> I thought maybe it will help if I quote the entire error message:
>> LINK : error : Internal error during ReadSymbolTable
yes, it does help. the access violation is not when your code is running, but caused by link.exe which ships with vc++ 6.0.
you may be able to fix this by turning of incremental linking in your project settings (change link.exe switch /INCREMENTAL:NO if you are using a make file). and clean the intermediate files before the build. (in particular, delete any file with a .ilk extension). you could also disable use of precompiled headers; is also known to cause problems in vc++ 6.0 sometimes.

vijayan121 1,152 Posting Virtuoso

can u expain what this code signifies
split( elements, line, is_any_of(", ") );

split() is used to split string line into parts separated by characters ',' or space. these parts are then put into the vector elements

assert( (i<N) && (vertices[i]==elements[0]) && (elements.size()==N+1) ) ;

verify that the input is sane

for( size_t j=0 ; j<N ; ++j )

graph[i][j] = elements[j+1] == "1" ;

if the element in the string part is "1", set the corrosponding element in the adjacency matrix to true.

Also your code given code gives following compilation errors

it does not for me; i'm using boost_1_34_1 (not boost_1_34_0), but i'm certain that boost_1_34_0 should be ok.

there were two errors in the earlier code; ++i (line 32) should me moved to the end of the while loop. also, getline( cin, line ) should be changed to getline( file, line ).
here is the modified code with a testcase and some diagnostic output.

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <cassert>
#include <algorithm>
#include <iterator>
using namespace std ;
using namespace boost ;

typedef vector< vector<bool> > adjacency_matrix ;

int main()
{
  vector<string> vertices ;
  ifstream file( "graph.txt" ) ;
  string line ;

  // read and parse the first line
  assert( getline( file, line ) ) ;
  split( vertices, line, is_any_of(", ") );

  const size_t N = vertices.size() ;
  adjacency_matrix graph( N, vector<bool>(N) ) ;

  // read and parse …
vijayan121 1,152 Posting Virtuoso

you can repesent a graph as an adjacency matrix. http://www.cs.usask.ca/resources/tutorials/csconcepts/1999_8/tutorial/beginner/matrices/matrix.html
using the specialization vector<bool> would take only one bit per matrix element, so large graphs can be accommodated. (not withstanding my efforts, the daniweb formatter refuses to believe that this sentence is not a url)

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <cassert>
using namespace std ;
using namespace boost ;

typedef vector< vector<bool> > adjacency_matrix ;

int main()
{
  vector<string> vertices ;
  ifstream file( "whatever.txt" ) ;
  string line ;
  
  // read and parse the first line
  assert( getline( cin, line ) ) ;
  split( vertices, line, is_any_of(", ") );

  const size_t N = vertices.size() ;
  adjacency_matrix graph( N, vector<bool>(N) ) ;

  // read and parse subsequent lines
  size_t i = 0 ;
  while( getline( cin, line ) )
  {
    vector<string> elements ;
    split( elements, line, is_any_of(", ") );
    assert( (i<N) && (vertices[i]==elements[0]) && (elements.size()==N+1) ) ;
    ++i ;
    for( size_t j=0 ; j<N ; ++j )
      graph[i][j] = elements[j+1] == "1" ;
  }
  assert( i == N ) ;
}
vijayan121 1,152 Posting Virtuoso

>> ...my mind still hasn't grasped how this number system works, is there some place I can read about it...
http://en.wikipedia.org/wiki/Signed_number_representations
http://en.wikipedia.org/wiki/Two%27s_complement

the c++ standard library header <limits> has a class template numeric_limits<> with specializations for each builtin numeric type. for integral types, the interesting members of std::numeric_limits<> are:

static const bool is_specialized; // will be true for integers
   static T min() throw(); // minimum value
   static T max() throw(); // maximum value
   static const int radix ; // the base of the representation; almost always 2
   static const int digits; // for integers, # value bits
   static const int digits10; // max number of decimal digits
   static const bool is_signed; //
   static const bool is_integer; // will be true for integers

for most uses, these are sufficient. here is an example of using numeric_limits<>.

#include <limits>
#include <iostream>
#include <bitset>
#include <cassert>
using namespace std ;

template< typename NUMERIC_TYPE > void show_info( NUMERIC_TYPE n )
{
   typedef numeric_limits<NUMERIC_TYPE> limits_type ;
   const int radix = limits_type::radix ;
   assert( radix == 2 ) ; // two's complement
   const int digits = limits_type::digits ;
   const int nbits = limits_type::is_signed ? digits+1 : digits ;
   cout << "radix: " << radix << "  digits: " << digits
        << "  nbits: " << nbits << '\n' ;
   NUMERIC_TYPE min_v = limits_type::min() ;
   NUMERIC_TYPE max_v = limits_type::max() ;
   cout << hex << showbase << "min value: " << min_v
        << "  max value: " << max_v << " …
SpS commented: Helpful +4
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

to put the machine into suspend/hibernate state, use SetSuspendState http://msdn2.microsoft.com/en-us/library/Aa373201.aspx
to wakeup from suspend/hibernate, use SetWaitableTimer http://msdn2.microsoft.com/en-us/library/ms686289.aspx with the last parameter (fResume) as TRUE and have a thread wait for the timer to be signalled or specify an APC to be called. note: to wake up from hibernate, hardware support for S4 power mode is required. this may not be available on all machines. check by calling GetLastError.

vijayan121 1,152 Posting Virtuoso

> where each column vector is normally distributed, between -1 and +1, and the row vectors are uniformly distributed between -1 and +1
this is mathematically impossible. if row vectors are uniformly distributed between -1 and +1, any element in any row (read any element in your 2d array) is equally likely to have any value in the range (-1,+1) and therefore the column vectors will also be uniformly distributed. standard normal distribution is the normal distribution with a mean of zero and a variance of one; about 99.7% of the sample points would lie in the range (-3,+3), only about 68% would lie in the range (-1,+1). the normal distribution is a *continuous* distribution, theoretically in the range(-infinity,+infinity).

vijayan121 1,152 Posting Virtuoso

> Or this to avoid break.
true, looks much neater
> You don't need the function pointer variable.
g++ (even very recent versions like 4.2) still does not have fully compliant "shadow headers" and can cause problems unless we tell the compiler explicitly that we intend using a pointer to a function. http://members.aon.at/hstraub/linux/newscache/porting-howto.html#sec-macros
this is a problem with the gnu libstdc++ . the code as dragon wrote (without the function pointer variable) works with most conforming implementations (microsoft, comeacu,icc).

vijayan121 1,152 Posting Virtuoso

dragon's algorithm does work. here is a version which a. uses isspace (handle all char sets) b. uses erase instead of extract substrings and concatenate (little more efficient). c. continues from the next char while repeatedly searching for whitespaces (again, little more efficient)

void remove_ws( vector<string>& vertex )
{
  int (*pfn_isspace)(int) = &isspace ;
  for( size_t i=0 ; i<vertex.size() ; ++i )
  {
      std::string& mystring = vertex[i] ;
      string::iterator where = mystring.begin() ;
      while(true)
      {
        where = find_if( where, mystring.end(), pfn_isspace ) ;
        if( where == mystring.end() ) break ;
        where = mystring.erase(where) ;
      }
  }
}
vijayan121 1,152 Posting Virtuoso

> if I want just to store a number of 200 characters there is no type for it ?????????
there is no *builtin* type for it. you can create a *userdefined* type which can be used like an int and has 200 decimal digits of precision.

vijayan121 1,152 Posting Virtuoso

here is a version without boost. note: the code is more brittle, eg. will break if the file format changes from what you have given to a simple csv.

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <sstream>
using namespace std;
using namespace boost;

bool init_map( const char* const file_name, map< string, size_t >& np_map )
{
  ifstream file( file_name ) ;
  if( !file ) return false ;
  string line ;
  while( getline( file, line ) )
  {
     istringstream stm(line) ;
     string fn ; string x ; size_t pos ;
     if( stm >> fn >> x >> pos ) np_map[fn] = pos ; 
  }
    return !np_map.empty() ;
}

int main()
{
  const char* const file_name = "whatever.txt" ;
  map< string, size_t > name_pos_map ;
  init_map( file_name, name_pos_map ) ;

  // look up
  string fn("0002.ogg") ;
  if( name_pos_map.find(fn) != name_pos_map.end() )
    cout << "found " << fn << " pos: " << name_pos_map[fn] << '\n' ;
  else
    cout << "did not find " << fn << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

> search the string (file name ) and read its data (file position) with a good speed. The requirement is that I have to search for 869 files.
the number of files are quite small; if you have to do this search more than once, it would be faster to read the file once and store the data in a lookup table in memory. the following example uses boost.tokenizer ( http://www.boost.org/ )

#include <iostream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <string>
#include <map>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;

bool init_map( const char* const file_name, map< string, size_t >& np_map )
{
  ifstream file( file_name ) ;
  if( !file ) return false ;
  string line ;
  while( getline( file, line ) )
  {
    tokenizer<> toker(line);
    tokenizer<>::iterator iterator = toker.begin() ;
    string fn = *iterator++ ;
    np_map[fn] = lexical_cast<size_t>( *++iterator ) ;
  }
    return !np_map.empty() ;
}

int main()
{
  const char* const file_name = "whatever.txt" ;
  map< string, size_t > name_pos_map ;
  init_map( file_name, name_pos_map ) ;

  // look up
  string fn("0002.ogg") ;
  if( name_pos_map.find(fn) != name_pos_map.end() )
    cout << "found " << fn << " pos: " << name_pos_map[fn] << '\n' ;
  else
    cout << "did not find " << fn << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

bsd: http://people.freebsd.org/~kientzle/libarchive/
as root, cd /usr/ports/archivers/libarchive && make install clean

windows: http://gnuwin32.sourceforge.net/packages/libarchive.htm
you would need to fetch the setup program & verify the MD5 checksum manually

vijayan121 1,152 Posting Virtuoso

> am planning to write a simple implementation of T9 , as seen in nokia phones.
Could someone suggest an efficient way to go about this ??
http://en.wikipedia.org/wiki/Trie
http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Tree/PATRICIA/

vijayan121 1,152 Posting Virtuoso

if you are interested in only an approximate value, you could use a type like double for computing the result. for example, a long double can hold very large values, but precision is limited (on my compiler, the mantissa is accurate upto 15 decimal digits).

#include <limits>
#include <iostream>
#include <iomanip>
using namespace std;

inline long double factorial( unsigned int n )
{
   long double result = 1.0 ;
   while( n>1 ) result *= n-- ;
   return result ;
}

int main()
{
  cout << "unsigned int-\t" << numeric_limits< unsigned int >::max() << '\t'
       << numeric_limits< unsigned int >::digits10 << " decimal digits\n" ;
  cout << "long double-\t" << numeric_limits< long double >::max() << '\t'
       << numeric_limits< long double >::digits10 << " decimal digits\n" ; ;

  cout << fixed << setprecision(0) << "53! ~= " << factorial(53) << '\n' ;
}
/**
>g++ -Wall -std=c++98 num_limits.cpp && ./a.out
unsigned int-   4294967295      9 decimal digits
long double-    1.18973e+4932   15 decimal digits
53! ~= 4274883284060023952295713899453537359909467862005827442747675726839808
*/

for accurate results, you could use a library eg. https://sourceforge.net/projects/cpp-bigint/

SpS commented: Nicely Presented +3
vijayan121 1,152 Posting Virtuoso

the simple answer is that the implementor does not want anyone else to be able to destroy the object. examples are: a. a singleton object which should be destroyed only when the program ends b. the object is reference counted and will self-destruct when all outstanding references have been released. such objects cannot have an automatic storage duration (storage duration would be dynamic); so destruction at end of scope would not apply to these objects. see: http://www.boost.org/libs/smart_ptr/sp_techniques.html#preventing_delete

vijayan121 1,152 Posting Virtuoso

> I know the if statement would be a better choice but I must you use the switch for an assignment
would this make your teacher happy?

enum { LESS_THAN_10000, NOT_LESS_THAN_10000 };
int to_be_used_in_switch = sales < 100000.0 ? 
                       LESS_THAN_10000 : NOT_LESS_THAN_10000 ;
switch( to_be_used_in_switch )
{
       case LESS_THAN_10000:
            /* ... */ break ;
       case NOT_LESS_THAN_10000:
            /* ... */ break ;
       default:
            assert(false) ;
 }
Hamrick commented: ooh, good idea! +2
vijayan121 1,152 Posting Virtuoso

an alternative is to use the ctype<> facet. the advantages are a. also works with c++ strings b. locales other than the default locale are supported (behaviour is unaffected by the LC_CTYPE category of the current c locale). 3. will not fail if a wide-character code encountered does not correspond to a valid character.

#include <locale>
#include <iostream>
#include <string>
#include <sstream>
using namespace std ;

wstring widen( const string& str )
{
    wostringstream wstm ;
    const ctype<wchar_t>& ctfacet = 
                        use_facet< ctype<wchar_t> >( wstm.getloc() ) ;
    for( size_t i=0 ; i<str.size() ; ++i ) 
              wstm << ctfacet.widen( str[i] ) ;
    return wstm.str() ;
}

string narrow( const wstring& str )
{
    ostringstream stm ;
    const ctype<char>& ctfacet = 
                         use_facet< ctype<char> >( stm.getloc() ) ;
    for( size_t i=0 ; i<str.size() ; ++i ) 
                  stm << ctfacet.narrow( str[i], 0 ) ;
    return stm.str() ;
}

int main()
{
  {
    const char* cstr = "abcdefghijkl" ;
    const wchar_t* wcstr = widen(cstr).c_str() ;
    wcout << wcstr << L'\n' ;
  }
  {  
    const wchar_t* wcstr = L"mnopqrstuvwx" ;
    const char* cstr = narrow(wcstr).c_str() ;
    cout << cstr << '\n' ;
  } 
}
WolfPack commented: I didn't know this. Thank you. +7
vijayan121 1,152 Posting Virtuoso

> i think im going to ask my IT teacher ... but he sucks
why don't you ask this person? http://www.research.att.com/~bs/bs_faq2.html#void-main

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

(1*n)+(2*n)+(3*n)...(n*n) == (1+2+3+..+n)*n == (n+1)/2*n*n

vijayan121 1,152 Posting Virtuoso

works fine on my machine; after kicking out <conio.h> and changing void main() to int main().
which compiler are you using? try stringstream stm(buffer) ; stm >> num;

vijayan121 1,152 Posting Virtuoso

> i did what you suggested and i got::....
you have not defined node::node_pool.
see line 23 of the earlier post boost::pool<> node::node_pool( sizeof(node) ) ;

n.aggel commented: excellent poster! +1
vijayan121 1,152 Posting Virtuoso

if you are going to have only one object of your heap class at a time (ie. you do not create a second heap before destroying the existing one), you could just call boost::pool<>::purge_memory() in your destructor. or you could remove the destructor and call this from outside. or you could have one boost::pool<> per heap, and call boost::pool<>::purge_memory() on it in the destructor. the last option has technical merit, but would require some modification to the part of the code where you allocate/deallocate nodes.

vijayan121 1,152 Posting Virtuoso

> ...what do you mean by saying if the destructor of a node is a trivial one..here is my node:
the destructor of you node is trivial (ie. a destructor is deemed to be declared, but is not synthesized by the implementation).

> and if this is the only way to implement pool, i will have to write the part of the program that instantiates the heap....{everywhere i've use the new operator...}
the solution would be to overload operators new and delete for your node.
here is how you could do it using boost.pool

#include <boost/pool/pool.hpp>
#include <cassert>

struct node // has a trivial destructor
{
  int element ;
  node* left ;
  node* right ;
  int field ;
  static boost::pool<> node_pool ;
  static void* operator new( size_t sz )
  {
    assert( sz == sizeof(node) ) ;
    return node_pool.malloc() ;
  }
  static void operator delete( void* ptr )
  {
    assert( node_pool.is_from(ptr) ) ;
    node_pool.free(ptr) ;
  }
};

boost::pool<> node::node_pool( sizeof(node) ) ;

void allocate_lots_of_nodes_but_do_not_deallocate_them()
{
  // function allocates a large number of nodes
  for( int i = 0 ; i < 1023*1024*16 ; ++i )
  {
    node* pn = new node ;
    // do something with pn; perhaps insert into a tree etc.
    // don't bother to delete
  }
} 

int main()
{
  for( int i=0 ; i<8 ; ++i )
  {
    allocate_lots_of_nodes_but_do_not_deallocate_them() ;

    // frees every memory block. invalidates any pointers previously
    // returned by allocation functions
    node::node_pool.purge_memory() ;
  }
}
/**
>g++ -Wall -std=c++98 …
vijayan121 1,152 Posting Virtuoso

..so basically the problem is if i can free the memory without visiting every node....

since all the nodes are of the same size, you could use a pool allocation (also called "simple segregated storage"). see: http://www.boost.org/libs/pool/doc/concepts.html
boost.pool is a library you could use; it is very efficient. and you could free all chunks in a pool in one go. if the destructor of the node is a trivial one, you can bypass visiting all nodes. if not, you will have to traverse every node (with a little extra overhead: keep a pointer to the next allocated node with each node in the pool), this would be just a sequential, linear traversal.

vijayan121 1,152 Posting Virtuoso

since a heap is a *balanced* binary tree (it has the 'shape' property), you do not need nodes to implement it. we can store the heap in a compact manner in a (dynamically resizeable) array; this would be much more efficient. see: http://en.wikipedia.org/wiki/Binary_heap#Heap_implementation

vijayan121 1,152 Posting Virtuoso
struct singleton
{
  // return a reference, not a pointer. the problem with returning
  // a pointer is that a caller might be tempted to call delete on it
  // returning an auto_ptr<> to a singleton is ruled out; 
  // it's (or it's copy's) destructor *will* call delete on the object.
  static singleton& get_the_only_object() ;

  /* other operations */
           
  private :
    
    // no accessible constructor; only way to get the singleton
    // is through the public *static* method 
    singleton() { /* ... */ }
    
    // copy constructor; there is only one object, copy of it should not
    // be created. do not define this!
    singleton( const singleton& ) ;

    // only one object; assignment is always a trivial self-assignment
    // do not define this!
    void operator= ( const singleton& ) ;

    /* other private stuff */
};

// this simple idea was first presented by scott myers
// see 'more effective c++', item 26
singleton& singleton::get_the_only_object()
{
  // created the first time flow of control reaches this point
  static singleton the_only_one ;
  // destroyed after main returns 
  return the_only_one ;
}

int main()
{
  // a user gets (a reference to) the singleton object this way
  singleton& object = singleton::get_the_only_object() ;
  // object.do_something() ;
}

this works fine in many cases. however, as andrei alexandrescu points out in his book 'modern c++ design', "The singleton design pattern is unique in that ... it's description is simple, but it's implementation is complicated". and then goes on to discuss singleton implementation issues in some 25 pages or so.

vijayan121 1,152 Posting Virtuoso

are you trying to run your program from within the turbo c++ ide? in this case, the amount of heap memory that you have is very limited. the memory layout would be something like this (wwww < xxxx < yyyy < zzzz < a000) :

0000:0000 interrupt vector
0040:0000 dos low memory
wwww:0000 IDE code, data, heap, stack.
xxxx:0000 your program code.
yyyy:0000 your program data& stack.
zzzz:0000 your program heap.
A000:0000 end of heap (start of graphic memory).
"640 Kb is more than enough for anybody" - Bill Gates

with the changes ( char huge* I, delete[] I ), have you tried getting out of the ide and running the program from the shell (command.com)? even if it may not work from within the ide, it should work once you kick the ide out. you would then have more memory for your program.

this would take care of the code that you posted; you should have enough heap size for an array of 100KB. if you want array sizes of a few MB, you would need to use a dos extender (like DPMI) which allows access to the protected mode memory on your machine. i do not know if turbo C++ ships with a dos extender or would be able to use one if it is present. however, since you say "64K gives me 304 mm of movement of the machine whereas I need at least 2000 mm.", …

vijayan121 1,152 Posting Virtuoso

> Because the code must read the digit one by one as individual characters(CHAR values)and convert them to numeric form.
or you can read the literal digits into a string; this would be easier.

> And you know C++ uses ASCII code for a character when it appears in an arithmetic expression.
not necessarily true for C++ or even C. this is all that you can assume:

The code value zero is reserved for the null character which is always in the target character set. Code values for the basic C character set are positive when stored in an object of type char. Code values for the digits are contiguous, with increasing value. For example, '0' + 5 equals '5'. Code values for any two letters are not necessarily contiguous.

> Also how do u handle for the carry from previous sum?
simulate adding integers by hand. here is an example (perhaps not suitable for submission as a homework assignment)

#include <string>
#include <vector>
#include <iostream>
#include <cctype>
#include <algorithm>
#include <cassert>
#include <boost/lambda/lambda.hpp>
#include <boost/operators.hpp>
using namespace std ;
using namespace boost ;
using namespace boost::lambda ;

template < size_t NDIGITS > 
struct integer : private addable< integer<NDIGITS> > 
{
  integer() : digits(NDIGITS) {}
  explicit integer( const string& str ) : digits(NDIGITS)
  {
    assert( str.size() <= NDIGITS ) ;
    for( size_t i=0 ; i<str.size() ; ++i ) { assert( isdigit(str[i]) ) ; }
    transform( str.begin(), str.end(),
               digits.begin() + NDIGITS - str.size(),
                _1 - '0' …