mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Generally, to be safe, you implement these kinds of "instance counters" wrapped in a factory function. Typically, you also don't want spurious copies and things to be created, so you make the class non-copyable. This way you count only the "uniquely new" objects that were created, not copies and temporaries. By making the class non-copyable, you force it to be used via a pointer, and the only function to create that pointer is your factory function, which records the instances created:

class People {
  private:
    int ssn;
    People(int aSSN) : ssn(aSSN) { }; //constructible only from factory Create().
    ~People() { }; //destructible only from factory Destroy().
    People(const People); //non-copyable.
    People& operator=(const People&); //non-assignable.
  public:
    static People* Create() {
      static int objectCount = 0;
      return new People( ++objectCount );
    };
    static void Destroy(People* p) { delete p; };
};

int main() {
  People p1 = People::Create();
  People::Destroy(p1);
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I agree, the OP's solution is better than the others posted. The remove_if is exactly meant for this purpose and it's use is clear, efficient and idiomatic.

But the string copying is useless btw, the idiomatic use of remove_if is as follows:

myString.erase( std::remove_if( myString.begin(), 
                                myString.end(),
                                isspace ),
                myString.end());
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As for data structuring for this, you can use polymorphism, in which case you have to look for what is common to all things involved. In this case, I would suggest at least one function: "evaluate()". All expressions or values have to be able to be evaluated to yield a value. In the case of expressions, they have to evaluate their operands and then compute the operation. While values only have to output the value they hold.

As for handling the case of functions (like sqrt or exp), they are simply unitary operators (i.e. they have one operand). While operations like + - * / are binary operators (i.e. they have two operands, one on either side).

The parsing will certainly require some look-ahead to determine what the next appearing expression is between a value, a unitary operator, or a binary operator. And then, it will require that it be added to the data structure that represents the overall expression. You can naturally see that the data-structure generated will be a tree-structure with branching factors from 0 to 2 (i.e. values have 0 children, unitary operators have 1 child (operand), and binary operators have 2).

The one additional thing to worry about is priority of operation. You should associate, to each expression, a priority value. The idea is that expressions of highest priority should be the deepest in the tree (nearest to the leaf nodes), because the expressions will be evaluated by descending the tree to the …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

std::vector 101: (for vector v)

- Use v[ index ] to read or write any value at "index" position.
- Use v.begin() and v.end() to get an iterator at the beginning or end of v.
- Use v.resize( newSize ) to change the number of elements in v to "newSize".
- Use v.size() to know the number of elements in v.
- Use v.empty() to know if the vector v is empty or not (empty -> size() == 0)
- Use v.push_back( newElem ) to add an element at the end of the vector v.

The above is enough to make it match the capabilities of standard C-style arrays. You can learn more features from here.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Of course, follow Narue's advice, she's always right! But, just to add to it:

You will have to specify the type for the use of the class template in your other class template:

#pragma once
template<typename T>
class D; //remove the <T>

template<typename T>
class B
{
	D<T>* d; //but you need it here. Or, at least, you need something between <>.
public:
	B(void){
    
	}
	~B(void){

	}
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You would probably want to take each word that occurs, create a vector of the number of occurrences of each letter for that word, then create a std::multimap where the key value is this vector of letter occurrences and the value is the word. When the user inputs the scrambled letters, count the letter frequency and search for matches in the multimap. This is going to be faster than computing all the possible (variable-length) permutations of the input letters and searching for each one of them.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Basically, the rule goes like this:
- A forward-declaration of a class is sufficient to create and use a variable whose type is a pointer/ref to that class.
- A class declaration is required to create or use a variable whose type is of that class (value).

When you dereference a pointer to class B, you are using a variable whose type is of class B, this requires class B to be fully declared. So, to solve this problem, you need to interleave the declarations and definitions:
1) forward-declare class B
2) declare class D (uses pointer/ref to class B) (no definitions that require B)
3) declare class B
4) define class D (implement functions in D that require the declaration of class B)

Typically, you group 1) and 2) in the "D.h" and you get 3) and 4) into "D.cpp" by #including "B.h" and then implementing the member functions of class D.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Intuitively, I would guess that the problem is that you are attempting to close a file stream that was never opened or already closed (i.e. Stream == NULL causes the assertion failure during the closing of the file, in fclose()).

The ZeroMemory() part seems suspect too. In C++, it rarely is a good idea to just zero the memory because you should normally rely on constructors and RAII-style classes.

