vijayan121 1,152 Posting Virtuoso

the ordering of data declared as bit fields is implementation dependant. you have to test and figure out what it is for your compiler.

#include <iostream>

int main()
{
  // assumes that the ordering of data declared as bit fields is from
  // low to high bit. this is implementation dependant
  struct number { unsigned second:2 ; unsigned first:6 ; };
  union { number n ; unsigned char c ; };
  n.first = 1 ; n.second = 0 ;
  std::cout << int(c) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

in fact the performance loss is so minimal, it's hardly worth taking that into account when trying to decide when and where to use exception handling.

not true. exceptions are designed with the idea that
a. you do not have to pay a high performance penalty in the event of there being no error
b. if there is an error, you are willing to spend time recovering from it.
c. exceptions, as the name suggests, are used to indicate exceptional conditions that do not occur in the normal course of events.

Ancient Dragon's statement is accurate; the easiest way to check it out is
a. generate the assembly code for both versions and have a look at it.
b. write a test driver and time the performance on your implementation.

vijayan121 1,152 Posting Virtuoso

construct a bitset using the string and then convert it to a ulong.

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

int main()
{
  string str = "00000100" ;
  cout << bitset<numeric_limits<unsigned long>::digits>(str).to_ulong() 
         << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

you are getting the error here.

my_reverse_iterator p(it);

this is because my_reverse_iterator is a template class; you are not using it as such.
change that to

my_reverse_iterator<vector<int>::iterator> p(it);

and you can get started on the rest of the class.

i presume you are not allowed to use the iterator adapter provided by libstdc++; if you are you could get your reverse iterator by a mere typedef. for example:

#include <iterator>
#include <iostream>
#include <algorithm>
using namespace std ;

int main()
{
  char cstr[] = "abcdefghijkl" ;
  
  typedef  char* iterator ;
  iterator begin(cstr), end(cstr+sizeof(cstr)-1) ; // exclude the null
  copy( begin, end, ostream_iterator<char>(cout) ) ; cout << '\n' ;

  typedef reverse_iterator<iterator>  rev_iterator ;
  rev_iterator rbegin(end), rend(begin) ;
  copy( rbegin, rend, ostream_iterator<char>(cout) ) ; cout << '\n' ;

  typedef reverse_iterator<rev_iterator>  rev_rev_iterator ;
  rev_rev_iterator rrbegin(rend), rrend(rbegin) ;
  copy( rrbegin, rrend, ostream_iterator<char>(cout) ) ; cout << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

you could make approximate drawings using character based graphics.

#include<iostream>         
#include<string>
#include <cassert>

struct shape
{
  virtual void draw() const = 0 ;
  virtual ~shape() {}
};

struct rectangle : shape
{
  explicit rectangle( int h = 10, int w = 10 ) : height(h), width(w) 
  { assert( h>2 && w>2 ) ; }
  virtual void draw() const ; // override
  private:
    int height ;
    int width ;
};

void rectangle::draw() const
{
  std::string top_bottom( width, '*' ), middle( width, ' ' ) ;
  middle[0] = middle[width-1] = '*' ;
  std::cout <<  top_bottom << '\n' ;
  for( int i=0 ; i<(height-2) ; ++i ) std::cout << middle << '\n' ;
  std::cout <<  top_bottom << '\n' ;
}

int main() 
{
  shape* s = new rectangle( 8, 12 ) ;
  s->draw() ;
  delete s ;
}

note: a circle would be much more interesting

vijayan121 1,152 Posting Virtuoso

I dont think this works please be more specific

here is the output.
g++ -std=c++98 -Wall -I/usr/include/boost-1_33_1 tokenize.cpp; ./a.exe

include
iostream
include
boost
tokenizer
hpp
include
string
include
fstream
int
main
using
namespace
std
using
namespace
boost
ifstream
file
FILE
string
str
while
getline
file
str
tokenizer
toker
str
for
tokenizer
iterator
beg
toker
begin
beg
toker
end
beg
cout
beg
n

vijayan121 1,152 Posting Virtuoso

the easiest way that i know is to use the boost tokenizer library.

#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
#include <fstream>

int main()
{
   using namespace std;
   using namespace boost;
   ifstream file( __FILE__ ) ;
   string str ;
   while( getline( file, str ) )
   {
        tokenizer<> toker( str ) ;
        for( tokenizer<>::iterator beg = toker.begin(); 
              beg != toker.end() ; ++beg ) cout << *beg << '\n' ;
   }
}
vijayan121 1,152 Posting Virtuoso

this kind of functionality is required only when the generic or metaprogramming paradigms are used. otherwise, when you write a function in a statically typed language, you already know the type of every expression.
for a tutorial on discovering and using information about types, see this: http://www.boost.org/doc/html/boost_typetraits/background.html

these books would give more information on this:
1. Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu
2. C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond
by David Abrahams, Aleksey Gurtovoy

vijayan121 1,152 Posting Virtuoso
enum { N=20, M=50 };
int(*a)[M] = malloc( sizeof( int[M] ) * N ) ; // C
int(*b)[M] = new int[N][M] ; // C++
vijayan121 1,152 Posting Virtuoso

what is the definition of the + operator for STL vectors?
template<typename T, typename Allocator>
vector<T, Allocator> &operator+ (const vector<T, Allocator> &a, const vector<T, Allocator> &b)
and do I just code this outside of main?

yes, you define it as a global. however, there is a logical error in your declaration; the result of operator+ is a temporary variable; you should return the temporary by value, not reference.
what does it mean to add two vectors? concatenate or add element by element?

vijayan121 1,152 Posting Virtuoso

now it will not compile. for a const map, the iterator is a const_iterator. change the typedef for the iterator to

typedef simap::const_iterator miterator ;
vijayan121 1,152 Posting Virtuoso

the last else (lines 13,14)should be in a block ({})

vijayan121 1,152 Posting Virtuoso

so something like

int temp

temp = money * 100

?

yes. and if you want the function to have output parameters, pass them by reference, not value.
also passing the amount in cents (as an integer) rather than a float would help avoid floating point round off errors.

vijayan121 1,152 Posting Virtuoso

what you need is integer division. in your program, temp is a float. float(123)/100 will give you 1.23, not 1. and a standards-compliant compiler would give you a compile-time error if you try float(123)%100

vijayan121 1,152 Posting Virtuoso

Thanks,

Fully agree with your reply, but I just want to see if it is possible to tell the compiler to display the number/output in a manner (with all the zeros/digits in it) that one wants to. Cheers...

stm << fixed << setprecision(200) << number << '\n' ;

would do what you want. obviously this will not give you an accuracy of 200 digits after the decimal.
see this example:

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

template<typename T> void show_limits()
{
  typedef numeric_limits<T> limits ;
  cout << "********************* type " << typeid(T).name() 
         << " **************************\n" ;
  cout << "smallest nonzero denormalized value: " 
         << limits::denorm_min() << '\n' ;
  cout << "allows  denormalized values? " << boolalpha 
         << (limits::has_denorm==denorm_present) << '\n' ;
  cout << "difference between 1 and the smallest value greater than 1: "  
         << limits::epsilon() << '\n' ;
  cout << "maximum rounding error: " << limits::round_error() << '\n' ;
  cout << "base (radix) used for the representation: " 
         << limits::radix << '\n' ;
  cout << "minimum value of exponent (radix): " 
         << limits::min_exponent << '\n' ;
  cout << "approximate minimum value of exponent (decimal): " 
         << limits::min_exponent10 << '\n' ;
  cout << "maximum value of exponent (radix): " 
         << limits::max_exponent << '\n' ;
  cout << "approximate maximum value of exponent (decimal): " 
         << limits::max_exponent10 << '\n' ;
  cout << "minimum normalized value: " << limits::min() << '\n' ;
  cout << "maximum normalized value: " << limits::max() << "\n\n" ;
 
} …
vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

typedef map<string,int> simap ;
typedef simap::iterator miterator ;
typedef vector<miterator> ivector ;

ivector find_values( simap& m, int val ) ;

int main()
{
    simap map ;
    map["one"] = 1;
    map["two"] = 2;
    map["three"] = 3;
    map["four"] = 2;
    map["five"] = 5;
    map["six"] = 2;
    
    ivector found = find_values(map,2);
    for( ivector::size_type i=0U ; i<found.size() ; ++i )
      cout << found[i]->first << ' ' << found[i]->second << '\t' ;
    cout << '\n';
}

ivector find_values( simap& m, int val )
{
    ivector v_found;
    for( miterator i = m.begin() ; i != m.end() ; ++i )
        if( i->second == val ) v_found.push_back(i) ;
    return v_found;
}

note: the question is not const-correct. ideally, it should have taken a reference to a const map, and returned a vector of const_iterators. it appears inefficient to make a copy of the vector on return from the function, but a good compiler can use RV optimization to avoid the overhead.

vijayan121 1,152 Posting Virtuoso

If yes,
Help with the declaration

template< typename T > inline void swap( T& a, T& b ) ; // declaration (function)
template< typename T, size_t N > struct array ; // declaration (class)

// definition of function
template< typename T > void swap( T& a, T& b ) 
{  T temp(a) ; a=b ; b=temp ; }

// definition of class
template< typename T, size_t N > struct array 
{
  T& operator[] ( size_t i ) 
  {
     if( i >= N ) throw "array bound exceeded!" ;
     return a[i] ;
  }

  const T& operator[] ( size_t i )  const 
  {
     if( i >= N ) throw "array bound exceeded!" ;
     return a[i] ;
  }

  private: T a[N] ;
};
vijayan121 1,152 Posting Virtuoso

i think the best way would be
a. allocate an array of pixel* , one entry per transmitter.

pixel** ppp = new pixel* [ NUM_TRANSMITTERS ] ;

b. as you read each file, allocate memory for the pixels

ppp[transmitter_number] = new pixel[npixels_in_this_transmitter] ;

c. you could either read the file data directly into the array, or you could create a local variable of type pixel and copy it into the array. do not worry about the overhead of copying the pixel object; it is small (x,y,power) and can be copied using bit-wise semantics (in c++ jargon, has a trivial copy constructor). so the compiler will generate the copy code inline (three or four instructions for your pixel).
d. need a little more information about destroying pixels. do you destroy pixels one by one or is it that when a new file comes in, you destroy all the pixels for that transmitter and create a new set of pixels? and if it is the second case, would the number of pixels change?

thekashyap commented: Rep was due, just forgotten.. :). Thanks. For all posts in this thread +1
vijayan121 1,152 Posting Virtuoso

ok thats what I said... in here we can find same amount of words. But I dont want to find same word.. I want to find which one is first? I mean how can program recognize the john should be before than mary?? because it starts j which is before than m(mary)

char john[] = "john" ;
char mary[] = "mary" ;
int result = strcmp( john, mary ) ;
if( result < 0 ) cout << john << " should be before " << mary << '\n' ;
else if( result > 0 ) cout << john << " should be after " << mary << '\n' ;
else /* result == 0 */  cout << john << " compares equal to " << mary << '\n' ;
vijayan121 1,152 Posting Virtuoso

three calls to getline() with the first two using : as delimeter and third using newline. Then convert each string obtained into numerical value using sprintf() or strtol() or atoi() or stringstream, etc.

if multiple reads can be used, the easiest is

#include <iostream>
int main()
{
  int a, b, c ;  char colon ;
  std::cin >> a >> colon >> b >> colon >> c ;
  std::cout << a << '\t' << b << '\t' << c << '\n' ;  
}
vijayan121 1,152 Posting Virtuoso

and this is another (using boost)

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>

int main()
{
  using namespace std;
  using namespace boost;
  string str ;
  getline( cin, str ) ;
  tokenizer<> tokens(str);
  tokenizer<>::iterator iter = tokens.begin() ;
  try
  {
    int a = lexical_cast<int>(*iter), b = lexical_cast<int>(*++iter), 
                 c = lexical_cast<int>(*++iter) ;
    cout << a << '\t' << b << '\t' << c << '\n' ;  
  }
  catch( const bad_lexical_cast& ) { cout << "error in input\n" ; }
}
vijayan121 1,152 Posting Virtuoso

let's say the user enters a value in this format xx:xx:xx, where xx is an integer, how can I assign each xx to integer vars?

this is one way.

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

int main()
{
  string str ;
  getline( cin, str ) ;
  replace( str.begin(), str.end(), ':', ' ' ) ;
  istringstream stm(str) ;
  int a, b, c ; 
  stm >> a >> b >> c ;
  cout << a << '\t' << b << '\t' << c << '\n' ; 
}
vijayan121 1,152 Posting Virtuoso

last question :( I heard some bubblesort thing.. what is it.. is it suitable for me???

yes jerry, it would be very suitable for you. you would enter the struct (with name, year, doctor, illness as member variables) into an array and use a bubble sort (not the best sort unless you have only a handful of records; but probably the easiest one to learn as your first sort) to sort on the required field.
note: use the strcmp function to compare strings, < or > operator would do for the year (number). try googling on "bubble sort" "C" "tutorial" and see what comes up.

vijayan121 1,152 Posting Virtuoso

from your posted code, i infer/guess that the following are true:
a. you know the number of pixels before hand
b. you do not need to destroy pixels till end of program.
c. you want to keep the pixels in a std::vector.
and as stated, your goal is to increase the allocation/access speed.
it would be more efficient to use a std::vector<pixel> instead of a std::vector<pixel*> (extra spae requirement for pointer, two memory accesses instead of one). and if you need the address of a pixel for some reason, &(v) is always available.
for fast allocation, and for using a vector with value semantics, the easiest way is to use a custom allocater. here is some sample code:

#include <iostream>
#include <vector>
#include <new>
#include <memory>
using namespace std ;

class pixel
{
  public:
    pixel( int xx=0, int yy=0 ) : _x(xx), _y(yy) {}
    void print() { cout << this << " = " << _x << ',' << _y << endl ; }
    int _x, _y ;
};

struct pixel_allocator : public std::allocator<pixel>
{
    enum { NUM_PIXELS = 1024*1024*32 }; // number of pixels
    pointer allocate( size_type N, const void* = 0 ) 
    { 
        void* pv = cnt<NUM_PIXELS ? buffer + cnt*sizeof(pixel) : 0 ; 
        cnt += N ; 
        return pointer(pv) ; 
    } 
    void deallocate( pointer ptr, size_type count ) {} // do nothing!
    void construct( pointer ptr, const pixel& val ) { new(ptr) pixel(val) ; }
    void destroy( pointer ptr ) …
vijayan121 1,152 Posting Virtuoso

placement new can still be used; it would be more efficient in terms of both time and space than using the normal new.
here is the code (with the placement new modified).

#include <iostream>
#include <vector>
#include <new>
using namespace std ;

class pixel
{
  public:
    pixel( ) : _x(0), _y(0) {}
    void print() { cout << this << " = " << _x << ',' << _y << endl ; }
    int _x, _y ;
};

int main()
{
  static const int MAX_PIXELS = 10 ;
  pixel* buffer = new pixel[MAX_PIXELS] ;
  vector<pixel*> v ;
  for( int i = 0; i < MAX_PIXELS; i++ )
  {
      pixel* p = new (buffer+i) pixel() ; // buffer => buffer+i
      p->_x = i ;
      p->_y = MAX_PIXELS - i ;
      p->print() ;
      v.push_back( p ) ;
  }
  cout << endl << "-------printing-------" << endl << endl ;
  for( vector<pixel*>::size_type j = 0; j < v.size(); j++ )
  { cout << "v[" << j << "] = " ; v[j]->print() ; }
  return 0 ;
}

and here is the output:
0x804c000 = 0,10
0x804c008 = 1,9
0x804c010 = 2,8
0x804c018 = 3,7
0x804c020 = 4,6
0x804c028 = 5,5
0x804c030 = 6,4
0x804c038 = 7,3
0x804c040 = 8,2
0x804c048 = 9,1

-------printing-------

v[0] = 0x804c000 = 0,10
v[1] = 0x804c008 = 1,9
v[2] = 0x804c010 = 2,8
v[3] = 0x804c018 = 3,7
v[4] = 0x804c020 …

vijayan121 1,152 Posting Virtuoso

My requirement is: I need to create lots and lots of pixel objects (e.g. about 100 matrixs of 800x800 pixels each)

this is the kind of problem where you could use the flyweight design pattern quite effectively. see:
Design Patterns: Elements of Reusable Object-Oriented Software
by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (aka Gang of Four) - Addison-Wesley Professional Computing Series pages 195-206.
if you do not have ready access to the book, here is a lik which may help you:
http://www.informit.com/articles/article.asp?p=468380&seqNum=1&rl=1

vijayan121 1,152 Posting Virtuoso

placement new is used when you do not want operator new to allocate memory (you have pre-allocated it and you want to place the object there), but you do want the object to be constructed. examples of typical situations where this may be required are
a. you want to create objects in memory shared between two different processes
b. you want objects to be created in non-pageable memory
c. you want to seperate memory allocation from construction eg. in implementing a std::vector<> (see std::vector<>::reserve)

the basic problem is that the constructor is a peculiar function; when it starts off, there is no object, only raw memory. and by the time it finishes, you have a fully initialized object. therefore i. the constructor cannot be called on an object ii. however, it needs to access (and initialize) non-static members. this makes calling the constructor directly an error. the solution is the placement form of operator new.

this operator is implemented as

inline void* operator new( size_t sz, void* here ) 
{ return here ; }
inline void* operator new[]( size_t sz, void* here ) 
{ return here ; }

in your case, using this is not required as an int is pod, it has a trivial constructor. if you want to use it, you could use it this way:

for( int i = 0; i < MAX_PIXELS; i++ )
    {
        int* p = new (buffer+i) int(i) ; // specify where you want the object …
vijayan121 1,152 Posting Virtuoso

Can't you just create an array of 5000 ints

for (int i =0; i< 5000; i++ )
{
   array[i] =i;
}

Then shuffle them around. So you would be picking two random index positions and swapping them. Do this say a couple of hundred times.

Then just print out the first 200 elements and you will get 200 random elements with no repeats in a number range from 0 - 5000.

This would be time-efficient and space-inefficient.

vijayan121 1,152 Posting Virtuoso

... but I'm stuck on how to avoid filling it with duplicate values. I'm assuming that i'll have to use either a linear or binary search function while filling the array...

1. you cannot do a binary search; the array is not ordered.
2. a linear search is possible, but it is not very efficient. filling up an array of size N would take O(N*N)
3. the smart thing to do would be to avoid the search alltogether.

to choose N unique numbers out of M
a. choose the first with probability N/M
b. choose the next with probability (N-1)/(M-1) if the first was chosen, N/(M-1) if it was not.
c. and so on.
this would take linear time. O(M)

here is an example of how this could be implemented.

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <iterator>
using namespace std ;

void fill_with_unique_rand( int* array, int N, int min_value, int max_value )
{
  int available = max_value - min_value +1 ;
  int required = N ;

  for( int i=0 ; i<available ; ++i )
    if( ( rand() % (available-i) ) < required )  // we have to choose required 
                                 // out of the remaining (available-i)
    {
      --required ;
      array[required] = min_value + i ;
    }

  random_shuffle( array, array+N ) ;   // if needed
}

template< int N > inline void fill_array_with_unique_rand( int (&array)[N], 
                                           int min_value, int max_value )
{ fill_with_unique_rand( array, N, min_value, max_value ) ; }

int …
vijayan121 1,152 Posting Virtuoso

start quote:

const int SIZE = 10;
double **arr = (double**)malloc(SIZE * sizeof(*arr));
for(int i = 0; i < SIZE; ++i)
{
    arr[i] = (double*)malloc(SIZE * sizeof(*arr[0]));
}
}

end quote.

This is first allocating an array of pointers, and allocating memory one by one for each one dimensional
array. (this kind of array is called a jagged array in C#).
A true two dimensional array is rectangular; a contigous area of memory which contains I*J elements.
we simulate this in C by creating an array, every element of which is an array. for example,

int a[50][30] ; // automatic or static storage class
int (*b)[30] = malloc( sizeof( int[30] ) * 50 ) ; // dynamic storage class

note: b is really a pointer to the first element (which is an array of 30 integers).

vijayan121 1,152 Posting Virtuoso

This problem is covered in detaill in Jon Bentley's Programming Pearls (Second Edition)
ISBN 81-7808-022-2 (Pearson Education)
see column 8 : Algorithm Design Techniques (pages 77-86)

Even if you have been programming for a number of years,
but have not seen this book so far, do yourself a favour. Get a copy.

vijayan121 1,152 Posting Virtuoso

you do not have to make one. it is available in libraries.
either the boost string algorithms or the boost tokenizer could be used.

here is an example using the boost string algorithms split. as you can notice, c++ libraries are
far more powerful and expressive. in this example, we are splitting on different criteria and placing the
result into different types of containers. and we are using one function: split to do all this.

#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/lambda/lambda.hpp>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
using namespace std;
using namespace boost;
using namespace boost::lambda;

template<typename C> inline void print( const C& cntr )
{ for_each( cntr.begin(), cntr.end(), cout << constant('[') << _1 << "]  " ) ; }

int main()
{
  string str = "ab+*%cde4fg*hijk   lmno%+pqr3stu--vwx yz   "
                       "ab0cde+fgh2ij345klm4nop5qr7st" ;

  vector<string> vec ;
  split( vec, str, is_any_of("+*%-"), token_compress_on ) ; 
  print(vec) ; cout << '\n' ; 

  list<string> lst ;
  split( lst, str, is_from_range('2', '6') ) ; // token_compress_off by default
  print(lst) ; cout << '\n' ; 

  deque<string> deq ;
  split( deq, str, is_space(), token_compress_on ) ; 
  print(deq) ; cout << '\n' ; 
}

and this is the output:
g++ -Wall -std=c++98 -I/usr/local/include split.cpp ; ./a.out
[ab] [cde4fg] [hijk lmno] [pqr3stu] [vwx yz ab0cde] [fgh2ij345klm4nop5qr7st]
[ab+*%cde] [fg*hijk lmno%+pqr] [stu--vwx yz ab0cde+fgh] [ij] [] [] [klm] [nop] [qr7st]
[ab+*%cde4fg*hijk] [lmno%+pqr3stu--vwx] [yz] [ab0cde+fgh2ij345klm4nop5qr7st]


ps: i should qualify my first statement; you do not have to make one; …

StuXYZ commented: Really nice example, thx +3
vijayan121 1,152 Posting Virtuoso

MIT's Technology Review magazine published an interview with Stroustrup in Nov, 2006:
'The Problem With Programming: Bjarne Stroustrup, the inventor of the C++ programming language, defends his legacy and examines what's wrong with most software code.'
link: http://www.technologyreview.com/Infotech/17831/

this generated such heated debate for an example, see:
http://it.slashdot.org/article.pl?sid=06/12/05/0045234
that Technology Review conducted a second interview (dec 2006), addressing some of the objections to C++. link: http://www.technologyreview.com/Infotech/17868/

you may find these interesting.

vijayan121 1,152 Posting Virtuoso

these two functions are the copy constructor and the overloaded assignment operator.
these would be explained in every C++ beginner's book, including your text book.

vijayan121 1,152 Posting Virtuoso

vijayan121, I don't think ifstream works for files over 2GB, which mine is. (7GB)

true, unless you are using a standard library implementation like one from dinkumware, and that too on a
64-bit architecture.

here is something you could try.

a. map chunks of the file (say 256 MB each) into memory.
how you would do this depends on the platform:
unix: use mmap (compile with -D_FILE_OFFSET_BITS=64 to make sure that off_t is a 64-bit value.
linux: same as unix, but i think kernels prior to something like 2.6.10 are buggy with large
files which are memory mapped.
windows: the CreateFile/CreateFileMapping/MapViewOfFile triplet

b. wrap an stlsoft::basic_string_view<char> around the chunk that is mapped.
eg. stlsoft::basic_string_view<char> str( static_cast<const char*>(address), nchars ) ;

download stlsoft from http://www.synesis.com.au/software/stlsoft.
for basic_string_view<> documentation, see:
http://www.synesis.com.au/software/stlsoft/doc-1.9/classstlsoft_1_1basic__string__view.html
stlsoft library is header-only; you need only #include the requisite files to access the functionality.

c. stlsoft::basic_string_view<> does not have the find family member functions as in std::string;
but do have provide polymorphic iterators. so, functions like find in the <algorithm> header
could be used.
eg. std::find( str.begin(), str.end(), '*' ) ;

vijayan121 1,152 Posting Virtuoso

Is there a way using file handling functions to search within a text file to find the position of certain text WITHOUT having to read each character/line and evaluating it?

the short answer is no. but you may not have to do this; let the standard library do the work.

For example, let's say I have a file of 'messages', where a message has a distinct start and end characters. I would like to go through the file and locate the positions of each start of a message. I would then index this (let's say with an stl map of each message # to it's starting position in the file. Later on, I could then ask for a particular message # by jumping to that position in the file (let's say with fseek) and read just that portion of the file.

here is an example of how to do this:

//23456<890<2345678<0123<567890
//45<789<1234567<90123456<890
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{
   vector<streampos> index ; // filepos where we find a '<' 
   
   // create index
   {
    ifstream file(__FILE__) ; 
    enum { BUFFER_SIZE = 1024*1024*256 } ; // a larger buffer can improve
    vector<char> large_buffer(BUFFER_SIZE) ; //  performance for very large files
    file.rdbuf()->pubsetbuf( &large_buffer.front(), large_buffer.size() ); 
    file >> noskipws ; 
    istream_iterator<char> begin(file), end ;
    begin = find( begin, end, '<' ) ;
    while( begin != end )
    {
      index.push_back( file.tellg() + streamoff(-1) ) ;
      begin = find( ++begin, end, '<' ) ;
    }
   } …
vijayan121 1,152 Posting Virtuoso

>>Extract the lower 4 digits of the result produced by step 2.

The easy way is to convert the number to a string then only use the last 4 digits.

int num = 12347;
char buf[10];
sprintf(buf,"%d",num);
int seed = atoi( &buf[1] );

The easier way is to divide by 10000 and take the remainder

int seed = num % 10000 ;
vijayan121 1,152 Posting Virtuoso

please post
a. what are the errors you get
b. what do you think is wrong?

vijayan121 1,152 Posting Virtuoso

All the errors are from these codes. I have no clue why? Thanks in advance.

std::map<std::string, std::map<std::string, c_PerformanceMeasurement> >::iterator iClass = mPerformances.find(Class);
if (iClass != mPerformances.end())
 {
  std::map<std::string, c_PerformanceMeasurement>::iterator iPerformance = iClass->second.find(Name);
  if (iPerformance != iClass->second.end())
  {
   return iPerformance->second;
  }
 }

looks like the variable mPerformances is a const map<...
you have to change ...>::iterator to ...>::const_iterator

vijayan121 1,152 Posting Virtuoso

run it from the command line. if you are on windows, either open a command window or
type in the command line in the Run.. dialog opened from the windows menu.

vijayan121 1,152 Posting Virtuoso

for suggestion a
let us say your queue (numbers are priorities, lower numbers indicate higher priority) looks like this:
2 5 8 11 16 23 32
and you want to add 14.
add it at the end to get 2 5 8 11 16 23 32 14
compare 14 with 32, priority is higher, so swap them to get 2 5 8 11 16 23 14 32
compare 14 with 23, priority is higher, so swap them to get 2 5 8 11 16 14 23 32
compare 14 with 16, priority is higher, so swap them to get 2 5 8 11 14 16 23 32
compare 14 with 11, priority is lower, so let things beso after add, you get a sequence sorted on priorities.
one with the highest priority is right in front.

vijayan121 1,152 Posting Virtuoso

can someone tell me how to check this dam thing lol .... i mean how do i use the command promt argument thingy .... i have no clue on how to run this thing

<your program name here> file1.txt file2.txt file3.txt result.txt

this line is ok as it is:
for(int i = 1; i < argc - 1; i++)

vijayan121 1,152 Posting Virtuoso

modify final.open(argv[5]);
to final.open(argv[4]);
and your code will work fine for 4 command line args.

vijayan121 1,152 Posting Virtuoso
#include <fstream>
#include <iterator>
#include <algorithm>
using namespace std;

struct copy_file_to_stream_t 
{
  explicit copy_file_to_stream_t( ostream& s ) : stm(s) {}
  void operator()( char* file_name ) const
  {
    ifstream file(file_name) ; file >> noskipws ;
    istream_iterator<char> begin(file), end ;
    copy( begin, end, ostream_iterator<char>(stm) ) ;
  }
  ostream& stm ;
};

int main( int argc, char** argv )
{
  if( argc > 2 )
  {
    ofstream file( argv[ argc-1 ] ) ;
    copy_file_to_stream_t copy_file_to_stream(file) ;
    for_each( argv+1, argv+argc-1, copy_file_to_stream ) ;
  }
}

*** warning *** do not submit this; you will get into trouble if you do.

vijayan121 1,152 Posting Virtuoso

if performance is not of great concern, you could do one of the following:
a. when you add an item to the array,
1. add it as the last element.
2. compare it with the element just ahead of it; if it has a higher priority,
swap the two.
3. repeat step two till either i. you find that the element just ahead has
a higher priority or ii. you have reached the front of the array.
now to remove/return the item with the highest priority, you know
that it is at the front of the array.
b. when you add an element add it at the back, as the last item.
to find the element with the highest priority, do a linear search.
with either of these approaches, the time taken to start with an empty
priority queue, add N elements and then remove N elements would be
O(N*N) - ie quadratic time.

to get a more efficient implementation ( O( N*log(N) ) ), you would
need to use a heap data structure; i am certain, it would be there
in one of your your text books.

i would suggest that you start of by implementing a dynamically
resizeable array first. make sure that it is working. and then
implement the priority queue on top of it.

vijayan121 1,152 Posting Virtuoso

great. perhaps you would not be viewed as a newbie; certainly not in daniweb. thimgs like predicates are rocket science out here.

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

just to make sure, compile with
g++ -std=c++98 -Wall
and see if you get any warnings or errors.
no errors or warnigs for me too.

vijayan121 1,152 Posting Virtuoso

the label menu: (line 28) hides the variable char menu (line 12). you could use the scope
resolution operator (::menu) to make the error go away; but hiding names like this is not a good idea.
technically, a label is a pointer (address).

vijayan121 1,152 Posting Virtuoso

a. read one line
b. strip off unwanted chars (non-printable/whitespace/,)
c. analyze the remaining chars.
repeat a,b,c till end of file.

struct is_2b_thrown_away
{
  bool operator() ( char ch ) const
  { return !isprint(ch) || isspace(ch) || (ch==',') ; }
};

void process_file( const char* file_name )
{
    ifstream file(file_name) ;
    string line ;
    while( getline( file, line ) )
    {
       vector<char> chars ;
       remove_copy_if( line.begin(), line.end(), back_inserter(chars), 
                                      is_2b_thrown_away() ) ;
       // analyse characters in vector chars
    }
}