vijayan121 1,152 Posting Virtuoso

I'm not sure what you mean

While building the DLL and the exe, for both use the same shared (DLL) version of the C/C++ runtime library.
http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx

vijayan121 1,152 Posting Virtuoso

You need to link both the DLL and the exe to the same instance of the run-time library.

Ie. link both with the shared version of the standard library: either /MDd (Debug) or /MD (Release)

vijayan121 1,152 Posting Virtuoso

where can i put thes code?

Anywhere. For instance, you could call the function split_into_ws_separated_columns() from main()

int main()
{
    std::ifstream file( "d:\\h1.txt" ) ;
    std::string line ;
    while( std::getline( file, line ) )
    {
       std::cout << "line: " << line << '\n' ;
       std::vector< std::string > cols = split_into_ws_separated_columns(line) ;
       for( std::size_t i = 0 ; i < cols.size() ; ++i )
        std::cout << "\tcolumn #" << i << ": " << cols[i] << '\n' ;
    }
}
vijayan121 1,152 Posting Virtuoso

How to print a sentence (including white spaces) from a file ?
Or How to print entire text file which has a paragraph?

Assunming that you have a compiler that is not antique:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::string filename ;
    std::cout << "file mame? " && std::cin >> filename ;
    std::ifstream file( filename.c_str() ) ;
    std::cout << file.rdbuf() ;
}
Daniel BE commented: I'm using Turbo C 4.5 +0
vijayan121 1,152 Posting Virtuoso

Split the line using a std::istringstream ?

#include <vector>
#include <string>
#include <sstream>

std::vector< std::string > split_into_ws_separated_columns( 
                                      const std::string& line_from_file )
{
    std::vector< std::string > columns ;
    std::istringstream stm(line_from_file) ;
    std::string col ;
    while( stm >> col ) columns.push_back(col) ;
    return columns ;
}
L7Sqr commented: Much cleaner approach. +8
vijayan121 1,152 Posting Virtuoso

Let us say we have a function:

// return a string with all occurrences of substr in str replaced with replacement  
std::string replace_all( const std::string& str, const std::string& substr, 
                         const std::string& replacement ) ;

This function can be called with many different input sets (each set being a tuple of three strings). A specific invocation of the function with a given input set is an instance. To analyuse its time and space complexity, we need to consider what happens as the size of data increases - what are the characteristics of the input data set which will affect performance? An instance characteristic is a (typically numeric) measure of the proiperties of the input data that has a bearing on performance.

In the above example, the instance characteristics would be
N - the length of str
K - the length of substr
L - the length of replacement

We would aim to estimate performance of the function as time(N,K,L) or space(N,K,L)

vijayan121 1,152 Posting Virtuoso

The Nuwen build of MinGW includes a number of pre-built libraries; libjpeg-8d is one of them. http://nuwen.net/mingw.html

Nuwen MinGW is distributed as a single self-extracting archive and can be installed from the command line.

vijayan121 1,152 Posting Virtuoso

I am facing problem using float
in loop its value stuck at 8388608.00

First read up a bit on the representation of floating point numbers and loss of precision.
http://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html

Then, try out this program:

#include <limits>
#include <iostream>
#include <iomanip>

int main()
{
    typedef std::numeric_limits<float> limits ;
    std::cout << "exponent ranges from: " << limits::min_exponent << " to "
              << limits::max_exponent << " binary ie. about "
              << limits::min_exponent10 << " to " << limits::max_exponent10
              << " decimal\nmantissa has " << limits::digits << " binary digits "
              << "ie. about " << limits::digits10 << " decimal digits\n" ;

    const unsigned long long max_mantissa = ( 1U <<  (limits::digits-1) ) - 1 ;
    std::cout << std::fixed << std::setprecision(limits::digits10)
              << "max value of normalised mantissa: " << max_mantissa << '\n' ;

    float big = max_mantissa ;
    float small = 0.1 ;

    float a = big, b = small, c = -a ;
    std::cout << "a == " << a << '\n' ;
    std::cout << "b == " << b << '\n' ;

    std::cout << "a+b == " << a+b << '\n' ;
    std::cout << "a-b == " << a-b << '\n' ;
    std::cout << "a+b+c == " << a+b+c << '\n' ;
    std::cout << "a+c+b == " << a+c+b << '\n' ;
}

