vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
#include <vector>
#include <utility>

int main()
{
    // C++0X
    std::vector< std::pair<int,int> > sequence = { {1,2}, {3,4}, {5,6}, {7,8} } ;
    int sum2nd = 0 ;
    for( const auto& pair : sequence ) sum2nd += pair.second ;
}
vijayan121 1,152 Posting Virtuoso

> there was no .tli file. Why is this?

The .tli contains generated inline member functions that wrap the interface methods.

No .tli file is generated id you suppressed it's generation by using the raw_interfaces_only attribute in the #import directive.

> When I was trying to instantiate the COM object i kept getting an error -
> class not licensed for use. I was however able to find a registry script
> that added the license to the registry and I am able to use the ocx.

1. Use CoGetClassObject() to get the IClassFactory2 interface of the class object.

2. Invoke IClassFactory2::CreateInstanceLic() to create the instance

Something like

IClassFactory2* factory = 0 ;
HRESULT hr = ::CoGetClassObject( CLSID_Registration, CLSCTX_INPROC_SERVER, 0, 
                                 IID_IClassFactory2, 
                                 reinterpret_cast<void**>(&factory) ) ;
if( SUCCEEDED(hr) )
{
    IRegistration* reg = 0 ;
    hr = factory->CreateInstanceLic( 0, 0, IID__Registration, 
                                     "put the license string here",
                                     reinterpret_cast<void**>(&reg) ) ;
    if( SUCCEEDED(hr) )
    // etc
}

> Can you please shed some light on as to what that license is meant to do
> and how it is created?

See http://msdn.microsoft.com/en-us/library/aa751973%28v=vs.85%29.aspx


> I would like to learn more about COM and ActiveX controls.
> Do you have any books that I can refer to.

Start with 'Inside Com' http://www.amazon.com/Inside-Microsoft-Programming-Dale-Rogerson/dp/1572313498

Then read Don Box http://www.amazon.com/Essential-COM-Don-Box/dp/0201634465/
and 'Understanding ActiveX and OLE' http://www.amazon.com/Understanding-ActiveX-OLE-Developers-Technology/dp/1572312165

vijayan121 1,152 Posting Virtuoso

The std namespace has a std::max . This is causing a name clash because of

using namespace std ;

int max ;

(The implementation seems to be gratuitously including a header which declares std::max ).

Either remove the using directive (and qualify names with std:: as in std::cout )or change the name max to something else.

vijayan121 1,152 Posting Virtuoso

Use std::vector<> instead of raw arrays.

For a beginner, a vector is easier to use (correctly).

http://www.cprogramming.com/tutorial/stl/vector.html

vijayan121 1,152 Posting Virtuoso

Clang; a great C++98 compiler, available as a set of libraries, under an open source non-viral license.

However, it does not yet support most of the C++11 features.

http://clang.llvm.org/features.html#libraryarch

vijayan121 1,152 Posting Virtuoso

> Just out of curiosity, you allocate the entire image in a single block of memory...

You might want t have a look at the boost pool library.
http://www.boost.org/doc/libs/1_47_0/libs/pool/doc/index.html

vijayan121 1,152 Posting Virtuoso

Place a #pragma warning(disable:4244) directive right at the top of the translation unit.

If you are using an earlier version of Microsoft C++, you could alternatively just turn off the (now deprecated) 64-bit portability warnings (/Wp64).

vijayan121 1,152 Posting Virtuoso

> conversion from 'std::streamsize' to 'size_t', possible loss of data

Unless you are using files larger than 4GB in size on a 32-bit platform, you can safely ignore this warning.

vijayan121 1,152 Posting Virtuoso
//while(!str_number.eof())
//     {
//     str_number >> str_description;
//     ...