What are the data-members of SVisFileDescriptor?
What is imageS1? Where is it initialized? Used?
What does imageS1.WriteFile(filedescriptor1) do?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The :: operator is a scope-resolution operator. Because CompareX is a static member function, it is like a free function which is in the scope of the class Point2D. So, the Point2D:: means "look into the scope of Point2D for ..." (just like std:: means "look into the scope of namespace std for..."). Because it is a static function, it does not require an instance of the class (an object) to be called with. On the other hand, the two options you tried (with dot and arrow) are operators to find members of an object. They can only be used on an object (not on the class) to retrieve a member (data or function), and the dot is for an object directly while the arrow is for a pointer to an object.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The error message says it all. You have made the function OnConnected() a pure virtual function which means that it has no implementation in the class Connection, which, in turn, forces you to provide a class, derived from Connection, that implements this function. In short, this pure virtual function makes the Connection class an "Abstract Class" and an object of that class cannot be created. You need to create a derived class, with an implementation for OnConnected(), and create an object of that class instead. In other words, you need to revise your implementation of your factory function create() which creates an object of Abstract class Connection. The second version succeeds only because you don't have that erroneous factory function.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The sort algorithm (or the std::set container) have an optional parameter which is the Compare function for the elements to be sorted. This comparison function is, by default, the less-than operator which ends up sorting things in increasing order. You simply need to make a functor (callable object) which does the kind of comparison you need for your problem (or it can be a function-pointer, but a functor is more practical). Here is an example to sort by the X value:

struct CompareByX {
  template <typename PointType>
  bool operator()(const PointType& p1, const PointType& p2) const {
    return p1.getX() < p2.getX();
  };
};

int main() {
  std::vector<Point2D> v_2D;
  // fill v_2D with values...
  //then, sort according to X:
  std::sort(v_2D.begin(), v_2D.end(), CompareByX()); //create the CompareByX functor.

  //similarly for Point3D:
  std::vector<Point3D> v_3D;
  //..
  std::sort(v_3D.begin(), v_3D.end(), CompareByX()); //you can reuse the same functor since it is template-callable.

  //you can do pretty much the same thing with a std::set (which keeps it sorted all the time):
  std::set<Point2D, CompareByX> s_2D;
  //just fill s_2D with data, no need to sort afterwards since it is always in order.
};

Just make other functors for Y and DistFrOrigin, and you are done. You can also make those functors as either classes nested in the Point2D/Point3D classes, or as static member functions of Point2D/Point3D classes. Here is an example as a static member function in the Point2D class:

