vijayan121 1,152 Posting Virtuoso

The last line is matching, but because it thinks the array size is zero it drops out and states that it doesn't match.

Haven't looked at any of the logic except this:

while(inFile) // the file stream is not yet at eof after the last line has been read
    {
        inFile.getline(inputArray, 8,'\n'); // try to read one past the last line
        // getline fails; and the stream goes an eof state
        // but we proceed as if no error has occurred.
        // ...

The correct idiom to read every line in a stream checks for failure after (not before) attempted input:

    while( inFile.getline(inputArray, 8,'\n') ) // if we have read a line
        {
            // go ahead and do something with the line
            // ...

static const ET CAPACITY = 20; //Size of the array

What happens if you encounter a line that is longer than this?
Is there a compelling reasaon not to use std::string?

Use the standard library - people who say you don't 'learn' C++ by if you use the language library are people who haven't learned C++ yet.
Ignore them for your own good.

vijayan121 1,152 Posting Virtuoso

i need to restrict the user from inputting an integer and string when inputting a char.

Read the input into a string. Verify that the string consists of precisely one non-digit character.

char get_single_nondigit_char()
{
    std::string input ;
    while( std::cout << "enter a single non-digit, non-whitespace char: "
            && std::cin >> input
            && ( input.size() != 1 || std::isdigit(input[0]) ) ) ;
    return input[0] ;
}
vijayan121 1,152 Posting Virtuoso
WolfPack commented: Thanks! +11
vijayan121 1,152 Posting Virtuoso

As far as I can tell, the main reason to declare a data member as const is to remind the user of that class not to change it's value.

A const member variable is an object that is initialized during construction of the object and is never changed after that. The const member is part of the logical state of an object, and this state never changes during the life of an object.

My current solution is to use a pointer to a const object that lives in a more global scope.

This is fine if and only if the above is not true.

For example, let us say that we have a class that represents an object with a persistent external state; and let us assume (without losing generality) that the persistent state is stored in a seperate file for each object. Say, we have a directory in which we have files file<nnnn>.txt where nnnn is a number 0001 to 9999, used as a unique id for each object. In this case, we can assign to everything else except the unique id of the object. (The object identity is maintained by this unique id instead of a referrence or pointer; typical in a distributed object environment).

struct some_object
{
      some_object get_object( /* ... */ int id = -1 ) 
      {
          try{ return some_object( id /* ... */ ) ; } // ok if file exists
          catch(...) { return some_object( /* ... */ ) ; …
vijayan121 1,152 Posting Virtuoso

Do you can show me a non-vector solution.

Hmm.. Thesnippet I posted dores not use vectors; instead it uses C-style null-terminated arrays of char (and dynamically allocated memory). With annotatations:

// input: an array of char terminated by a null-character
// returns: a dynamically allocated array of unique chars in the input
//          terminated by a null-character

char* remove_duplicates_preserve_order( const char* cstr )
{
    // 1. get a count of the number of unique chars in the input array
    // ---------------------------------------------------------------

    bool already_seen[UCHAR_MAX] = { false } ; // to look up already seen chars 
    int cnt_unique = 0 ; // number of unique chars in the string

    // for every char in the input array till we encounter the null-character
    for( const char* p = cstr ; *p ; ++p ) 
    {
        const unsigned char u = *p ;

        // if we have not seen this char earlier, increment cnt_unique 
        // and set already_seen[u] to true
        if( !already_seen[u] ) { already_seen[u] = true ; ++cnt_unique ; }
    }


    // 2. allocate memory for the result (a null-terminated array of chars)
    // --------------------------------------------------------------------

    char* result = new char[ cnt_unique + 1 ] ; // + 1 for the null-termination 
    result[cnt_unique] = 0 ; // null-terminate result


    // 3. copy unique chars in the input array to the result array
    // -----------------------------------------------------------

    // look up table to check if we had alredy copied a char to the result
    bool already_copied[UCHAR_MAX] = { false } ;

    // for every …
WaltP commented: Nooooob, remember? Dynamic memory? C'mon!!! -3
vijayan121 1,152 Posting Virtuoso

but now the problem I am having that it only deletes repeated pairs not all repeats. How can I make it so that it deletes all the repeats in the word?

If you are allowed to have a different order of chars in the result, just sort the original array first and it will remove all the duplicates.

If not, you need a to lookup the duplicated values (perhaps using a set). Something like:

char* remove_duplicates_preserve_order( const char* cstr )
{
    bool already_seen[ std::numeric_limits<unsigned char>::max() + 1 ] = { false } ;
    int cnt_unique = 0 ;
    for( const char* p = cstr ; *p ; ++p )
    {
        const unsigned char u = *p ;
        if( !already_seen[u] ) { already_seen[u] = true ; ++cnt_unique ; }
    }
    char* result = new char[ cnt_unique + 1 ] ;
    result[cnt_unique] = 0 ; // null-terminate

    bool already_copied[ std::numeric_limits<unsigned char>::max() + 1 ] = { false } ;
    for( char* p = result ; *cstr ; ++cstr )
    {
        const unsigned char u = *cstr ;
        if( !already_copied[u] ) { already_copied[u] = true ; *p = *cstr ; ++p ; }
    }

    return result ;
}

If you are allowed to use C++, std::string in conjuction with std::set<> would make the code a lot shorter, and a lot cleaner.

vijayan121 1,152 Posting Virtuoso

Also, I would get the input from the user, and than form a string composed by the name and pet strings.

Yes. Then randomly shuffle the string and pick the first six chars.
Likwwise, for the string containing digits (pick the first two after a shuffle).
Randomly shuffle the eight chars to form the password.
Something like:

std::string text = get_text( "your name" ) ;
std::string numbers = get_date( "your date of birth" ) ; // say yyyymmdd
text += get_text( "your favorite animal" ) ;

std::srand( std::time(nullptr) ) ;
enum { NCHARS = 6, NDIGITS = 2 } ;

std::random_shuffle( text.begin(), text.end() ) ;
std::random_shuffle( numbers.begin(), numbers.end() ) ;

std::string pword = text.substr(0,NCHARS) + numbers.substr(0,NDIGITS) ;

std::random_shuffle( pword.begin(), pword.end() ) ;
vijayan121 1,152 Posting Virtuoso

How long has C++ supported this?

C++ has never supported this. It wasn't supported in 1998 and it still isn't supported today. Variable length array is a C99 feature.

In C++, use std::vector<> if similar functionality is required.
http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm

I am using Dev-CPP 4.9.9.2 with GCC version 3.4.2-20040916-1.

You should switch to a more recent compiler. If you would like to continue using the familiar IDE, Orwell Dev-C++ would be a reasonable replacement:
http://sourceforge.net/projects/orwelldevcpp/

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
#include <cmath>

inline double log_to_base( double value, double base )
{ return std::log(value) / std::log(base) ; }
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

my task is to type 20 integer numbers from 0 to 99 as the input data.
But i have problem for my next task, which is to display prime numbers from the input data.

2, 3, 5 and 7 are prime numbers. If an integer between 8 and 99 is evenly divisible by 2, 3, 5 or 7, it is not a prime number; otherwise it is a prime number.

vijayan121 1,152 Posting Virtuoso

In ArrayList.cpp, do not redefine the type ArrayList That would be a violation of ODR.
http://en.wikipedia.org/wiki/One_Definition_Rule

Instead, #include "ArrayList.h"

I assume the problem is there is no operator != in the Country.h file.

Yes. The problem is that there is no operator != anywhere.

our instructor told us there would be no problems with missing operators in the header files.
Is there anything Else I can do?

Hmm... Perhaps your instructor expects you to define the operator in ArrayList.cpp

namespace
{
    inline bool operator== ( const Country& a, const Country& b ) 
    { return a.getName() == b.getName() ; }

    inline bool operator!= ( const Country& a, const Country& b ) 
    { return !( a==b ) ; }
 }

And Country::getName() should have a const qualifier.

typedef Country Object;

What purpose is this serving?

vijayan121 1,152 Posting Virtuoso

Date.h requires an include guard.
http://en.wikipedia.org/wiki/Include_guard

Either:

////////// date.h ////////////
class Date
{
    // ...
    bool sameMonth( string aMonth, string aMonth2 ) const ; // *** const added
};

//////// date.cpp ///////////
#include "date.h"

bool Date::sameMonth( string aMonth, string aMonth2 ) const // *** note the Date::
{ return aMonth == aMonth2 ; }

Or (better):

////////// date.h ////////////
class Date
{
    // ...
    static bool sameMonth( string aMonth, string aMonth2 ) ; // *** static added
};

//////// date.cpp ///////////
#include "date.h"

bool Date::sameMonth( string aMonth, string aMonth2 )
{ return aMonth == aMonth2 ; }

Consider passing aMonth and aMonth2 by reference to const.
http://stackoverflow.com/questions/270408/is-it-better-in-c-to-pass-by-value-or-pass-by-constant-reference

vijayan121 1,152 Posting Virtuoso

im writing a program that creates a dynamic array then input numbers(not exceeding 100).

Why do you need an array with dynamic storage duration? You know the size of the array at compile time - 100 - and that is not a huge number.

constexpr std::size_t ARRAY_SIZE = 100 ;
int array[ ARRAY_SIZE ] ;

std::size_t count = 0 ; // holds the count of numbers entered. 
// invariant: count <= ARRAY_SIZE

This loop is completely wrong.

    cout << "enter intger values" << endl;
 do{

         for(i= 0; i < size ; i++) // number input
         {          
              cin>>array[i]; 
         }

   }while(x >'/' && x<':');

What will happen if the user enters a number (say 1) which compares less than '/' or 1234567 which compares greater than ':' ?

Instead, something like this:

cout << "enter intger values (enter any non-integer to stop):\n" ;
while( ( count < ARRAY_SIZE ) && ( std::cin >> array[count] ) ) ++count ;
vijayan121 1,152 Posting Virtuoso

In general, prefer to declare a variable closest to its point of use. Local variables should have no more visibility than absolutely required; define them when you need them, and let them go out of scope when you're done with them.

For instance,

for( unsigned int i = 0 ; i < sOList.size() ; ++i )
{
    // code for first loop
}

// ...

for( unsigned int i = 0 ; i < sOList.size() ; ++i )
{
    // code for another loop
}

If you have a current compiler, to iterate through a vector:
for( const SalesOrder& order : sOList ) order.showInfo() ;

And your showInfo() should be:

class SalesOrder
{
       int bidPrice, lots, accountNumber;
    public:
       // ... 
       void showInfo() const ; // you don't need any parameters
       // ...
};

void SalesOrder::showInfo() const
{
       cout << "The bid price is " << bidPrice << "\n" ; // member variable bidPrice
       cout << "The lot size is " << lots << "\n";
       cout << "The account number is " << accountNumber << "\n\n";
}
vijayan121 1,152 Posting Virtuoso

In

string::const_iterator url_beg(string::const_iterator b, string::const_iterator e)
{
    static const string sep = "://";
    // ...    
    return e;
}

the value returned is always e (end). Instead, return an iterator to the begin of the url.
Something like:

string::const_iterator url_beg( std::string::const_iterator b,
                                std::string::const_iterator e )
{
    static const string sep = "://";
    string::const_iterator iter = std::search( b, e, sep.begin(), sep.end() ) ;
    if( iter != e ) while( iter != b && std::isalpha( iter[-1] ) ) --iter ;
    return iter ;
}
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

could use some more help

Have you tried using the procedure outlined in the CodeBlocks wiki?
If you did, what problems have you encountered?

vijayan121 1,152 Posting Virtuoso

std::vector< unsigned > buckets( std::numeric_limits< unsigned char >::max() );
(note the correction to the type of the vector ;)

unsigned does not improve it in any way.

If it is to be a correction, it would have to be:
std::vector< std::string::size_type > buckets( /* ... */ ) ;

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
CBase b;

void func_set(CBase *pb) 
// pb may point to an object which has the dynamic type of some derived class of CBase
{
    b = *pb; // the object *pb may be sliced here
}

See http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c

You probolly can get away with changing line 24 to
&b = pb;

&b is not an lvalue.

vijayan121 1,152 Posting Virtuoso

Note for those facing challenges reading comprewhension:

ravenous said: Nope, sorting is N Log(N), you can do it in N + M...

And I believe that he He can define a char string, and use vectors, maps, numeric_limits, sorts, and all that crap.

Though I must admit that it may not be true of Mr. WaltP; these are and will remain 'crap' for someone who has proclaimed his belief that std::sort() is a 'language extention'.

vijayan121 1,152 Posting Virtuoso

Use std::uninitialized_copy() instead of std::copy()
http://en.cppreference.com/w/cpp/memory/uninitialized_copy

vijayan121 1,152 Posting Virtuoso

The typical C++ approach is to simulate multimethods with multiple dispatch
http://en.wikipedia.org/wiki/Multiple_dispatch

or with the visitor pattern
http://www.codeproject.com/Articles/7360/MultiMethods-in-C-Finding-a-complete-solution

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

sorting is N Log(N), ...

Use a counting sort with std::vector< char > bucket( std::numeric_limits<unsigned char>::max() ) ;
http://en.wikipedia.org/wiki/Counting_sort

O(N) time, O(M) space where M is the range of values a char can hold.

WaltP commented: He can't even define a char string! How the h*** is he going to use vectors, maps, numeric_limits, sorts, and all that crap? Help him, don't flaunt your expertise +0
m4ster_r0shi commented: I don't think vectors, maps, numeric_limits and sorts are crap. +6
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

Are you talking about hashmaps ? Or map in C++ ?

Don't think so. Just about sorting both strings and the determining their set intersection.

char amit[] = "AMITABH BACHCHAN" ;
char rajn[] = "RAJNIKANTH" ;
std::sort( std::begin(amit), std::end(amit)-1 ) ;
std::sort( std::begin(rajn), std::end(rajn)-1 ) ;
std::set_intersection( std::begin(amit), std::end(amit)-1, 
                       std::begin(rajn), std::end(rajn)-1,
                       std::ostreambuf_iterator<char>(std::cout) ) ;
vijayan121 1,152 Posting Virtuoso

Dudes I am newbie to C++ and forums. I thought i was helping that dude.

Fair enough. Perhaps you should have waited till marius2010 demostrated that a genuine attempt to solve the problem was made.

Code snippets are a genuine aid in learning programming - one good snippet is worth a thousand words. There is no reason why you should completely refrain from posting them.

This has always been a forum where the oldies have grown senile and forgotten that they too were once newbies. At least as far as I am concerned, you just tried to help some one, and I for one appreciate that you tried to help.

WaltP commented: helping and doing their homework are two different things. You can help without writing *the* answer. -3
m4ster_r0shi commented: Wise words! +0
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 think its something to do with a certain version of the GNU GCC complier and using MINGW. Works fine in Windows but not in VxWorks:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=13333

"fstream tell/seek bug with DOS-format text files"

seekg() and tellg() on fstream (not stringstream).

vijayan121 1,152 Posting Virtuoso

All this is (conforming) C++:

struct A
{
    // http://www.stroustrup.com/C++11FAQ.html#default
    // http://www.stroustrup.com/C++11FAQ.html#constexpr
    constexpr A() = default ; // x == 0, y == 0

    constexpr explicit A( int x ) : x(x) {} // A::x==x A::y==0

    A( int x, int y )
    {
        A::x = x ;
        this->y = y ;
    }

    private:
        int x = 0 ; // http://www.stroustrup.com/C++11FAQ.html#member-init
        int y = 0 ;
};

struct B
{
    // http://www.stroustrup.com/C++11FAQ.html#delegating-ctor
    constexpr B() : B(0,0,0) {}

    constexpr explicit B( int x ) : B(x,0,0) {}

    constexpr B( int x, int y ) : B( x, y, 0 ) {}

    constexpr B( int x, int y, int z ) : x(x), y(y), z(z) {}

    private:
        int x ;
        int y ;
        int z ;
};

struct C : B
{
    // http://www.stroustrup.com/C++11FAQ.html#inheriting
    using B::B ; // a is initialized with 9 when we use an inherited construtor

    constexpr C( int x, int y, int z, int a ) : B(x,y,z), a(a) {}

    private: int a = 9 ;
};
vijayan121 1,152 Posting Virtuoso

tellg() in my code as the function is not supported on the desired hardware.

What hardware? A std::istringstream holds a std::stringbuf and it does not use anything other than memory allocated with the standard allocator.

Have you tried printing out the result returned by tellg() on the string stream?

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

string::const_reverse_iterator rit = s.rbegin();
This should be outside the loop(just before the loop)

Yes.

And you need not go all the way to end(); upto the middle of the string would suffice.

Which would make the code equivalent to:

bool is_palindrome( const std::string& str )
{ return std::equal( str.begin(), str.begin() + str.size()/2, str.rbegin() ) ; }

http://en.cppreference.com/w/cpp/algorithm/equal

vijayan121 1,152 Posting Virtuoso

resolving _GLHook_wglSwapLayerBuffers by linking to _GLHook_wglSwapLayerBuffers@8

Hmm... Seems to have found a library built with the Microsoft toolchain instead of one built with the GCC toolchain. Shouldn't be a problem unless there is a major version mismatch. Personally, I wouldn't be happy about this, and would still put in the -L<search_for_library_here> linker options.

vijayan121 1,152 Posting Virtuoso

Main part of my project is to capture and parse all incoming and outgoing network traffic on the fly. Do you think that merits a performance concern?

It certainly does. Bursts in network traffic are difficult to predict and difficult to simulate with any kind of accuracy.

Nevertheless, performance is a design constraint, never a design goal.

And it has to be addressed by using high level architectural and algorithmic decisions - for example, in this case, by using techniques like adaptive buffering.

Returning to the original topic:

Just wondering what general thoughts there are regarding the pros and cons of using namespace NameSpace;

You might find this dicussion on using namespace std ; interesting:
http://www.cplusplus.com/forum/general/72248/

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
vijayan121 1,152 Posting Virtuoso

The linker can't find the library files. You need to add one or more -L<path to library files> to the link command
http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/Directory-Options.html#Directory-Options

For example: -LC:\MinGW\lib

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

Are they compiled separately then linked?

Yes.

The linking may be done either statically or at load/run time from a .dll or .so

vijayan121 1,152 Posting Virtuoso

I pretty much get what was posted (need to look up sprintf), but the code below gives me the error that "fname, MAX_FILE_NAME_LENGTH, and strlen"

Why have you started messing around with all this stuff? Your origininal idea was far superior; just that you made a careless typo. Fix that and move on to the next task at hand.

// ofstream write ("test\\" (variable+".txt").c_str()  ); 
// this the place where I'm having trouble

ofstream write( ( "test\\" + variable + ".txt" ).c_str() ) ; 
// you wouldn't have any trouble now
vijayan121 1,152 Posting Virtuoso

Each constructor and destructor gets called each time the loop is executed...

If this is what you want, arkoenig has already given you the solution.

The purpose is to create a brand new object each time the loop is executed for as long as the loop runs. Once the loop terminates the objects will be destroyed.

If this is really what you need to do, use a std::vector<>

{
    std::vector<DataType> objects ;
    while( whatever ) // each time through the loop
    {
        objects.emplace_back( /*...*/ ) ; // construct a new object in situ
        objects.back().do_something() ; // use the object
        // ...
    }
}
// all the objects would have been destroyed by this tine
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

Use std::sort() and std::unique() in <algorithm>

#include <algorithm>
#include <iostream>

int main()
{
    int a[] = { 0, 1, 0, 2, 3, 4, 3, 3, 5, 2 } ;
    enum { SIZE = sizeof(a) / sizeof(*a) } ;
    std::sort( a, a+SIZE ) ;
    const int size_unique = std::unique( a, a+SIZE ) - a ;
    std::cout << "size_unique: " << size_unique << '\n' ; // size_unique: 6
    for( int i=0 ; i<size_unique ; ++i ) std::cout << a[i] << ' ' ; // 0 1 2 3 4 5 
}
WaltP commented: You learn nothing from using language extensions. -3
m4ster_r0shi commented: I don't see any language extensions here. This code is standard C++. +6