while( str_number >> str_description ) // while attempt to extract a string has succeeded 
     {
       ...
vijayan121 1,152 Posting Virtuoso
void Manufacturer::WhatIsYourTeam()
{
    // ...
}
vijayan121 1,152 Posting Virtuoso

> its only when the vector get reallocated in memory (due to another thread loading a different sample into it)

The memory buffer held by the vector could get reallocated.

You need to synchronize access to the vector across multiple threads.

vijayan121 1,152 Posting Virtuoso
// ...
for (i=0; i<10; i++)
     {
         if (nums[i]== k)
         {
           temp=1;
           pos=i;
         }
      }
     if (temp==1) 
		 cout << "first occurrence : " << pos << " ";
	 else
		 cout << "first occurrence : " << "-1" << " ";

This fragment finds the last occurrence if any.

To locate the first occurrence, you need to break out of the loop once k has been found.

vijayan121 1,152 Posting Virtuoso

Pete Becker's 'The C++ Standard Library Extensions: A Tutorial and Reference' has been available for some time.
http://www.amazon.com/Standard-Library-Extensions-Tutorial-Reference/dp/0321412990/ref=sr_1_1?s=books&ie=UTF8&qid=1313201008&sr=1-1

'C++ Concurrency in Action' by Anthony Williams has in-depth coverage of concurrency features in C++11.
http://www.manning.com/williams/

Scott Meyers' presentation materials on C++11 is also a useful resource.
http://www.artima.com/shop/overview_of_the_new_cpp

InformIT has a series of articles on C++0x by Danny Kalev; for example:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=254

jonsca commented: Good info, too +14
Chilton commented: Hey. Thanks a lot for the help. +3
vijayan121 1,152 Posting Virtuoso

In the boost distribution: <directoy_where_boost_has_been_unpacked>/boost_1_47_0/doc/html PDF documentation can be downloaded from sourceforge: http://sourceforge.net/projects/boost/files/boost-docs/1.47.0/


Or use wget. Something like:
> wget --mirror -p --no-parent --convert-links -P ./boostdoc http://www.boost.org/doc/libs/1_47_0/libs/libraries.htm


Note: 1_47_0 is boost version 1.47.0. Use 1_46_1 for 1.46.1 and so on.

vijayan121 1,152 Posting Virtuoso

factorial *= (i-1) * i would make the entire factorial zero (or very close to zero) when i == 1.
One way out of this is to start with i == 3.

In each term of the expansion, the numerator can be computed by multiplying the previous term by x*x.
That is, x^9 == x^7 * x*x. This could be more efficient than calling std::pow() every time.

If you want to avoid the if statement, use an int variable to hold the sign: +1 if positive and -1 if negative.

You might also want to check that x does not exceed 2 * PI (the sweep of the angle across a full circle).

// ...
    double xPower = x ;
    double factorial = 1 ;
    double sineComputed = x ;
    int sign = 1 ;

    for( int i=3; i<=n; i+=2 )
    {
        sign = -sign ;
        xPower *=  x*x ;
        factorial *= i * (i-1);
        sineComputed += xPower/factorial * sign ;
    }
// ...
vijayan121 1,152 Posting Virtuoso

> Point taken, but realize that I'm no Windows programmer
> so that format was, to me, associated with product keys.

uuids are not a Windows innovation; they conform to the standard originally specified by OSF/DCE and now in ISO/IEC 11578:1996. Windows uses uuids; but so do several other systems - Linux ext2/ext3 file systems, Mac OS X, GNOME, KDE, J2SE among others.

For example, using libuuid:

#include <string>
#include <uuid/uuid.h>

std::string rand_uuid_string() // link with -luuid
{
    uuid_t uuid ;
    uuid_generate_random( uuid ) ;
    char temp[64] ;
    uuid_unparse( uuid, temp ) ;
    return temp ;
}

The current release of boost has a portable implementation:

#include <boost/uuid/random_generator.hpp>
#include <string>

std::string rand_uuid_string() 
{
    static boost::uuids::random_generator generator ;
    return generator().to_string() ;
}
vijayan121 1,152 Posting Virtuoso

A more general version of NathanOliver's idea; somewhat academic, and using the boost iterator library.

#include <iterator>
#include <type_traits>
#include <locale>
#include <functional>
#include <boost/iterator/filter_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <algorithm>
#include <string>
#include <iostream>
#include <list>

namespace
{
  template < typename ITERATOR, typename FILTER, typename TRANSFORM >
  bool _is_palindorome( ITERATOR begin, ITERATOR end, FILTER filter,
                         TRANSFORM transform, std::random_access_iterator_tag )
  {
    const auto N = ( end - begin ) / 2 ;
    std::reverse_iterator<ITERATOR> rbegin(end), rend(begin) ;

    using namespace boost ;
    return std::equal(
      make_transform_iterator( make_filter_iterator(filter,begin,end-N), transform ),
      make_transform_iterator( make_filter_iterator(filter,end-N,end-N), transform ),
      make_transform_iterator( make_filter_iterator(filter,rbegin,rend-N), transform ) ) ;
  }

  template < typename ITERATOR, typename FILTER, typename TRANSFORM >
  bool _is_palindorome( ITERATOR begin, ITERATOR end, FILTER filter,
                         TRANSFORM transform, std::bidirectional_iterator_tag )
  {
    std::reverse_iterator<ITERATOR> rbegin(end), rend(begin) ;

    using namespace boost ;
    return std::equal(
      make_transform_iterator( make_filter_iterator(filter,begin,end), transform ),
      make_transform_iterator( make_filter_iterator(filter,end,end), transform ),
      make_transform_iterator( make_filter_iterator(filter,rbegin,rend), transform ) ) ;
  }
}

template < typename ITERATOR > bool is_palindorome( ITERATOR begin, ITERATOR end,
                                            const std::locale& locale = std::locale() )
{
    typedef typename std::iterator_traits<ITERATOR>::value_type char_type ;

    static const std::function< bool(char_type) > is_alnum =
                        [locale] ( char_type c ) { return std::isalnum(c,locale) ; } ;

    static const std::function< char_type(char_type) > to_lower =
                        [locale] ( char_type c ) { return std::tolower(c,locale) ; } ;

    return _is_palindorome( begin, end, is_alnum, to_lower,
                      typename std::iterator_traits<ITERATOR>::iterator_category() ) ;
}

int main()
{
    const std::string& str = "This is not a palindrome." ;
    std::cout << std::boolalpha << is_palindorome( str.begin(), str.end() ) << '\n' ;
    std::cout << is_palindorome( str.c_str(), str.c_str()+str.size() ) << '\n' ;
    const std::wstring …
vijayan121 1,152 Posting Virtuoso

If you are going to perform unformatted I/O, open the stream in binary mode (use std::ios_base::binary). Or else, text mode escape sequence translations will take place.

vijayan121 1,152 Posting Virtuoso

> wait what does enable_if return if false?

Repeat: std::enable_if<> proposal was based on boost::enable_if<>, which is explained here: http://drdobbs.com/cpp/184401659

Alternatively, look up section 20.9.7.6 in the FDIS.

vijayan121 1,152 Posting Virtuoso

> Might I ask for an explanation of this line
> typename std::enable_if< std::is_arithmetic<T>::value, T >::type* = 0 Well, the original question was about

Only valid integer should be returned. All other input should be tossed, user should be asked again for valid integer input.

I took the liberty of generalizing that to 'Only valid number should be returned. All other input should be tossed, user should be asked again for valid numeric input.'. Where the number is any numeric (integral or real) type.

So, the template function

template< typename T = int > T number_from_stdin( ... )

should only be available for numeric types. The last parameter to the function is just a place holder with a default value to ensure that T is a numeric type.

An instance of std::is_arthmetic<T> holds true only if the type T is an arithmetic type (either an integral type or a floating point type). std::is_arithmetic<volatile int>::value is true , so an improved version of the function would be:

template< typename T = int >
T number_from_stdin(  const char* prompt = "enter a valid number, then a <newline>: ",
                      const char* emsg = "error: input is not numeric\n",
                      typename std::enable_if< std::is_arithmetic<T>::value, T >::type* = 0  )
{
    std::string str ;
    std::cout << prompt ;
    if( std::getline( std::cin, str ) )
    {
        std::istringstream stm(str) ;
        [B]typename std::remove_cv<T>::type number ;[/B]
        char trailing_crud ;
        if( ( stm >> number ) && !( stm >> std::ws >> trailing_crud ) ) return …
vijayan121 1,152 Posting Virtuoso

> I came with the idear of visit all the column index and matrix values with an iterator. such as
> for(iter=begin(ith row); iter!=end(ith row); iter++) cout<<*iter;
> the overloaded * to give the matrix value.

As long as the keys in the map are ordered row by row in ascending order, and within each row, col by col in ascending order, you can base your iterator on the map's iterator. Just use std::map<>::lower_bound() and std::map<>::upper_bound() to get begin and end for a particular row.

struct sparse_matrix_2d
{
    // ...

    struct index
    {
        index( std::size_t r, std::size_t c ) : row(r), col(c) {}
        const std::size_t row ;
        const std::size_t col ;
        bool operator< ( const index& that ) const
        {
          if( row < that.row ) return true ;
          else if( row == that.row ) return col < that.col ;
          else return false ;
        }
    };

    typedef std::map< index, double > map_t ;
    struct row_iterator : std::iterator< std::forward_iterator_tag, double >
    {
        explicit row_iterator( map_t::iterator i ) : iter(i) {}

        double& operator* () { return iter->second ; }

        row_iterator& operator++() { ++iter ; return *this ; }
        row_iterator operator++(int)
        { row_iterator before_increment(*this) ; ++iter ; return before_increment ; }

        bool operator== ( const row_iterator& that ) const
        { return iter == that.iter ; }
        bool operator!= ( const row_iterator& that ) const
        { return iter != that.iter ; }

        private:
            map_t::iterator iter ;
    };

    row_iterator row_begin( std::size_t row_num )
    { return row_iterator( non_zero_elements.lower_bound( index(row_num,0) ) ) ; } …
vijayan121 1,152 Posting Virtuoso

<already answered, deleted>

vijayan121 1,152 Posting Virtuoso
[B]>[/B] int number;
[B]>[/B] stm >> number;
[B]>[/B] while( stm.fail() ) ....

This kind of construct fails to check for crud remaining in the input; 567#$! would be treated as a valid number with a value of 567.

If the attempt to read a non-ws char after reading the number is successful, there was some crud left in the input line.

#include <type_traits>
#include <iostream>
#include <sstream>

template< typename T = int >
T number_from_stdin(  const char* prompt = "enter a valid number, then a <newline>: ",
                      const char* emsg = "error: input is not numeric\n",
                      typename std::enable_if< std::is_arithmetic<T>::value, T >::type* = 0  )
{
    std::string str ;
    std::cout << prompt ;
    if( std::getline( std::cin, str ) )
    {
        std::istringstream stm(str) ;
        T number ;
        char trailing_crud ;
        if( ( stm >> number ) && !( stm >> std::ws >> trailing_crud ) ) return number ;
    }
    std::cerr << emsg ;
    return number_from_stdin<T>( prompt, emsg ) ;
}
vijayan121 1,152 Posting Virtuoso

> class Mesh" by using "verctor< vector<int> >" structure.
> But how transfer this row-column matrix in the " class Mesh" to the "class CoordMatrix".

This is one way of doing it.

1. Declare mesh to be a friend of the earlier sparse_matrix_2d .

2. In class mesh:
a. define a constructor that can initialize a mesh from a sparse_matrix_2d .
b. define a function that can populate a sparse_matrix_2d with the data in the mesh .

Code only for expositional purpose:

struct sparse_matrix_2d
{
    // other sparse_matrix_2d stuff
    
    friend struct mesh ;
};

struct mesh
{
    struct mesh_element
    {
        mesh_element( std::size_t c, double v ) : column(c), value(v) {}
        std::size_t column ;
        double value ;
    };

    std::size_t ncols ;
    std::vector< std::vector<mesh_element> > mesh_data ;

    explicit mesh( const sparse_matrix_2d& mtx ) : ncols(mtx.ncols), mesh_data(mtx.nrows)
    {
         const sparse_matrix_2d::map_t& non_zero_elements = mtx.non_zero_elements ;
         typedef sparse_matrix_2d::map_t::const_iterator iterator ;
         iterator end = non_zero_elements.end() ;
         for( iterator iter = non_zero_elements.begin() ; iter != end ; ++iter )
            mesh_data[ iter->first.row ].push_back(
                                        mesh_element( iter->first.col, iter->second ) ) ;

    }

    sparse_matrix_2d& populate( sparse_matrix_2d& mtx )
    {
        mtx.non_zero_elements.clear() ;
        mtx.nrows = mesh_data.size() ;
        mtx.ncols = ncols ;

        for( std::size_t r = 0 ; r < mesh_data.size() ; ++r )
            for( std::size_t c = 0 ; c < mesh_data[r].size() ; ++c )
               mtx.non_zero_elements[ sparse_matrix_2d::index(r,c) ] = mesh_data[r][c].value ;

        return mtx ;
    }

    // other mesh operations
};
vijayan121 1,152 Posting Virtuoso

The architecture is fairly straightforward.

The stream class (in case of std::cout , std::ostream ) is responsible for parsing and formatting the sequence of characters required for output.

The stream buffer object associated with the stream provides an abstract connection to some external device; the stream buffer is responsible for transport of characters to ( from for input) this external device, and buffering of these characters in an internal buffer.

For example in,

#include <iostream>
#include <iomanip>
#include <fstream>

int main()
{
    int i = 1234 ;
    double d = 123456.789 ;
    bool flag = i > 100 ;
    std::cout << std::fixed << std::setprecision(2) << std::boolalpha ;

    std::cout << "to stdout: " << i << ' ' << d << ' ' << flag << '\n' << std::flush ;

    std::filebuf stmbuf ;
    stmbuf.open( "out.txt", std::ios::out ) ;
    std::streambuf* old_buf = std::cout.rdbuf( &stmbuf ) ;
    std::cout << "to file: " << i << ' ' << d << ' ' << flag << '\n' << std::flush ;

    std::cout.rdbuf( old_buf ) ;
    std::cout << "back to stdout: " << i << ' ' << d << ' ' << flag << '\n' ;
}

std::cout formats the output (converts objects int, double etc. to a sequence of chars). The streambuf sends these chars to the external device as required (eg. a std::filebuf sends it to a file).

See: http://www.angelikalanger.com/IOStreams/Excerpt/excerpt.htm
And for more detailed information on the architecture, read the book.

vijayan121 1,152 Posting Virtuoso

> "non_zero_elements[ index(row,col) ]", the index(row, col) use the structure name index directly.
> why it works? I think we should creat a new instance like
> " index aIndex(row,col), and then "non_zero_elements[ AIndex(row,col) ]".

See: http://people.cs.vt.edu/~kafura/cs2704/anonymous.html


> How to identify the column numbers in the i'th row,
> i tried to use find algorithm, but it can only return one values?
> Does STL has this kind of algorithm to perfrom this task.

There is no standard algorithm which will do this. But it is quite easy to write a function that would do the job.

If the keys in the map are ordered by the predicate bool operator< ( const index& that ) const given earlier:
that is row by row in ascending order, and within each row, col by col in in ascending order, then:

// returns all column numbers in the i'th row
std::vector<std::size_t> sparse_matrix_2d::column_numbers( std::size_t i ) const
{
    typedef std::map< index, double >::const_iterator iterator ;
    iterator begin = non_zero_elements.lower_bound( index( i, 0 ) ) ;
    iterator end = non_zero_elements.upper_bound( index( i, ncols ) ) ;

    std::vector<std::size_t> col_numbers ;
    for( ; begin != end ; ++begin ) col_numbers.push_back( begin->first.col ) ;

    return col_numbers ;
}
vijayan121 1,152 Posting Virtuoso

> Since Cout<<MA(2,2) is a right operation, why it do not use the const version?

When a non-static member function is overloaded on the cv qualifiers, the function is being overloaded on the type of the this pointer (which is an implicit parameter to the function). CoordMatrix* gives an exact match for the this pointer for the non-const overload; the const overload requires a conversion from CoordMatrix* to const CoordMatrix* . Normal overload resolution applies and the overload resolves to the one with an exact match.

There is an elementary error in one of the functions I posted earlier; you should be able to figure out what is missing on your on.

// ...
    void at( std::size_t row, std::size_t col, double value )
    {
        if( (row>=nrows) || (col>=ncols) ) throw std::out_of_range("invalid index") ;
        else if( is_non_zero(value) ) non_zero_elements[ index(row,col) ] = value ;
        // TODO: what is being missed here?
    }
    // ...
vijayan121 1,152 Posting Virtuoso

Use a library, perhaps?

zlib is the library of choice - open source with a non-viral license, proven, reliable and portable.
http://www.zlib.net/

You might want to use a C++ wrapper for zlib. Very many are available; for example
http://code.google.com/p/zipstream/
http://www.cs.unc.edu/Research/compgeom/gzstream/

vijayan121 1,152 Posting Virtuoso

> I wrote a spare Matrix class and the Matrix was stored in a coornidate format.

Consider using a data structure that would allow efficient look up of the element at a given row and col position. One way is to use a std::map<> where the (row,col) tuple is the key.


> if( *(aVal[i]+j) != 0.0 ) This check for a floating point value being non-zero may not give you the results that you anticipate.
See: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17


> I want to constructe a CoordMatrix from a 2d array

There is no "standard" 2d array in C or C++. There are a variety of ways of simulating it. So the answer is: it depends. In every case, information about the number of rows and cols would have to be passed to a function/constructor.
For more information: http://forums.devx.com/showthread.php?p=519222

If the array has a static storage duration, the number of elements are constants known at compile time and we could do it this way (assuming a std::map<> implementation of the sparse 2d matrix):

#include <iostream>
#include <cmath>
#include <map>
#include <stdexcept>
#include <iomanip>

struct sparse_matrix_2d
{
    struct index ;

    template< std::size_t ROWS, std::size_t COLS >
        explicit inline sparse_matrix_2d( double (&array)[ROWS][COLS] )
            : nrows(ROWS), ncols(COLS)
        {
            for( std::size_t i = 0 ; i < ROWS ; ++i )
                for( std::size_t j = 0 ; j < COLS ; ++j )
                    if( is_non_zero( array[i][j] ) )
                        non_zero_elements[index(i,j)] = array[i][j] …
vijayan121 1,152 Posting Virtuoso

Straddling compile-time techniques and run-time techniques requires a fair amount of care. The code tends to be fairly stylized.

For this paricular example:

#include <iostream>
#include <boost/any.hpp>
#include <vector>
#include <boost/mpl/list.hpp>
#include <boost/mpl/for_each.hpp>
using namespace boost ;

struct triangle
{
    void draw() const // polymorphic across many different types 
    { std::cout << "triangle {sides:" << a << ',' << b << ',' << c << "}\n" ; }
    int a, b, c ;
} ;

struct rectangle
{
    void draw() const
    { std::cout << "rectangle {widthxheight:" << width << 'x' << height << "}\n" ; }
    int width, height ;
} ;
struct circle
{
    void draw() const { std::cout << "circle {radius:" << radius << "}\n" ; }
    int radius ;
} ;

struct draw_it
{
    explicit draw_it( const any& a ) : object(a) {}

    template< typename T > void operator() (T) const
    {
        // the argument (which is ignored) is just a place holder; a null pointer to T
        try { any_cast<T>(object)->draw() ; throw drew_it() ; }
        catch( const bad_any_cast& ) {}
    }

    struct drew_it {} ;

    private:  const any& object ; // has a pointer to the actual object to be drawn
} ;

template< typename TYPELIST, typename ITERATOR >
void draw_all( ITERATOR begin, ITERATOR end )
{
    for( ; begin != end ; ++begin )
    {
        try
        {
            mpl::for_each<TYPELIST>( draw_it(*begin) ) ;
            std::cerr << "I don't know how to draw this object\n" ;
        }
        catch( const draw_it::drew_it& ) { /* ok */ }
    } …
mrnutty commented: Another good post +13
alwaysLearning0 commented: liked it. +4
vijayan121 1,152 Posting Virtuoso

The K-means clustering algorithm computes yields K clusters, where K is given by you. You have to "tell" the algorithm beforehand how many clusters the data set should be broken up into.

A hierarchical clustering algorithm on the other hand forms successive groupings, with the number of clusters varying from from 1 to N (where N is the cardinality of the data set). Hierarchical clustering lets you choose which of the N steps gives you the most convenient number of clusters for your analysis. Ward's algorithm is a commonly used agglomerative hierarchical clustering algorithm. http://iv.slis.indiana.edu/sw/ward.html

Different clustering methods have different strengths and weaknesses. Which algorithm to use, choosing the distance metric which is most appropriate, and determining the number of clusters to specify for K-means clustering or select from hierarchical clustering are interesting problems. Discriminant function analysis is typically used for these quality measures.

Jsplinter commented: Interesting... more food for thought to digest. Thank you! +2
vijayan121 1,152 Posting Virtuoso

list is a typedef (an alias for) a pointer to a nodo_lista. typedef struct nodo_lista *list; If struct nodo_lista does have a member function insert_list(), then: (i)->primerapos[B]->[/B]insert_list(&primerapos, contador_etiquetas);

vijayan121 1,152 Posting Virtuoso

Though the standard does not say anything specific about the representation of a wchar_t, it is either strictly Unicode (UCS-2) or ISO 10646 (UCS-4) on every implementation. These two have an identical character repertoire and code points for the Basic Multilingual Plane. In practice, this will remove non-printable characters from a string.

void remove_non_printable_chars( std::wstring& wstr )
{
    // get the ctype facet for wchar_t (Unicode code points in pactice)
    typedef std::ctype< wchar_t > ctype ;
    const ctype& ct = std::use_facet<ctype>( std::locale() ) ;

    // remove non printable Unicode characters
    wstr.erase( std::remove_if( wstr.begin(), wstr.end(),
                    [&ct]( wchar_t ch ) { return !ct.is( ctype::print, ch ) ; } ),
                wstr.end() ) ;
}

Incidentally, U+0020 is a printable Unicode character.

mrnutty commented: man you know too much +13
vijayan121 1,152 Posting Virtuoso

> I know I could try getline(cin, FullName), then split it them all
> but the text did not recommend this and suggesting 3 string variables

This would be one way of doing it:

std::string FirstName, LastName ;
	std::cout << "What is your first and last name? " ;

	if( std::cin >> FirstName >> LastName >> std::skipws )
        {
            std::string MiddleName ;
	    std::cout << "What is your middle name? "
                         "enter EOF (Posix CTRL+D, Microsoft CTRL+Z) if none: " ;
	    std::cin >> MiddleName ;

            std::cout << '\n' << LastName << ", " << FirstName ;
            if( !MiddleName.empty() ) std::cout << ' ' << MiddleName ;
	    std::cout << ".\n" ;
        }
vijayan121 1,152 Posting Virtuoso

> tokenize a string, yet allow it to leave the whitespaces as token also.

Construct a boost::char_separator<char> with white spaces as the kept delimiters (an an empty string for dropped delimiters). Tokenize with a tokenizer using this as the tokenizer function. For example:

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

int main()
{
   std::string str = "This is,  a test";

   typedef boost::tokenizer< boost::char_separator<char> > tokenizer_type ;

   const char* const dropped_delimiters = "" ; // nothing
   const char* const kept_delimiters = " \t" ; // space, tab
   boost::char_separator<char> separator( dropped_delimiters, kept_delimiters ) ;

   tokenizer_type toker( str, separator ) ;

   int cnt = 0 ;
   for( tokenizer_type::iterator beg = toker.begin() ; beg != toker.end(); ++beg )
       std::cout << "token " << ++cnt << ": '" << *beg << "'\n";
}
vijayan121 1,152 Posting Virtuoso

> even if i had to print 10^100, how would i do about doing it?
> store in an array upto a limit of a long and then another long variable?

It would be simpler to store each digit separately in an array or vector.


> but i think i'm gonna pass out on completing this problem.
> actually i implemented the algo on the wiki, from the first link.
> but it didn't print anything

I think you are giving up far too soon. Programming in general is not particularly difficult, though it would appear so to someone starting out.

For example, the algorithm given in wiki is quite easy to implement once you work out how to keep track of the digits of a large integer (bigger than what an int can hold).

#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>

// based on sieve of sundaram (naive implementation)
std::vector<int> generate_primes_not_divisible_by_10( int N )
{
    const int M = N / 2 ;
    std::vector<bool> sieve( M, true ) ;
    for( int i = 1 ; i < M ; ++i )
    {
        const int L = (M-i) / ( 2*i + 1 ) ;
        for( int j = i ; j <= L ; ++j )
            sieve[ i + j + 2*i*j ] = false ;
    }

    std::vector<int> primes ;
    primes.push_back(3) ;
    primes.push_back(7) ;
    // ignore 2 and 5; now add 11 upwards:
    for( int i = 5 …
vijayan121 1,152 Posting Virtuoso

To get a random int between 0 and 31 (inclusive) using rand(), prefer something like int( 32.0 * ( rand() / (RAND_MAX+1.0) ) ) ; Or else, you would be assuming that the least significant 5 bits of the pseudo random number generated by rand() are also randomly distributed.

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
string parseInputString( const string& oneline ) // prefer passing by const referance
{
    // when possible, initialize objects at the point of their definition
    string::size_type index = oneline.find (' ') ;
    string firstName = oneline.substr( 0, index ) ;

    // find the next non-space character
    index = oneline.find_first_not_of( ' ', index ) ;

    string lastName ;
    if( index != string::npos ) // if there is something after the spaces
        lastName = oneline.substr( index ) ; // lastName is everything from there on

    return lastName + ", " + firstName + "." ;

}
vijayan121 1,152 Posting Virtuoso

The base class with virtual functions (student) must have a virtual destructor.

Add an extra pure virtual function in the base class to handle stream output.

Override that function in derived classes to do class specific stream output.

Write a single overloaded operator for the base class to insert an object into a stream. As the object is passed by (const) reference, call to the virtual function will yield polymorphic stream output.

class student
{
    public:
        // a virtual destructor is required
        virtual ~student() {}

        // other virtual functions
        // virtual ... = 0 ;
        // etc.

        // add a virtual function to print to a stream
        virtual std::ostream& print( std::ostream& stm ) const = 0 ;
};

inline std::ostream& operator<< ( std::ostream& stm, const student& s )
{ return s.print(stm) ; } // print is dynamically dispatched  

class phy_student : public student
{
    std::ostream& print( std::ostream& stm ) const
    {
        // print out phy_student stuff
        // stm << ...
        return stm ;
    }

    // override other virtual functions

    // ...
};

> Do you need to have a virtual function in the base class for all functions that are in derived classes?

No.

> My understanding of virtual functions is that since a base class pointer only points to the "base" part of a derived object, they are necessary to tell the compiler to look for the most derived version of a function.

Yes.

> can you have a base class …

vijayan121 1,152 Posting Virtuoso

Have you overloaded the operator for the base class? That is, do you have std::ostream & phy_namespace::operator<<( std::ostream &cout, const student& student); Also, do you know what virtual functions are?

vijayan121 1,152 Posting Virtuoso

Some kind of a radix tree (a patricia trie is commonly used).

vijayan121 1,152 Posting Virtuoso
v.assign( 1U, 4 ) ; // usually more efficient than create temporary vector and then swap
v = { 4 } ; // only in C++ 2011
vijayan121 1,152 Posting Virtuoso
typedef A::B B ;

// ...
Jsplinter commented: thanks +2
vijayan121 1,152 Posting Virtuoso

Something like this:

name = fName + ":" + lName;
        
        // find the first free position
        int free_pos = -1 ;
	for(int i = 0; i < size; i++) 
            if( nameList[i].length() == 0 ) 
            {
                free_pos = i ;
                break ;
            }
        
        if( free_pos != -1 ) nameList[free_pos] = name ; 
        else cout << "Namnlistan är full\n" ;
vijayan121 1,152 Posting Virtuoso

Use boost::filter_iterator, perhaps.
http://www.boost.org/doc/libs/1_46_0/libs/iterator/doc/filter_iterator.html

A trivial example:

#include <vector>
#include <algorithm>
#include <boost/iterator/filter_iterator.hpp>
#include <iostream>

int main()
{
    std::vector<int> seq = { 36, 4, 63, 21, 41, 64, 0, 35, 4, 17, 8, 33 } ;
    auto is_odd = [] ( int i ) { return i%2 != 0 ; } ;
    auto odd_begin = boost::make_filter_iterator( is_odd, seq.begin(), seq.end() ) ;
    auto odd_end = boost::make_filter_iterator( is_odd, seq.end(), seq.end() ) ;
    std::cout << "min_odd_element: " << *std::min_element( odd_begin, odd_end ) << '\n' ;
}
fandango commented: Always good to learn something new! +1
vijayan121 1,152 Posting Virtuoso

Use std::move to convert the lvalue reference to an rvalue reference.
see: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2027.html#Move_Semantics

> Maybe this? testPF(std::move(a), std::move(b) ) ; Yes.

vijayan121 1,152 Posting Virtuoso

> dereferencing type-punned pointer will break strict-aliasing rules
> Should I care about the warning message?

If you get this warning in your own code, you should certainly care about it. This means that aliasing rules as specified in 3.10/15 of IS have been violated resulting in undefined behaviour. See http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html

In this particular case, you can safely ignore the warning; it arises because of a known bug resulting from the interaction of boost::bind/boost::function/g++ 4.5. This has been known for a while, and AFAIK, has been now fixed.
See: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=44164
and: https://svn.boost.org/trac/boost/ticket/4538

I would still think that writing this code with C++0x lambdas and type inference is easier:

#include <iostream>

template < typename T > T foobar( T a, T b ) { return a+b ; }

template < typename T > T foobar( T a, T& b, T c ) { return b = a-b+c ; }

template< typename FUNCTION, typename T >
auto call_it( FUNCTION f, T t ) -> decltype ( f(t) ) { return f(t) ; }

int main()
{
    auto fun = [] ( int a ) { return foobar(a,23) ; } ; // 23 is bound as arg 2
    std::cout << call_it( fun, 99 ) << '\n' ;
}

I agree that this would work only with newer compilers eg. g++ 4.5 or 4.6, microsoft VC++ 2010
boost::bind/boost::function would work on most older compilers too. C++0x is currently at FCD …

vijayan121 1,152 Posting Virtuoso

> when things mess up with template
> It can't work as the way you show me

You need to disambiguate the overload. As long as you do that, it would work - templates or no templates.

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <functional>

template < typename T > T foobar( T a, T b ) { return a+b ; }

template < typename T > T foobar( T a, T& b, T c ) { return b = a-b+c ; }

int main()
{
    // disabiguate the overloaded functions for boost::bind
    int (&int_foobar)(int,int) = foobar ;
    double (&dbl_foobar)(double,double&,double) = foobar ;

    boost::function< int(int) > f1 = boost::bind( int_foobar, _1, 23 ) ;
    std::cout << f1(99) << '\n' ;

    double b = 56.2 ;
    boost::function< double(double,double) > f2 =
                        boost::bind( dbl_foobar, _1, boost::ref(b), _2 ) ;
    std::cout << f2( 17.4, 23.9 ) << ' ' << b << '\n' ;

    // same disambiguation is also needed for C++0x std::bind
    std::function< int(int) > f3 = std::bind( int_foobar, std::placeholders::_1, 23 ) ;
    std::cout << f3(99) << '\n' ;

    b = 56.2 ;
    // but in C++0x using a lambda function instead is so much easier
    auto f4 = [&b] ( const double a, const double c ) { return foobar(a,b,c) ; } ;
    std::cout << f4( 17.4, 23.9 ) << ' ' << b <<  '\n' ;
}

> The most easiest way for me now is changing the name of the function

Using lambda functions (with …