class Point2D {
  //... all your other stuff...
  public:
    static bool CompareX(const Point2D& p1, const Point2D& p2) {
      return p1.x …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@raptr_dflo: the setDistFrOrigin() is a private function that is called in the constructors and in every set() function of the Point2D class. So, the distance value that he gets is not garbage, he actually handled this problem quite well (making setDistFrOrigin() private and calling it at every modification of the data, to keep it consistent at all times). You seem to have missed the original problem, that is, how to print his Point2D class in two different ways (with and without the distance value after), and I provided two solutions to that problem.

You are right about pow() being inefficient here. I did point that out in the code I posted. For small, integer exponents, it is always more efficient to multiply the values out instead of making a call to pow().

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As suggested already, you should store all the strings from the file into a set. Now, you can choose:

- std::set: Uses a balanced-tree implementation to sort and search for words. Most operations are O(logN) time.

- std::unordered_set: This is going to be part of C++ standard library very soon, and most implementations support it already (Microsoft and GCC). This is a hash-table implementation, so most operations are in constant O(1) time (but your mileage may differ due to collisions problems).

The two options turn out to be the same coding-wise, and for performance, unordered_set is probably better, but that's always something you need to test. And if this is for an assignment, it's probably better to stick to (really) standard stuff like std::set (because you don't want to require to corrector to install anything additional if his implementation does not happen to have unordered_set).

>>So i have been wondering how i can optimize that using Object-oriented programming.
I don't think OOP is useful for this. And, on a side-note, things like std::set, #include <algorithm> and #include <functional>, almost the entire STL, are pieces of code that would be classified under "Generic Programming" not under object-oriented programming. C++ is a multi-paradigm language with strong synergy between the different styles. For instance, in the standard libraries only a few things like the IOStream library could be classified as more OOP than anything else, the rest is predominantly GP with some clever use of OOP and Procedural …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The easiest solution is surely to use simple print() functions instead of overloads, as follows:

//in the header:
class Point2D {
  //...
    void print(ostream& out, bool WithDistFrOrigin = false) const;
};


//in the .cpp file:
void Point2D::print(ostream& out, bool WithDistFrOrigin) const {
  out << "[" << setw(4) << p2d.x << "," << setw(4) << p2d.y << "]";
  if(WithDistFrOrigin)
    out << setw(3) << "" << p2d.distFrOrigin << endl;
};

This way, if you just call "print" on your point (passing the output-stream), you will get the output without the distance from origin, but if you add a "true" value to the call, you will get the distance from origin output as well.

If you absolutely want to use the >> operator on your Point2D objects, then you need an additional little trick. Operator overloads are selected based on the type of the parameters (and the number of parameters is fixed, so you can't add a flag to do one or the other printing method). So, in order to select different printing methods, you have to change the type of your object, which is actually quite trivial to do with a simple nested class:

class Point2D
{
  protected:
    //Declarations
    int x;
    int y;
    double distFrOrigin;	
    //Function
    void setDistFrOrigin();

  public:
    //Constructor
    Point2D(int aX = 0,int aY = 0); //use default parameters instead of 2 constructors.

    //Set Methods
    void setX(int aX); //use parameter names in prototypes to be more descriptive. 
    void setY(int aY);

    //Get Methods
    //If a member function does not …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Windows or Linux? (or Mac?)

Try CodeBlocks (for windows, make sure you download the one with mingw (the compiler)).

For Linux, just ask your package manager system! For the compiler: 'build-essentials'. For a good IDE, either 'codeblocks' or 'kdevelop' (I prefer the latter).

All these are based on the GCC compiler. So, for just the compiler, you can get either gcc in Linux/Mac or MinGW in windows. But then, you have to write the software in a text editor (emacs or vim) and then compile in the terminal (or command prompt).

You can also try the Microsoft products, like Visual Studio Express Edition (which is free). Personally, I'm not a big fan of their C++ related products (mostly their compilers are shit).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The error is obvious. At line 197, you use a local variable called "books" to record the booksBorrowed. Then, you insert into your std::map a value which is the address to that local variable. Then, you return from that function, which also causes that local variable to disappear (be destroyed), but you still hold a pointer to it in your std::map. Finally, you try to access it in your "checkCurrentLoans" function which throws an error because you try to access an object that no longer exists (and since that object was allocated on the stack, you get an "abnormal termination" as opposed to the classic "access violation" you normally get when accessing other memory you are not supposed to access since it was destroyed earlier).

To remedy the situation, you need to either allocate the "books" as a pointer to an object newly created on the heap (with new) and delete all the values in your map at the end of the application. Or, you can store the "bookBorrowed" objects by value inside your std::map instead of by pointer.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes, you can do so. But, of course, not using "dynamic polymorphism" but "static polymorphism" (as in, at compile-time). In your example, you don't need dynamic polymorphism, so it will work (when you really do need it, it won't).

The basis for achieving this is via a clever technique called "TypeList", developed the all-mighty template wizard himself: Andrei Alexandrescu. I suggest you read his book if you are really serious about learning to manipulate templates (his book: "Modern C++").

In a nutshell, here is the typelist technique. You need to build a list of types, but, in template meta-programming, everything has to be recursive (which is not really a problem since everything is done at compile-time, it will just increase compilation-time). So, you can build a single-linked-list of types with the following simple templates:

struct null_type {
  typedef null_type tail; //cycling terminator.
};

template <typename T, typename Tail = null_type>
struct type_list {
  typedef T type;
  typedef Tail tail;
};

So, the above can be traversed recursively (as with a normal linked-list) until the tail type is the null_type . Now, if you need random-access, as with any linked-list, to mimic it, you have to traverse from the beginning up to the element of the index (but since it is done a compile-time, it doesn't really matter at the end, no run-time overhead). Of course, the index has to be known at compile-time. So, here is a simple type-list indexing template:

//general type indexer
template <typename …
L7Sqr commented: I'm reading his book now; great stuff. Great example here, too. +6
jonsca commented: Great examples!! +14
alwaysLearning0 commented: nice example. +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have indeed a simple problem of terminology.

What you are describing is a classic problem in, at least, the fields of machine learning and data mining. The problem is called "data clustering" (which is part of the field of "unsupervised learning methods" for "data classification").

If you search for these terms, you will have much better luck, I guarantee.

As for the most suited algorithm for your simple problem of clustering simple integer numbers, it is definitely the "K-means clustering" algorithm. The algorithm is very simple:

1) Start with K random elements in your set as the starting means of your clusters,
2) Put all the other number together with whichever mean they are closest to
3) Then recompute the mean of each cluster,
4) and Repeat, until you have no more change in the clusters.

Very simple, guaranteed convergence. Although, there might be a more specialized algorithm (or version of it) for this 1D case (since K-means is more generally applicable to any dimensionality and any distance metric). And, of course, there are refinements to this basic algorithm (and entire fields of research are dedicated to this), but for your simple problem, this simple algorithm is definitely good enough, and can be implemented in a matter of minutes.

Jsplinter commented: lol, I thought so. Thanks for getting me on the right track! +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your function needs to return a LRESULT, not void. And your parameters are inverted

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You should play around with the pixelformatdescriptor. This is often a source of weird errors because when it cannot be realized, the OS chooses a closely matching pfd and sometimes that pfd is crap and gives very weird results. What parameters did you try? Most modern computers work on a 32 bpp, but that means that the ColorBits should be 24 and the AlphaBits should be 8 (or 0). You set it to 32 bits on the ColorBits field (while NeHe sets it to 16, for older systems). If you are seeing a transparent screen, it is possible that the pixelformat gets selected wrong due to a poor choice of parameters.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

D) Use Boost.Multi-Index. This is a library for keeping an array sorted according to multiple indices (i.e. keys). This is probably the best and easiest way to keep the list "sorted" according to both the key and the value at the same time.