Can you explain the output?

This is the output on my implementation:

exponent ranges from: -125 to 128 binary ie. about -37 to 38 decimal
mantissa has 24 …

vijayan121 1,152 Posting Virtuoso

Something like this:

enum { N = 1024*1024*1024 } ; // 1G times
double value = 1.0 / 3.0 ;

double plus_result = 0 ;
for( int i=0 ; i < N ; ++i ) plus_result += value ;

const double multiplies_result = value * N ;

std::cout << std::fixed << std::setprecision( std::numeric_limits< double >::digits10 )
          << "plus_result: " << plus_result << '\n'
          << "multiplies_result: " << multiplies_result << '\n' ;
vijayan121 1,152 Posting Virtuoso

void DeleteRepeats(char array[], int size, int sizeUnique) is not const-correct.
A const-correct version would be:
void DeleteRepeats( const char array[], int size, int sizeUnique )
http://www.cprogramming.com/tutorial/const_correctness.html

http://www.parashift.com/c++-faq-lite/overview-const.html

Also, void DeleteRepeats(char array[], int size, int sizeUnique ) does not return anything to the caller. It is just a function for printing out the unique (non-duplicated) characters in the input array.

For that, you just need to iterate through each char in the input array and then print it out if it is not present at an earlier position in the array. And perhaps the function could have been given a more meaningful name. Something like this would suffice, wouldn't it?

// is char at array[pos] a duplicate? (present at an earlier position in the array)
bool is_duplicate( const char array[], std::size_t pos )
{
    for( std::size_t i = 0 ; i < pos ; ++i )
       if( array[i] == array[pos] ) return true ;

    return false ;
}