However, if you just want to completely switch from one ordering (according to keys) to another ordering (according to values), then store them as a pair, and make two functors for the two kinds of comparison:

typedef std::pair<MyKey, MyValue> MyPair;

struct CompareByKey {
  bool operator() (const MyPair& a, const MyPair& b) const {
    return a.first < b.first;
  };
};
struct CompareByValue {
  bool operator() (const MyPair& a, const MyPair& b) const {
    return a.second < b.second;
  };
};

Then either you use std::vector and std::sort, or use two sets.

int main() {
  std::vector< MyPair > v;
  //... push all the elements into v.
  std::sort(v.begin(), v.end(), CompareByKey()); 
  //now you have a vector sorted by keys and can be accessed by binary_search.

  std::sort(v.begin(), v.end(), CompareByValue());
  //now you have the same vector but sorted by values.

  //with two sets:
  std::set< MyPair, CompareByKey> sk;
  //insert all the elements into sk and you have a sorted set according to key.

  std::multiset<MyPair, CompareByValue> sv;
  std::copy(sk.begin(), sk.end(), std::back_inserter(sv)); 
  //now you have another set with the values sorted by value.
 
};

You can also have a std::vector of the pairs, and then keep a std::set and a std::multiset that holds the indices into the vector, sorted (with similar kinds of functors) by …

Jsplinter commented: Once again, awesome post! +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

well I know that the last delete statement you have should be an array deletion, as such:

delete[] c;

But other than that, I don't see any reason for the "weird" behavior. It might simply be that your implementation (compiler + libs + OS) has a more sophisticated or different heap than the malloc/free allocator.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

conio.h is a non-standard library for MS-DOS. You can read the little wiki on it.

The only function that requires conio.h in that piece of code is the final statement getch() whose sole purpose is to pause the program until you press a key.

First of all, you should definitely not remove the .h.

Second, if your compiler does not provide conio.h, then you need to remove that include and also remove the getch() statement. You can achieve almost the same effect by using cin.ignore(); cin.get(); (but it will require that you hit enter).

Finally, a little correction:
>>I know that this is old one and the .h format is replaced with using namespace
That is not true at all. Basically, only the standard libraries do not have the .h extension, and I don't really know why, maybe to distinguish them from everything else (and legacy versions of the standard libraries). Whether namespaces are used or not does not affect whether the .h extension is there or not. The compiler basically ignores the extensions or whatever, it treats the #include file as a filename that it looks up in its include search-directories (and C++ standard library headers are files without an extension). In C++, the common extensions for header files are .h and .hpp, and namespaces are used and should be used in all library code (standard or not). In C, only the .h extension is used and there are no namespaces. …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think you are stepping into this topic a bit too early in your learning experience. To understand it, you should read this FAQ. And I would also suggest you first read all the parashift FAQs that come before as well (chapters 0 to 25).

>>theName is passed to the Teacher and Student constructors which is then carried over to the base class: Person(theName)

Actually, no. Because of the order of construction, the rule is that all virtual base classes should be initialized before anything else. Since, in this case, a parameter is required to initialize the base class Person, all derived classes have to explicitly call the constructor of Person with a parameter (e.g. theName) in their initialization list. Basically, if you create an object of class Teacher (with two parameters: name and class), then the theName parameter will be carried over to initialize the Person base class. The same if you create an object of class Student. However, if you create an object of class TeachingStudent, in order to be able to construct its virtual base class before anything else, the constructor of Person has to be called with the proper parameter in the initialization list of TeachingStudent (this explains the addition of "Person(theName)" in your "confusing" line of code). When the other (non-virtual) base class constructors are invoked (for Teacher and Student), even though the theName parameter is given to them, it will not be carried over to the virtual base class Person, …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>When I do have a condition to set the loop = 0 (false), my loop continues to run though!

There are two keywords you need to know about: break : this instruction will terminate the loop. In other words, the execution "jumps" from where the 'break' statement appears to the line immediately following the end of the loop. continue : this instruction will skip the remainder of the current iteration and move on to the start of the next iteration of the loop (i.e. goes back to the start of the loop, and does also check the condition of the loop and evaluates the for-loop expression (third slot) too, if such is the case).


Besides that question you asked, I have no idea what the relation between the code you posted and the question you asked is.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

dist: This is an array that stores the estimate of the distance to the source (through the "optimal" path) for every vertex in the graph. This is a quantity you want to minimize all the time, i.e., this is a shortest-path algorithm.

previous: This is an array that stores, for each vertex v, which vertex would have been visited just before vertex v if you were following the shortest-path (found so far) from the source to vertex v. In other words, at the end, if you want to know optimal path, you just follow the "previous" vertex, then again and again until you reach the source.

In this implementation, I assume that "alt" is short for "alternative route". Basically, at each vertex that you look at (vertex u in this case), you check if any of the neighbors would be better off coming from u than what they current hold as their best distance estimate (dist[v]) and associated predecessor (previous[v]). "alt" is just the addition of the distance estimate of the current vertex u and the distance to travel to the neighbor vertex v. If that distance is smaller than v's current shortest-distance estimate, then u becomes the new predecessor of v and "alt" becomes its new distance estimate.

Initially, you set all distance estimates to infinity and all predecessors to "undefined" (or "none"). Then, by giving a distance of 0 to the source vertex (because it is obviously at zero distance to itself), you guarantee that …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Ok, in your second last post, you are right! That is exactly how it goes.


As for 'theName', there are two of them. Both are inherited from Person, but one is inherited through Student and the other is inherited through Teacher. This is why you can access one via Student::theName and the other via Teacher::theName. The problem is if you try to access 'theName' directly (without the 'Student::' or 'Teacher::'), then the compiler will have a problem with that because there are two to choose from.

So, 'theName' is the same case as 'theClass' which you understood correctly. The only difference is that the two 'theName' variables (the one from Student and the one from Teacher) are initialized to the same value by passing the same string to both constructors of Student and Teacher (which each carry that string over to their base class 'Person').

At this point, it might seem odd to you that there are two 'theName' when there really only need to be one. But the compiler can't know that. There is a mechanism in C++ to tell the compiler that this is the case, and it is usually used in this kind of multiple inheritance case, and it is called virtual inheritance, you can read more on that here.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>hoping <enter> would made an eof approach

Yeah, cin is special, it basically never has an end, because it can always wait for the user to input more stuff. But, in any case, that kind of while(some_stream >> value) loop is pretty usual for other "normal" streams (like file streams and string streams). However, in this case you have heterogeneous data, so a loop is generally inappropriate for that (it is appropriate when you have sequential and homogeneous data, like a sequence of numbers).


For the rest, I pretty much agree with Clinton Portis. In these cases, you are usually better off inputting whole lines into a string stream and then deal with what you got in there (it is easier for inspection of the content, validating it, etc.). Of course, as with your code, you CAN do it without, but that doesn't mean you should.

Another useful trick with string parsing is to flip between string-stream and string. You can use the string-stream for sequentially extracting (formatted) information. And you can switch to string to have random-access (to count words or commas, or whatever defines the 'validity' of your input).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>_*_CLK are #defines (not variables I mean). Do they still pause a problem?

Of course. What if something else (anywhere) in the standard libraries' implementation from any compiler-vendor you might want to compile this code with has the same name? After all, these names are reserved for compiler-vendors (or OS implementers), they are allowed to use them at will. Then, what will happen is that the preprocessor will sub-in your MACRO's definition in all those places where that item is found, and then you will get extremely weird, obscure, MACRO-expanded errors in the standard libraries' code (compilation errors) and you will probably plow your way through Hell to find what is causing the errors. It's definitely worse if you have #defines with these leading underscores than if you have variable names (because at least, variable names respect scopes, #defines don't).

>>I do hope you would believe me when I say that I had planned a fourth iteration