// print out each unique char in the array
void print_unique( const char array[], std::size_t size )
{
    for( std::size_t i = 0 ; i < size ; ++i ) // for each position i in the array
        if( !is_duplicate( array, i ) ) // if the char at array[i] is not a duplicate
            std::cout << array[i] ; // print it out
    std::cout << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

Is such a thing possible?

Yes. You would find it easier to solve a bigger problem by breaking it down into a set of smaller problems, each of which is easy to solve. For example:

Problem : return a dynamically allocated array containing unique chars from the input array.

Sub-problem one: check if a char in the array is a duplicate char. Is it present at an earlier position in the array?

// is char at array[pos] a duplicate? (present at an earlier position in the array)
bool is_duplicate( const char array[], std::size_t pos )
{
    for( std::size_t i = 0 ; i < pos ; ++i )
       if( array[i] == array[pos] ) return true ;

    return false ;
}

Sub-problem two: How many unique characters are there in the input array?

// get a count of unique chars in the array
std::size_t count_unique( const char array[], std::size_t size )
{
    std::size_t unique_cnt = 0 ;

    for( std::size_t i = 0 ; i < size ; ++i )
        if( !is_duplicate( array, i ) )  ++unique_cnt ;

    return unique_cnt ;
}

The bigger problem can now be reduced to:
a. Determine the number of unique characters are there in the input array
b. Dynamically allocate an array of that many chars.
c. For each char in the input array, if it is not a duplicate, copy it to the result array

char* array_without_dups( const char array[], std::size_t size, 
                          std::size_t& no_dups_array_size ) …
vijayan121 1,152 Posting Virtuoso
WolfPack commented: Thanks! +11
vijayan121 1,152 Posting Virtuoso

Use a std::istringstream to extract the tokens from the string.
http://www.artima.com/cppsource/streamstrings3.html

#include <iostream>
#include <string>
#include <sstream>
#include <cmath>

inline void error() { std::cerr << "error in input\n" ; }

int main()
{
    std::string input ;
    while( std::cout << "? " && std::getline( std::cin, input ) )
    {
        std::istringstream stm(input) ;
        std::string function_name ;
        if( stm >> function_name )
        {
            if( function_name == "sqrt" )
            {
                double arg ;
                if( stm >> arg ) 
                    std::cout << "sqrt(" << arg << ") == " 
                                         << std::sqrt(arg) << '\n' ;
                else error() ;
            }

            else if( function_name == "pow" )
            {
                double arg1, arg2 ;
                if( stm >> arg1 >> arg2 ) 
                    std::cout << "pow(" << arg1 << ',' << arg2 << ") == "
                              << std::pow(arg1,arg2) << '\n' ;
                else error() ;
            }

            // else if etc ...

            else error() ;
        }
        else error() ;
    }
}
vijayan121 1,152 Posting Virtuoso
  1. the names x, v, f and i can be unambiguously resolved by name look-up; except that f may be the name of a function with two or more unambiguous overloads.

  2. v is either a pointer (other than pointer to possibly cv-qualified void) or an object which has an overloaded subscript operator.

  3. i is of a type trivially or impliciltly convertible to the type of the subscript required by v[]

  4. If x=f(v[i]); does not appear at class scope, f is a free function which can be invoked with one argument (either a unary function or with default values for the other arguments) or a pointer or a reference to a unary function, or a unary function object

  5. If x=f(v[i]); appears at class scope, f may also be a member function callable with one explicit argument.

  6. the result type of v[i] is trivially or impliciltly convertible to the type of the argument required by f

  7. if f is the name of an overloaded function, or an overloaded function call operator, the overload to be called for f(v[i]) can be unambiguosly resolved

  8. x is a non-const lvalue, or an lvalue reference or rvalue reference to a non-const object

  9. x is an object of, or a reference to an object of an assignable type

  10. the result type of f(v[i]) is trivially or impliciltly convertible to the type of an object that can be assigned to x

This is probably not exhaustive; I'd be surprised if there weren't some cases that were missed.

mike_2000_17 commented: good effort! +13
vijayan121 1,152 Posting Virtuoso

Some other options are,

OpenCV:

You could just use OpenCv's Mat class with an OpenCV primitive data type; and then just store 0 or 1 as the values.

cv::Mat matrix4( 100, 60, CV_8U ) ;

Standard C++ library:

    #include <vector>
    #include <bitset>

    // fixed width matrix of bits
    std::vector< std::bitset<100> > matrix(60); // matrix of 1/0 values
    // http://en.cppreference.com/w/cpp/utility/bitset

    // resizeable matrix of bool values
    std::vector< std::vector<bool> > matrix2( 60, std::vector<bool>(100) ) ;

Boost:

#include <vector>
#include <boost/dynamic_bitset.hpp>

// resizeable matrix of bits
std::vector< boost::dynamic_bitset<> > matrix3( 60, boost::dynamic_bitset<>(100) ) ;
// http://www.boost.org/doc/libs/1_51_0/libs/dynamic_bitset/dynamic_bitset.html
vijayan121 1,152 Posting Virtuoso
//////////////////// a.h //////////////////////////

class C ;

class A
{
    public:
        void setInfo(int age, C *ptrToC);
};


//////////////////// b.h //////////////////////////////

#include "a.h"

class B
{
    private:
        A exampleofA;
};


//////////////////// c.h /////////////////////////////////

#include "b.h"

class C
{
    public:
        void randomFunction();
    private:
        A secondexampleofA;
        B exampleofB;
};


/////////////////////// a.cc //////////////////////////

#include "a.h"
#include "c.h"

void A::setInfo( int age, C *ptrToC )
{
    ptrToC->randomFunction(); 
}

Note: #include guards etc. elided for brevity

vijayan121 1,152 Posting Virtuoso

You should not be using a name like _FOO anywhere in your code.

A name like _fOO can be used except in the global unnamed namespace. Just make sure that the character following the leading underscore is a lower case character.

vijayan121 1,152 Posting Virtuoso

If you know where Bjarne has explained this, then say so, because I can't see it.

I suppose it must be there somewhere in his book. Its definitely there on his support site for the book.
http://www.stroustrup.com/Programming/std_lib_facilities.h

vijayan121 1,152 Posting Virtuoso

have also tested the ascii values of the string and they are identical always beginning with 37 120 116(%xt) and ending with 37 0 (% ).

Ending with % null-char is not the same as ending with % space.

// pattern starts with %xt and ends with a % space sequence 
// const std::regex pattern( "%xt(.*?)% " ) ;

// pattern starts with %xt and ends with a % null-char sequence 
const std::regex pattern( "%xt(.*?)%\000" ) ;
vijayan121 1,152 Posting Virtuoso

I'm interested in sorting a standard container called say 'first_container' via another container which has iterators pointing to the first container.

An indirect sort is useful in many situations

  • a sequence is immutable, but we want a sorted view of the sequence
  • we want to access the sequence in two ways - in the original order and in the sorted order
  • a sequence contains objects which are expensive to move around, and we want a sorted view

The options available are:

  • indirect sort with reference_wrappers
  • indirect sort with iterators
  • indirect sort with pointers

The code using reference_wrappers tends to be cleaner than the code using either pointers or iterators.

const std::list<int> seq = { 42, 24, 75, 65, 42, 53, 65, 75, 74, 63, 46, 52, 35 } ;
for( int v : seq ) std::cout << v << ' ' ; std::cout << '\n' ;
// 42 24 75 65 42 53 65 75 74 63 46 52 35

// indirect sort with reference wrappers
std::vector< std::reference_wrapper<const int> > ref_wrappers( seq.begin(), seq.end() ) ;
std::sort( ref_wrappers.begin(), ref_wrappers.end() ) ;
for( const auto& rw : ref_wrappers ) std::cout << rw << ' ' ; std::cout << '\n' ;
// 24 35 42 42 46 52 53 63 65 65 74 75 75

// indirect sort with iterators
using iterator = std::list<int>::const_iterator ;
std::vector<iterator> iters ;
for( auto iter = seq.begin() ; iter != seq.end() ; ++iter ) iters.push_back(iter) ;
std::sort( iters.begin(), iters.end(), …
gerard4143 commented: Nice detailed reply - Thanks +12
vijayan121 1,152 Posting Virtuoso

Couple of points

for(int i=0;i!=x+y+2;++i) ++iter;

If the iterator is a random access iterator (in this case it is, container_Student_info is a std::vector<>), we could just write iter += n ; to advance the iterator by n positions. This would be more efficient.

However, if the iterator is not a random access iterator (which would be the case if container_Student_info was changed to be a std::list<>), we have to increment it n times in a loop.

We can get the best of both worlds with std::advance() which first discovers what kind of iterator is being avanced and then does it in the most appropriate way. http://en.cppreference.com/w/cpp/iterator/advance

I should copy the elements (of the passing students) to the beginning of the vector and then use resize() to remove the unnecessary elements from the end of the vector.

You could do this more elegantly (and also more efficiently) with a classic in-place partitioning algorithm. Start with two iterators, one 'ponting' to the first student and the other 'pointing' to the last student in the vector.

In a loop, while first != last

  • keep incrementing the first iterator till you reach a student who has failed (or last).
  • keep decrementing the last iterator till you reach a student who has passed (or first)
  • swap the two students with a std::iter_swap() http://en.cppreference.com/w/cpp/algorithm/iter_swap

Needless to say, std::partition() is there in <algorithm>
http://en.cppreference.com/w/cpp/algorithm/partition

With it, the code would look like:

container_Student_info extract_fails( …
vijayan121 1,152 Posting Virtuoso

So my question is, why is it crashing?

container_Student_info::iterator iter = students.begin() ;
while(iter!=students.end())
{
        if(fgrade(*iter))
        {
            // ....
        }
        else
        {
            it = students.begin();  
            students.insert(it, *iter) ; // the iterator 'iter' is no longer valid
            // because we have modified (added a new item into) the container  
            // ..
            ++iter ; // this leads to undefined behaviour
        }
        // ...
vijayan121 1,152 Posting Virtuoso

I thought a major point of regex was that it negates the need to iterate throug a string. I was expecting to have an array of matches after a regex was carried out.

You do not need to iterate through a string if all that you want is a full match.
If you want to access each submatch one by one, you need to iterate.

I was expecting to have an array of matches after a regex was carried out.

std::match_results<> returned by std:regex_match() will contain a sequence of submatches if and only if you have subexpression captures in the regex.

expected output
title1%0.0%4%796.0
title2%0.0%4%796.0
output
title1%0.0%4%796.0% %xt%title2%0.0%4%796.0%

std:regex_match() performs a greedy match - it will match as much of the string as possible.

Is it not possible to get an array of matches?

It is. For example:

#include <iostream>
#include <regex>
#include <algorithm> 
#include <vector>
#include <string>

std::vector< std::string> get_submatches( const std::string& str, 
                                          const std::regex& pattern )
{
    std::vector< std::string> submatches ;

    // iterate through the submatches (omitting the full match at position zero)
    std::sregex_token_iterator iter( str.begin(), str.end(), pattern, 1 ), end ;
    for(  ; iter != end ; ++iter ) submatches.push_back( iter->str() ) ;

    return submatches ;
}

std::vector< std::string > extract_words( const std::string& str, const std::regex& re )
{
    std::vector< std::string > result ;

    const std::sregex_iterator begin( str.begin(), str.end(), re ), end ;
    for( auto iter = begin ; iter != end ; …
Suzie999 commented: Superb help here absolutely delighted +0
vijayan121 1,152 Posting Virtuoso

I'd like to use std::tr1::regex

You have int _tmain(int argc, _TCHAR* argv[]); so presumably you are using the Microsoft compiler. If it is a recent version (2010 or later), use std::regex instead.

I was expecting all values between % and %

The regular expression %(.*?)% consumes the terminating %, so regex_search() wont find a starting % when looking for the next match. Since you are do not need captures of sub-matches, using a regex_iterator would perhaps be simpler.

#include <iostream>
#include <regex>
#include <algorithm> 

int main ()
{
    const char str[] = "%xt%how%-1%now%brown%cow%" ;

    // % followed by any character other than % repeated 1 or more times
    std::regex re( "%[^%]+" ) ; 

    // std::end(str)-1 : -1 to omit the terminating null character from the range
    const std::cregex_iterator begin( std::begin(str), std::end(str)-1, re ), end ;
    std::cout << "#matches: " << std::distance(begin,end) << '\n' ;

    int n = 0 ;
    for( auto iter = begin ; iter != end ; ++iter )
        std::cout << "  " << ++n << ". " << iter->str() << "%\n" ;
}

Output:

#matches: 6
  1. %xt%
  2. %how%
  3. %-1%
  4. %now%
  5. %brown%
  6. %cow%
Suzie999 commented: excellent help +2
vijayan121 1,152 Posting Virtuoso

I have a string and in it there is a character I want to remove.
What is the best way to remove it?

Remove char at position pos in string str
str.erase( pos, 1 ) ;
or str.erase( str.begin() + pos ) ;
or str = str.substr(0,pos) + str.substr(pos) ;

Remove the first occurrance of char ch in string str

    auto pos = str.find( ch ) ;
    if( pos != std::string::npos ) str.erase( pos, 1 ) ;

Remove all occurrances of char ch in string str
str.erase( std::remove( str.begin(), str.end(), c ), str.end() ) ;

The line here I don't get is "string:;iterator it;" Because there's something magical happening there. I tried making a variable "it=9", it didn't work.

Apparently you have not been exposed to iterators and algorithms. Essential knowlegde for someone starting out to explore C++.

Perhaps this tutorial would be a good starting point: http://www.mochima.com/tutorials/STL.html

Then lookup the algorithm std::remove() http://www.cplusplus.com/reference/algorithm/remove/
and the string member function std::string::erase() http://www.cplusplus.com/reference/string/string/erase/

vijayan121 1,152 Posting Virtuoso

I think he wants his own program to do this things, he doesn't wants library functions.

He has a choice; and I would let him decide for himself.

I personally tend to agree with this view (Koenig and Moo):

Our approach is possible only because C++, and our understanding of it, has had time to mature. That maturity has let us ignore many of the low-level ideas that were the mainstay of earlier C++ programs and programmers.
The ability to ignore details is characteristic of maturing technologies. For example, early automobiles broke down so often that every driver had to be an amateur mechanic. It would have been foolhardy to go for a drive without knowing how to get back home even if something went wrong. Today's drivers don't need detailed engineering knowledge in order to use a car for transportation. They may wish to learn the engineering details for other reasons, but that's another story entirely.

We define abstraction as selective ignorance--concentrating on the ideas that are relevant to the task at hand, and ignoring everything else--and we think that it is the most important idea in modern programming. The key to writing a successful program is knowing which parts of the problem to take into account, and which parts to ignore. Every programming langauge offers tools for creating useful abstractions, and every successful programmer knows how to use those tools.
http://www.acceleratedcpp.com/details/preface.html

IMNSHO, one doesn't have to first learn to be …

vijayan121 1,152 Posting Virtuoso

while const int may not even be given storage because the compiler may just treat it as if it were a macro by inserting its value wherever it is used.

Yes, an object of type const int need not be stored anywhere.

But then, the same is also true of any object, even modifiable objects.

If we have int m = 23 ; m is an lvalue, and its adress can be taken: int* p = &m ; p will not be equal to the nullptr and p will not compare equal to a pointer to any object other than m; *p will alias m. All these are requirements of a conforming C++ implementatrion. That m should be actually stored somewhere is not.

The semantic descriptions in this International Standard defne a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine.
Foot note: This provision is sometimes called the 'as-if' rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program....

Consequently:

Under the 'as-if' rule an implementation is allowed to store two objects at the same machine address …

vijayan121 1,152 Posting Virtuoso

The point of the exercise is to use list throughout rather than vector.

Yes; the point of the exercise is to understand the difference between using a sequence container like std::vector<> that provides random access to its values and one like std::list<> that does not.

double median( list<double> vec )
{
    typedef list<double>::size_type vec_sz ;
    vec_sz size = vec.size() ;
    if(size==0) throw domain_error("median of an empty list");

    // std::list<> does not provide random access to the values
    // std::list<>::iterator is not a random_access_iterator
    // we can't use std::sort() which requires random acccess iterators
    // http://en.cppreference.com/w/cpp/algorithm/sort
    // instead use the member function list<>::sort
    // http://en.cppreference.com/w/cpp/container/list/sort

    // sort(vec.begin(),vec.end());
    vec.sort() ;

    vec_sz mid=size/2;

    // std::list<> does not provide random access;
    // it does not have a subscript operator
    // we have to iterate linearly using its bidirectional iterator
    // keeping a count of the position and keeping track of the previous value

    /*
    for(list<double>::const_iterator it=vec.begin(); it!=vec.end(); ++it)   // Start of "list" median calculation
        {
            if(it == mid)
            {
                return size%2==0 ? (vec[*it]+vec[*it-1])/2 : vec[*it];
            }
        }
    */

    list<double>::size_type position = 0 ;
    double previous ;
    for( list<double>::iterator iter = vec.begin() ; iter != vec.end() ; ++iter )
    {
        if( position == mid ) return size%2==0 ? ( previous + *iter ) / 2 : *iter ;
        previous = *iter ;
        ++position ;
    }
}

If you have a current (C++11) compiler:

double median( list<double> seq )
{
    auto size = seq.size() ;
    if(size==0) throw …
vijayan121 1,152 Posting Virtuoso

However I am aware of the .h/.cpp model and never bought into it: instead I only use cpp file and I have a master file that include them all in a way (alas manually!)to avoid any circularity of duplication. By using pre-compiled headers (the headers referring to .cpp files) I have not experienced any problem of slow build).

I'm not sure that I clearly understand what you are trying to say. But I'm quite alarmed by what I think you are driving at.

The seperate compilation model is fundamental to any reasonably large C++ software development. And that is founded on the idea of header files specifying the interfaces. This is an old book, written even before the 1998 C++ standard - and its age shows at several places. But I would still consider it mandatory reading for anyone aspiring to be a serious C++ programmer:
http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620
See if you can get your hands on a copy; it would clarify a lot of things that you have asked about.

1) List all the files in a directory that contains the functions definitions required by each function of a specific cpp file, outputing the files and functions.
2) List all the files in a directory that use each function definition of a specific cpp file, outputing the files and functions.

Perhaps you could start by reading:
http://www.ibm.com/developerworks/linux/tutorials/l-gnutex/index.html

4) create a tree to help me view the entire structure …

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

This would suffice:

template< typename T > void foo( const T& t ) ;

template< typename T > void foo( const MyClass<T>& mc ) ;

The partial ordering of templates involved (that is taken into account in the deduction process) would make the second template be preferred over the first for objects of type MyClass<T>.

daviddoria commented: Thanks for several very helpful answers! +12
vijayan121 1,152 Posting Virtuoso

> Is it possible to write a c++ compiler in c++ ?

The first C++ compiler was written in C++. http://www2.research.att.com/~bs/bs_faq.html#bootstrapping

Clang is written in pure C++; with heavy use of C++ facilities (like STL). http://clang.llvm.org/ Pretty well-written code too, IMHO.

mike_2000_17 commented: good to know! +14
vijayan121 1,152 Posting Virtuoso

Build the program from within the CodeBlocks IDE.

Start the command line interpreter (Start Menu -> Run... -> cmd on Windows XP ), switch to the directory which contains the executable (typically <Project Directory>\bin\Debug) and run it from the command prompt.
For example: > test.exe how now brown cow

Srinivas0 commented: clear explanation on command line parameters +2
vijayan121 1,152 Posting Virtuoso

> s this legal? (For example, can I set a GUIComponent as the return of a function and instead return a subclass?)

Yes. For example:

GUIComponent* getComponent() { return new TextLabel( /* ... */ )

is fine, provided TextLabel is a derived class of GUIComponent.


> Why is the compiler complaining?

The compile-time type of the result of the function is a pointer to GUIComponent (though the run-time of the pointed object might be TextLabel). And the compiler cannot see a member-function getFont() in GUIComponent.


> What would work?

A simple way would be to perform a type-safe run-time down-cast to TextLabel and call getFont() on the result of the cast. For example:

GUIComponent* gui_component = guiList[0]->getComponent(1) ;

TextLabel* text_label = dynamic_cast<TextLabel*>(gui_component) ;

if( text_label != nullptr ) 
{
   // use text_label
   auto font = text_label->getFont() ;
   // etc
}
else
{
   // this component is not a TextLabel 
}

See: http://www.bogotobogo.com/cplusplus/dynamic_cast.php

epicbeast9022 commented: Detailed, correct response! +1
vijayan121 1,152 Posting Virtuoso

Enable ISO C++ conformance (eg. --std=c++0x -pedantic) and warning messages (eg. -Wall).

char * s = "hello world";

would have made the compiler emit a diagnostic - something like
"warning: deprecated conversion from string constant to char*".

vijayan121 1,152 Posting Virtuoso

ntdll.dll etc. are system library files; the PDB files for these are required only if you want to debug system library function calls. You can safely ignore these warnings.

You might want to add a line so that the program would wait for an input at the end:

int main()
{
	std::cout << "Hello world!\n";
        std::cin.get() ;
}
vijayan121 1,152 Posting Virtuoso
void foo( boost::asio::ip::tcp::iostream& stm )
{
    std::size_t bytes_available = stm.rdbuf()->available() ;
    // ...

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

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

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

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

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

Something like:

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

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

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

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

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

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

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

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

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

Something like:

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

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

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

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

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

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

The header <vector> already defines

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

and

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

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

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

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

> Is the member variable from the base class renamed?

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

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

#include <iostream>

struct A
{
    int x ;
    int y ;
};

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

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

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

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

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

vijayan121 1,152 Posting Virtuoso

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

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


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

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

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

vijayan121 1,152 Posting Virtuoso

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

vijayan121 1,152 Posting Virtuoso

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

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

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

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

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

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

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

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

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

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

Repeat: Use boost::sregex_iterator, perhaps?

Like this:

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

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

>> Dragon: why don't you just call CreateProcess() in a loop and call it 10 times?

Just listen to the Dragon, and treat everything else as white noise.

This is almost certainly the problem you were asked to solve, but just fantasize for a moment that your program is to run on (an otherwise idling) machine with, say, sixteen processors, and these ten processes need to start running at about the same measurable instant in time. You could do something like this:

enum { N = 10 } ;
char path[] = "<path to executable image>" ;

PROCESS_INFORMATION pi ;
STARTUPINFO si ;
std::memset( &si, 0, sizeof(si) ) ;
si.cb = sizeof(si) ;
std::vector<HANDLE> threads ;

for( int i=0 ; i<N ; ++i )
{
   if( CreateProcess( path, nullptr, nullptr, nullptr, FALSE,
                      CREATE_SUSPENDED, nullptr, nullptr, &si, &pi ) )
   {
       CloseHandle( pi.hProcess ) ;
       threads.push_back( pi.hThread ) ;
   }
   SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL ) ;
   std::for_each( threads.begin(), threads.end(), ::ResumeThread ) ;
   SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_NORMAL ) ;
   // ..

   WaitForMultipleObjects( threads.size(), &threads.front(), TRUE, INFINITE ) ;
   // ...
   std::for_each( threads.begin(), threads.end(), ::CloseHandle ) ;
}
xfbs commented: good job +2
vijayan121 1,152 Posting Virtuoso

Create two index files, perhaps?

keywords.idx for keywords with each line containing: keyword path, [ path... ]
jade aaron_rogers.txt brett_favre.txt calvin_johnson.txt
amethyst jahvid_best.txt mathew_stafford.txt
urgent tom_brady.txt tony_romo.txt
// etc

ordernumbers.idx with each line containing: ordernumber path
10237 aaron_rogers.txt
11384 brett_favre.txt
etc.

On program startup read keywords.idx into a std::map< std::string, std::vector<std::string> >, update it as entries are being made and on shutdown write it back to keywords.idx.

Likewise for ordernumbers.idx with a std::map< std::string, std::string >

Clinton Portis commented: very nice STL implementation +10
vijayan121 1,152 Posting Virtuoso
#include <limits>
#include <iostream>

int main()
{
    std::cout << "does the type double have a representation for positive infinity? "
              << std::boolalpha << std::numeric_limits<double>::has_infinity << '\n' ;

    // if the answer was true, representation of positive infinity.
    const double infinity =  std::numeric_limits<double>::infinity() ;

    // maximum possible [B]finite[/B] value.
    const double max_value = std::numeric_limits<double>::max() ;

    // they are obviously not equal
    std::cout << "is max_value equal to infinity? " << ( max_value == infinity ) << '\n' ;
}