I do believe you. You had a great post and a great explanation, I found it rather bizarre that you didn't go that one extra step and mention the allocator (which essentially encapsulates the placement new operator). Don't get me wrong, most of my comments on your post were about minor details (except for the importing of a namespace in a header, that's a pretty big deal).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You got this example from "Teach yourself C++ in 21 days". Do you really think that is possible? Really?

By seeing the quality of the code in this simple, short example, it doesn't baud well for the remainder of the book.

Anyways, I think Saith covered what was needed. You might want to take a look at this thread for better book suggestions.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Sorry, it was just a couple of typos in the writing of check_data_member. Here is a replacement:

template <typename ClassType,typename DataType>
struct check_data_member {
    DataType want_;
    DataType ClassType::*pmember;
    bool operator() (const Foo& f) { return want_ == f.*pmember; }
    check_data_member(const DataType& x, DataType ClassType::*aPMember) : want_(x), pmember(aPMember) {}
};

Notice the constructor's name ('check_data_member' and not 'Pred') and the fixed typo with 'aPMember'.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You need to post more code, that's for sure. If it is too big, just make a copy of it all, then strip away as much as you can without eliminating the error (unless you find the bug!), then post it.

Also, try this:

void candidateType::setVotes(int region, int votes)
{
  try {
    votesByRegion[region-1]=votes;
  } catch (...) {  //literally triple dots (not two, not four, three!)
    std::cout << "****** Exception was thrown with region = " << region << " and votes = " << votes << " ******" << std::endl;
    throw;
  };
};

I'm also pretty sure that region is 0 when the error occurs.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, you are right Narue. I knew about those subtleties, but I generally apply the simple "don't use leading underscores" rule anyways.

>>data members like _x and _y are just fine.

They are, sure. But what about, if later you decide to eliminate the data member, or change its name, if you rely on the compiler to point out the places in your implementation where you use that data member that no longer exists, it might remain silent, assume you are referring to a global identifier of the same name, and you could get a nasty, silent bug on your hands. I admit that this is a bit far-fetched.

Don't get me wrong, there are plenty of people using leading underscores for this and that in their naming conventions. And where it's safe w.r.t. the C++ standard rules, and working, it's definitely not worth refactoring all the code to fix such a minor detail (and risking introducing bugs in the process). But, it's probably better to get used to another naming convention, if you are still at that point in the learning or have the liberty to do so (e.g. you don't have to use the already established naming convention of your project).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

For polymorphic types, it is quite easy to imagine (for a lack of actual knowledge). The compiler generates a static const type_info structure for each type that appears in the code. Then, if the type already has a virtual table (has at least one virtual function), then an entry is added to the virtual table which points to a virtual member function that returns a reference to the type_info structure for that class. Then, the compiler generates such a virtual overrided function for each derived class, each returning the reference to their generated type_info structure.

A similar mechanism is probably used for the dynamic_cast operator. For instance, you can have a virtual cast() function in each derived class, which tries to cast 'this' to whatever type the type_info structure of the destination type is. When dynamic_cast is done, it calls the most derived version of cast() and then works backwards by calling the base-class versions of cast() until the type_info structures of 'this' and the destination type match. If no match was found by the time you reached the most basic classes, then NULL is returned and the cast failed.

Well, you can't be sure that the above is the way it is done, since the compilers can do a lot more fancy stuff. The above was just how I implemented my RTTI system, and how many others work as well.

The point to take out of this is that C++ RTTI is usually fairly heavy-weight, because …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Nice explanation, but I do have a few things to point out.

First, a few details. You make extensive use of variable names, defines and identifiers which start with an underscore character. This is explicitly forbidden by the C++ standard. All identifiers starting with one or two underscore characters are reserved for the compiler vendors for use in their implementation (of either the standard libraries or language extensions, or both). Most of the times your code will work anyways, but you should learn to change your habits in that regard if you wish to write portable, standard-compliant code.

Second, I find it a bit bizarre that you make this whole explanation about initialization / allocation / construction, and yet, in your pixel constructor, you initialize the data members in the body of the constructor as opposed to the initialization list. This poor choice will lead to your constructor taking roughly twice the execution time that it could. So, here is a more appropriate pixel class:

class pixel {
public:
    pixel() { } //provide a default constructor.
    pixel(int aX, int aY, int aSignalStrength) : x(aX), y(aY), signal_strength(aSignalStrength) { }
    int signal_strength;
    int x;
    int y;

    void print_pixel(const char* msg) {
        printf("%s\n\tptr = 0x%x, x = %d, y = %d, signal_strength = %d\n", msg, this, x, y, signal_strength);
    }
};

Now for the meat of it. I think that you missed a very important piece here (probably should be the fourth iteration of your example). The concept that you …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Take out line 71. It is probably a left-over, and it is not needed (and is, of course, the erroneous line).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, what you are referring to is called "pass-by-reference" and "pass-by-pointer" because it pertains to the passing of the parameters to a function, not to the calling of the function. Those who use those "call-by-" terms are simply sloppy with their terminology.

Their are two main purposes for using pass-by-reference or pass-by-pointer, as opposed to pass-by-value. First, you can avoid the copying of the object in question, this is particularly important if the object is expensive to copy (large in size), or even non-copyable. The cost for that is, of course, that all access to the variable is indirect (requires dereferencing). This use-case often lead to the idiomatic const MyClass& param form for passing a parameter. This syntax means that you pass the caller's variable by reference to it, but you forbid the function that takes this parameter to actually modify the variable (which guarantees to the caller that his variable will remain intact after the call).

The second purpose for pass-by-reference or pass-by-pointer is to actually allow for the modification of the caller's variable. This is especially useful when your function needs to return more information than can be conveniently bundled in the return value (i.e. more than one output variable). You can then pass variables by (non-const) reference, modify them in the function, and then the caller will be left with the "results of the function" stored in the variables he passed to the function. This can be implemented with either a reference or …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, if(x==MINVAL) makes no sense, I think you meant to write if(x < MINVAL) .

Second, I'm pretty certain that you would be better off using a Tailor series expansion. All you should need is a Taylor series expansion around 0 degrees for both the sine and cosine, which is valid (within you desired precision) on an interval from -45 degree to 45 degrees (i.e. -Pi/4 to Pi/4). With simple trig. identities, you should be able to use those two expansions to calculate a sine, cosine or tangent of any angle. For example, for the sine of an angle of 80 degrees, you can compute the cosine of -10 degrees (which is in the Taylor series' range for the cosine), and similarly for other ranges of values.

Third, you should also remember that branchings (e.g. conditional statements) are surprisingly expensive and slow, you should reduce those to a minimum. Also, mark your free-functions with the keyword "inline" to allow the compiler to inline if it leads to faster code.

Finally, if you are using or can use C++0x, you should mark those functions with constexpr keyword to allow compile-time computation of the values whenever possible.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To flush the standard output, you can do std::cout.flush(); . As for the input buffer, you can't really flush it, but usually either std::cin.ignore(); , std::cin.clear(); or std::cin.sync(); will achieve what you want (i.e. ignore stray characters, clear error states, or re-synchronize with the buffer). Try those. I don't really know about flushall(), but a simple google search reveals that it is a POSIX-specific, C function and that it is deprecated in C++ (and modern OSes), but the header file for it is <stdio.h> (not cstdio, but the C library version finishing with .h).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes, definitely. C++ cannot allow you to overload operators for its built-in types or any array of them, that would be too easy to abuse and too dangerous, with no gain. You definitely need to wrap this in a class, and you should also want to do so, because defining such a 4x4 matrix definitely requires more than a simple typedef.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In order to be able to print using << with a custom type (class), you need to overload the << operator of the std::ostream class. And since you are using some class inheritance, it is probably advisable to use a virtual print() function for printing the content of your class (the most derived one). You could do the following:

// In the declaration of the Account class:
class Account  {
  //...
  public:
    virtual ~Account(); //never forget to make the base-class destructor virtual.

    virtual void print(std::ostream& out) const;
  //..
};

// Then, in account.cpp:

void Account::print(std::ostream& out) const {
  out << "Account: " << num << " Balance: " << bal << std::endl; //or whatever way you want it to look.
};

// Then, if you want a custom printing for Checking, add in declaration of Checking:

class Checking : public Account {
  //...
  public:
    void print(std::ostream& out) const; //this overrides the base-class implementation.
};

// Then, in checking.cpp:

void Checking::print(std::ostream& out) const {
  out << "Checking "; //add some customization.
  Account::print(out); //call the base-class version of print().
};

//finally, somewhere like in account.h or in main.cpp:
// overload the << operator for a Account object
std::ostream& operator <<(std::ostream& out, const Account& obj) {
  obj.print(out); //call the virtual print function.
};

// And then, in main(), you will need to dereference the pointer before using <<.
int main() {
  //...
  cout << *(checking[0]) << endl; //remember that C++ indices start from 0, not 1.
  cout << *(checking[1]) << endl;
  cout …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Typedefs are just aliases, they don't "create a new type". So, you have to overload the operator for the underlying type. You can also overload with the typedef, but that will just overload for the underlying type as well.

So, basically, the rule applies as for the underlying type. If the type is a type for which you cannot overload (e.g. built-in type) or should not overload (like an STL container), then it is not possible. And if the type already has an overload for it, then it will conflict with your typedef'd overload.

Find a better option. Wrap it is a new class. You could also provide, in that new class, an implicit conversion operator. This will allow all built-in operator overloads to act on the type if there is no specific overload that you provided for wrapper class. But this technique can have surprising or undesirable side-effects.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You should post your code that uses the + operator. The problem is possibly (or probably) there.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Narue is correct, of course. With, maybe, the additional remark that if you are going to make a copy of the parameters immediately as you enter the function, you are better off passing-by-value instead, you get a local copy, and you allow the compiler more opportunity for optimizations. Furthermore, operators like + should be implemented as friend functions. So, you would get:

friend
pentathlete_team operator+(pentathlete_team lhs, pentathlete_team rhs) 
{
    if (lhs.sum_res < 0)
        lhs.results();

    rhs.results();

    return pentathlete_team(0, 0, 0, 0, 0, lhs.sum_res + rhs.sum_res);
}

On a design perspective, you are missing a very nice opportunity here. You, correctly, made the data members of the pentathlete protected-access. This means, you have control over all modifications to those values. So, a function like results(), whose purpose is to make sure that the sum_res corresponds to the stores result array values, should not need to be called unless you are modifying the comp_res array. Since you control all access to comp_res, you can easily call results() every time the values were updated, ensuring that sum_res' value is always in sync with comp_res' values. If you do that, you will have no reason to call results() in your operator+, thus eliminating the original error, reducing the amount of code, and getting a more robust design. This is why const-correctness is nice, it tells you where you have made design mistakes that you could significantly improve on.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You need to also specify the "include directory" of boost, not just the link directory. The headers (such as adjacency_list.h) are in the boost include directory, not where the libs are. BTW, I'm pretty sure you need to include "boost/graph/adjacency_list.h"

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Forget what sergent said, especially if you are using SDL or any other cross-platform GUI library. OpenGL is the way to go. GLUT and GLUI are also fairly feature-full as well.

For a kick start, you can look at full-blown game renderers as well. For instance, Ogre3D is a nice and simple one (and surprisingly feature-rich), and it won't blow your brains in terms of coding either, just middle-of-the-road, simple OOP.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

After inputting a single character or a number, you should always make a call to cin.ignore(); .

For the error, I can't be sure.

Try to avoid using C-style strings, they can yield surprising errors. I suggest you use a stringstream based conversion from both appearances of itoa(). As follows, for example:

string AnB = (stringstream() << hex << resist).str(); //instead of itoa(resist,AnB,16);

Then, I say this line 133:

anb = countAnB.substr(2,2);

How do you guarantee that the string countAnB will actually contain a sub-string of length 2 starting from position 2. If countAnB is not long enough, this will crash.

Line 137 is also suspect. You are storing the number as a base-16 (hexadecimal) string, then converting to "result", but your conversion assumes decimal (base-10) digits. This could also crash very easily. You should use the same method for input as for output, thus:

if(!(convert >> hex >> result))
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are no real "standard" screen size. There are big screens, small screens, higher and lower pixel density.

The common aspect ratios are 4:3 (full-screen), 16:9 (wide-screen), and sometimes 16:10. And common pixel dimensions would be 1900x1080 (16:9), 960x720 (4:3), 1440x1080 (4:3), and so on.. I really don't think it should matter, your program should do like any good video player: start the video at the native size of the video, and allow the user to resize the screen at his will.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I don't know much about that. But gstreamer is the classic tool for video loading / decoding / displaying. Look at the list of plugins, they have several "videosink" (which is the lingo for "displaying the video"), I believe it can be easily be used with OpenGL, SDL, X, Xv, OSX, DirectX, and other less well-known rendering systems.

Then, there is also the well-known VideoLAN (VLC). You can use libvlc to embed video into either an SDL surface or a Qt widget. With all the video formats that VLC supports.

Then, phonon which can be used in Qt4.5 and above.

There are plenty of options to choose from.

OpenCV is another which can easily grab raw video and display it on a separate window.

The list could go on... This depends also one whether you want to decode video files or if you want to display/record a raw video input (IP camera, firewire, etc.). VLC is probably the most comprehensive solution. But again, I don't know much about video.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>flashed up really quick
This is simply due to the fact that you are using a windows-based IDE that pops up a console terminal and then shuts it down as soon as the program finishes executing. You need to get into a command-prompt from outside your IDE, go to your program's directory and execute the program manually. This way, the command-prompt won't disappear after the end of the program and you will be able to see what was last printed.

OR

Use the program I posted. The destructor messages should appear before you have to press enter.