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

>>would their definition then usually occur outside of the class scope?
Not necessarily. Operators can be non-friend as well if access to private members is not necessary. They can be defined outside the class declaration if they seem too long to remain in the declaration. Often people use the friend keyword just so that the implementation can be put in the declaration (even if private member access is not needed), when the function is very small it is sometimes nicer to have it in the declaration. But this is all just a matter of taste (however, when it comes to class templates, it is usually more natural to have them in the class declaration).

The main idea here is that free-functions should be preferred to member functions for essentially all operators that allow them. This is because of overload resolution, function hiding, and other considerations. Just get in the habit of overloading operators as free-functions (friend or not, in-declaration or not).

Jsplinter commented: will do +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, operators like comparison operators should usually be implemented as friend functions, not as member functions. In this case, that is not the problem.

The problem is that your member functions for operators < and == both take a const reference (which is correct), but the member functions are not marked as const themselves. Because member functions are called on an object of the class. If that object happens to be marked as 'const', then it should not be modified, which means that only member functions which don't modify the object can be called, and so, you need to mark those member functions which don't modify the object with the keyword 'const' at the end of the function prototype. As so:

bool operator< (const StrategyKey& stratKey) const //notice 'const' here.
	{
	  //..
        }

	bool operator== (const StrategyKey& StratKey) const //notice 'const' here.
	{
	  //..
	}

The error you are getting is simply because the function find() in map is marked as const, and thus, the constness propagates to all its elements, which means only const member functions can be called on them, which excluded your operator overloads (since they were not const).

Usually, the idiomatic way of implementing this is as follows, using friend functions instead:

class StrategyKey
{
public:
   //...
	friend bool operator< (const StrategyKey& stratKey1, const StrategyKey& stratKey2) 
	{
	  //..
        }

	friend bool operator== (const StrategyKey& StratKey1, const StrategyKey& StratKey2)
	{
	  //..
	}
  //...
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, any good C++ book should tell you that the destructor in a base class has to be marked 'virtual' (unless you are an expert and intentionally leave it non-virtual in the context of some advanced programming technique, like scope-guards).

Anyways, on my computer, it does as expected. The issue here is that the program "stops" (as in, it reaches the end of main()) and then the destructors are called. I guess under some operating systems or under some terminal/console/command-prompt the stuff printed after the end of main() don't get printed. It's not an issue with the code.

Here is a modified version that is certain to show you what you are longing to see (also notice the fixed identation, this is a very important habit to develop):

#include <iostream>
#include <string>

// Declare the BaseClass.
class BaseClass {
  public:
    // Constructor.
    BaseClass();
             
    // Destructor.
    virtual ~BaseClass(); //notice 'virtual' here.
             
    // Simple method.
    void doSomething();
             
};
             
// Declare a SubClass that
// inherits BaseClass.
class SubClass : public BaseClass {
  public:
    // Constructor.
    SubClass();
                          
    // Destructor.
    ~SubClass();
             
};
             
// Define the functions.
BaseClass::BaseClass() {
  std::cout << "Entering BaseClass::BaseClass()\n";
  // Do some initialization here.
  std::cout << "Leaving BaseClass::BaseClass()\n\n";
}
             
BaseClass::~BaseClass() { //notice that 'virtual' is not needed here (only in declaration).
  std::cout << "Entering BaseClass::~BaseClass()\n";
  // Do some cleanup here.
  std::cout << "Leaving BaseClass::~BaseClass()\n\n";
}
             
void BaseClass::doSomething() {
  std::cout << "Entering BaseClass::doSomething()\n";
  // Do something here.
  std::cout << "Leaving BaseClass::doSomething()\n\n";
}
                  
SubClass::SubClass() {
  std::cout << "Entering …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

g2++.h is not part of Boost, it is part of the g2 library. That problem is not related to Boost, since Boost does not contain external dependencies (especially not from such dubious source) except for the standard libraries. Additionally, I find it bizarre to have a file name that includes ++ in its name, some operating systems might not even be able to find it just because of the odd characters in the filename.

Just try to compile a simple BGL example from the tutorials and see if that works. That should tell you if your Boost installation is correct.

If you are using, alongside, other external libraries, and that some of those use this g2 library, deeming it OK to do so, it means you will most probably have further problems with that external dependency (Boost installation will be the last of your worries).

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

First: seed you random number generator once with srand(time(NULL)) .

Then, get a value between 0 and 31 using the modulus operator on the result of rand(), as so rand() % 32 . That gives you "n".

Finally, use the bitshift operator to raise to the power of "n". As so 1 << n .

And, that's it. Enjoy!

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

No.

The methods are associated with the type of the object (i.e. the class), they are not associate with the object, so they require no extra storage space on a per object basis. In fact, you can easily test it, just apply the sizeof() operator on a class with and without methods, both with the same data members. The sizes will be the same.

However, if you have virtual functions in your class, then the objects of that class will have to store a pointer to the virtual table (the virtual table is a simple per-class look-up table of function pointers for all the virtual methods). In this case (if you have one or more virtual functions), the objects will be one "pointer-size" bigger, which is usually negligible (the size of a pointer is usually the same as an "int", i.e. the natural word size of the computer, e.g. 32bits or 64bits). But in the example you showed, you have no virtual functions, so, no virtual table pointer, and thus, it doesn't make a difference.

You can try the following to see for yourself:

#include <iostream>

class A {
public:
   void DoSomething();
   void DoSomethingelse();
private:
   int x, y;
};

class B {
private:
    int x, y;
};

class C {
public:
   virtual void DoSomething();     //notice the 'virtual' here,
   virtual void DoSomethingelse(); // and here.
private:
   int x, y;
};

int main() {
  std::cout << "the size of A is " << sizeof(A) << std::endl;
  std::cout << …
Jsplinter commented: wow, thank you for that great answer! +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you want your addition operator to take a pentathlete_team, it should take a pentathlete_team and return one too. As so:

pentathlete_team operator + ( const pentathlete_team& sec_comp ) const {
				if ( sum_res < 0 ) {
					results ( ) ;
				}
				sec_comp . results ( ) ;
				return pentathlete_team( 0, 0, 0, 0 ,0, 
					sum_res + sec_comp . sum_res ) ;
			}

Notice also that you should pass by const-reference, and mark the member function as const as well. Also, you are going to need a constructor similar to that of pentathlete to construct the result.

Frankly, I have no idea why you are using inheritance here. There really isn't any reasonable "is a" relationship between pentathlete and pentathlete_team.

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

BGL is header-only, it does not require a library (at least, I think so).

If you do need to link to boost libraries, you need to follow the instructions on the boost website to build the libraries using MinGW GCC. That must be done in command-line (command prompt), using Boost's build system (BJam).

Normally, the libraries get installed into "boost_install_folder/lib/stage/". And, depending on the options you use for the build, they will have either .a or .lib extensions.

If you need to use the libraries for another compiler (like the microsoft compiler), you will need to build them with that compiler as well.

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

All you need to do, since BGL is a header-only library, is to add the include directory for boost in your CB project.

First, of course, you need to have installed Boost libraries, by following the instructions on the www.boost.org Getting Started page.

After that, you should have boost installed to some directory that you specified.

Then, in CB, you go to project/build-options and add, under include directories, the boost/include directory from where your boost installation was done. Then, all should be fine.

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

I doubt that using difftime with clock_t is a good idea. difftime works with data of type time_t, which is obtained from the function time(). The clock() function returns clock ticks since the start of the program, and if I'm not mistaken, the clock ticks are only those counted towards this program (it is not a measure of real time elapsing, it is a measure of how much time this program has spent executing stuff, which is only a fraction of the overall time the computer spends executing stuff (which is real time consumption)).

To get the difference between clock ticks, you can do:

return float(cur_time - start_time) / float(CLOCKS_PER_SEC);

To use time() instead of clock, you can do:

float timer(){
  time_t cur_time, start_time;
  cur_time = time();
  start_time = cur_time + 1; //???? THIS MAKES NO SENSE AT ALL ?????
  return difftime(start_time,cur_time);
}

The above just fixes the obvious problem (that you shouldn't mix time_t and clock_t). However, I cannot, for the life of me, understand how your function is supposed to work. Right now, all the timer() function does is return a constant value, whose value is undefined (implementation-specific). What did you expect the function to do? If you expected that function to cause the program to sleep for X amount of time, you are mistaken. You need to use a sleep function for that (Sleep() in Windows, and usleep() in Linux). Essentially, this program you have executes at the maximum speed it can, and the …

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

As L7Sqr said. And, of course, since find_if/find only finds the first occurrence, it is a trivial matter to wrap it in a while loop to find all the occurrences:

int main() {
  std::vector<int> v;
  //populate v. Now, delete all 0 values:
  std::vector<int>::iterator vit = v.begin();
  do {
    vit = std::find(vit, v.end(), 0);
  } while ((vit != v.end()) && ((vit = v.erase(vit)) != v.end()));
};

Additionally, you can define a generic predicate to check a particular data member:

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

struct Foo {
    int val_;
    Foo(int v) : val_(v) {}
};

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

template <typename ClassType,typename DataType>
check_data_member<ClassType,DataType> make_check(const DataType& val, DataType ClassType::*pmember) {
  return check_data_member<ClassType,DataType>(val,pmember);
};

int main () {
    std::vector< Foo > v;
    for (int i = 0; i < 5; ++i)
        v.push_back (Foo(i));
    std::cout << "length of vector: " << v.size () << std::endl;
    std::vector< Foo >::iterator vit;
    vit = std::find_if (v.begin (), v.end (), make_check(3,&Foo::val_));
    if (vit != v.end ()) {
        std::cout << "Found item to delete..." << std::endl;
        v.erase (vit);
    }
    std::cout << "length of vector: " << v.size () << std::endl;
    return 0;
}

However, if you want your look-ups to be fast, I suggest you use Boost.MultiIndex library to create efficient look-ups via different data members or methods. The library also includes standard generic …

munitjsr2 commented: Thanks, i get it +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>How do things like third.getfeet and third.getInches work?

These are member functions. This means that they have a hidden parameter which refers to the object on which the function was called (in this case, that object is 'third'). When those functions are called, if they use (set or get) the data members of the class they belong to, then those data members are implicitly taken from the object 'third'. I don't know what else I can explain about that.

>>I mean don't third already have a value since it equals to first + second?

Sure, third stores the value of the addition of first and second. The functions getFeet and getInches are used to access the values stored in third, such that they can be printed out.

>>Also in the length.cpp part, why did they include the class name when they were returning a value(lines 36,44,52,60)?

That is an 'explicit construction'. It is just to explicitly create an object of class Length with its value initialized to whatever is between parentheses.

NB: It is not needed in this case, because the author of this piece of code has made a mistake (amongst many others) and did not require the construction of Length from a single parameter to be explicit, in order to avoid unwanted implicit conversions from int to Length. Normally, his constructor should be declared as:

explicit Length(int inches){ len_inches = inches; } //notice 'explicit' keyword.

>>Last question, do you always have …

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

>>Local * pLocal = *(Local**)0xE6EB54; // valid

English translation: Take the literal numeric value of the hexadecimal number E6EB54 and interpret that numeric value as the address of an address to an object of type Local. Dereference this numeric value to obtain value stored at the address it points to; that value is interpreted as the address of an object of type Local. Finally, store that address in a newly created variable called pLocal, of the same type.

NB: I guess you can see why we use a programming language to write programs, and not a regular language like English.. it would be much too verbose.

>>Local * pLocal = (Local**)0xE6EB54; // not sure if this is even valid

That's not valid, but this is: Local* pLocal = (Local*)0xE6EB56; .


Even if the above may compile (and are 'valid' in that sense), it doesn't mean that they are OK. In either cases 1 or 2, needless to say, the program will crash! You cannot just take some literal numeric value and fetch memory at that location, the OS forbids that (for many obvious and less obvious reasons). The only ways to get a valid pointer is by either taking the address of an object (with the & operator), or by getting a pointer in free-store (i.e. allocating a new chunk of memory with the 'new' operator, or equivalent).

NicAx64 commented: roger that , well answered +7
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes, a line like this:

friend Length operator+(Length a, Length b);

in the declaration of class Length, tells the compiler that later, there is a free function (which is the operator+) that takes two Length parameters, and that this free function should be granted access to the private members of class Length. This what you typically do for these operator overloads. Later, the definition of the function will clearly show that this function is a free function. Like, for instance, if setLength() and operator+() definitions were to appear outside the class declaration, they would look like this:

void Length::setLength(int feet, int inches)  //notice the Length:: because setLength is a member of Length.
{
  len_inches = 12 *feet + inches;
};

Length operator+(Length a, Length b) { //notice no Length:: or 'friend' keyword.
  //...
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Most operators (except for the assignment, compound operator-assignment, and the few special operators like & and ->) can be implemented as a free function, not a member function of the class. Operator overloading should be regarded exactly as any other kind of function, they just have a different calling syntax. So, just like you could make any function a member function, you also have the choice to make them free functions. If you understand the difference between a member function and a free function, in the context of any "normal" function, the same applies to operator overloading. However, generally speaking, it is preferable to implement most operator overloads as free functions, because of the way C++ picks the right overloaded version.

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

FreeImage is a simple open-source library which can do this, no problem. If you have used any other external library in the past, it will be a walk-in-the-park to use this one.

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

>>no, I need to pass it by value.

You are passing it by pointer, not by value. Passing-by-pointer is just a (bad) way of doing passing-by-reference. Here is a simple piece of code that illustrates the three methods:

#include <iostream>

void pass_by_value(int val) {
  val = 42;    //val is a local variable now, so modifying it will not modify the caller's variable.
};

void pass_by_reference(int& val) {
  val = 42;     //val is an alias for the caller's variable, so it can be modified.
};

void pass_by_pointer(int* val) {
  *val = 42;    //val points to the caller's variable, so it can be modified, after dereferencing the pointer 'val'.
};

int main() {
  int i = 0;
  pass_by_value(i);
  std::cout << "Passed-by-value yields i = " << i << std::endl;
  int j = 0;
  pass_by_reference(j);
  std::cout << "Passed-by-ref yields j = " << j << std::endl;
  int k = 0;
  pass_by_pointer(&k); //take the address of k.
  std::cout << "Passed-by-ptr yields k = " << k << std::endl;

  return 0;
};

In the above, the type int is used for the passed parameter. In your case, the type of the passed parameter is 'avl' (pointer to nodo). Make sure you understand what is going on in the above example, it will surely help you understand what you are doing, or trying to do.


>>All this works perfectly, but on the moment I go out of Comprobar_equilibrio(), *r is still the same.

Then, all is NOT working perfectly. I …

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

>>I have been programming for a while now

Taking you on your word, I would assume that the explanations of the previous posters isn't what you were looking for, because if you have been "programming for a while" you definitely knew this already. Right? I'm sure your question is not about the difference between a dot and an arrow in C++ (because you would surely have found tons of resources explaining that in way more details than you could imagine).

So, I'm guessing you are asking why would someone choose to use an object via a pointer to it, or to use an object directly. If it is so, you need to clarify the question more. Do you mean any one of these:
- "dynamically allocated objects" versus "stack-allocated objects"
- difference between accessing members from an object-pointer or an object
- pass-by-reference versus pass-by-value
- ...

The example code you posted doesn't really tell much (especially since the first one is erroneous in any case).

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

-- Here is a description of what you should NOT do --

You could do what firstPerson suggests, but that would just create an error at line 41 saying that you cannot convert a const T& to a T& (usually, the message for that is: "error: converting parameter of type 'const T&' to 'T&' discards qualifiers").

Now, you could also make the constructor of Node to take a const T& as well, as so:

Node(const T& rItem):pItem(&rItem),pNext(0){}

But, then you will get yet another conversion error at that line because taking the address of a 'const T&' yields a pointer of type 'const T*', and thus, the statement pItem(&rItem) will again say: "error: converting pointer of type 'const T*' to a pointer of type 'T*' discards qualifiers".

Now, you could then make the pointer stored in Node, also be a const pointer, that is, you could write const T* pItem; .

That will get rid of your compilation errors. But it's the worst thing you could do!


-- Here is why the above is so bad --

There is a rule in C++ that allows you to take a temporary variable via a const reference. In other words, this is valid:

void Foo(const int& bar); //some function takes a const reference

int main() {
  Foo(42);     //the function can be called and the const ref can be binded to the temporary value 42, even though that "variable" has no "real" address in …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster
if(number == 7) continue;

This will skip the rest of the loop if the number is 7, and it will go back to the start of the loop (i.e. it will increment i, and check the end-condition).

if(number == 7) break;

This will terminate the loop if the number is 7, and it will resume execution after the closing } of the loop.

Loki55 commented: Thanks +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

One big red flag that I see in all your explanations is that you always stick the * next to the name of the pointer. This hints at a classic misunderstanding beginners have with pointers. Notice how I always stuck the * next to the type in the declarations, not next to the variable name (it makes no difference in compilation, but it makes a difference when it comes to understanding it right). Understand this:

int* ptr; //this declares a variable called 'ptr' which stores a pointer (i.e. the address) to an integer (not allocated here).

When you are not in a declaration, if you put the * next to the pointer's name, it will dereference the pointer, meaning it will fetch the value at the address stored in the pointer variable.

When you have a variable, and apply the & operator on it, it takes the address of the variable. The address of a variable is just a value, a temporary value, it is not a pointer variable, and it is certainly not the pointer variable from which the original variable was obtained by dereferencing with *. When you have something that is a value, but is not a variable, in C++ lingo, it is called an rvalue (because it is not a variable, you cannot store values in it, but since it is a value, you can assign that value to a variable, i.e. it can appear on the right-hand-side of an assignment).

>>and it …

Nick Evan commented: good posts in this thread +16
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

** Don't bump old threads like that, especially if you add nothing to it **

BTW, the C++ version of this code is this:

#include <iostream>
#include <list>
#include <algorithm>

int main() {
  using namespace std;
  int number;
  list<int> lst;
  while((cin >> number) && (number != 0))
    lst.push_back(number);
  lst.sort();
  copy(lst.begin(),lst.end(),ostream_iterator<int>(cout," "));
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Ok, so lets see if we can break-up this statement into pieces (which is NOT equivalent to &*raiz, but it illustrates a point):

nodo** raiz; //from your code, this is basically the type of raiz
  nodo*& tmp = *raiz; //when you dereference raiz, this is what happens
  nodo** ptmp = &tmp; //when you reference tmp again, this is what happens
  ptmp = &*p; //when you assign, this is what happens

The above works fine because ptmp is an lvalue (it is a variable with an identifier and thus, it can be assigned to). But, when you use &*raiz, you don't create an lvalue, you just create a temporary value which contains the address of *raiz, this is not an lvalue, it is called an rvalue (can only go on the right-side of an assignment).

This is why people here have said it makes no sense to do the statement you posted. You are basically creating a temporary variable and assigning a value to it. In any case, if the compiler allows it (and it should not!), the statement has no effect at all.

I'm guessing, what you really meant to do was simply raiz = p; . But, if your code works as is under Windows, then I guess you should just delete that statement since it has no effect.

PS: Whenever something compiles in "under Windows" (which I guess means with MSVC, the microsoft compiler) and fails to compile with GCC, there is probably a …

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

Another thing that might help, notice that the least-significant digit of successive powers of 2, starting from 2, follow a fixed sequence: 2,4,8,6,2,4,8,6,2,4,8,6,... I'm sure there a sequences like that for other digits too!

You could also map all the triplets of bits to an octal representation (base 8, which is easy because it maps directly from 3 bits) and work from that intermediate representation to construct the decimal representation. Octal arithmetic might be less tedious than binary arithmetic.

Probably, the easiest solution is to convert first to BCD (Binary-Coded Decimal) which restricts every 4 bit sequence to be less than 10 and then the conversion to decimal is trivial. Here is a simple algorithm to convert a binary sequence to a BCD sequence.

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

First of all, assuming your binary string is stored from most significant bit to least significant bit, you will have to traverse it in reverse (from the end to the start), which isn't a big deal.

The same goes for the output string. You will have to preallocate enough storage for the output string (e.g. the size of the input string, or one third of that, since 3 bits represent at most 7 in decimal, but 4 bits go beyond one digit in the decimal base (i.e. 15)). Then, you can set its characters starting from the last (least-significant digit), at the end, you can copy the string back to the start if you used fewer digits than the preallocated amount.

As for computing the actual digits, that just requires a bit of arithmetic. Your main problem is going to be that all bits will yield a decimal representation with no trailing zeros. This means, you will always have to go all the way back to the least-significant digit of your output string and update its value based on the current bit you have that is not 0 (i.e. 1). In order to avoid overflowing integers, you will have to make wise use of modulus and bitshifting. When you figure out what value a particular bit contributes to a particular digit, then it is just a matter of doing addition with a carry (like you did in elementary school). This certainly isn't a trivial problem, but just try …

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

Line 48 of function_definition.cpp: When you allocate new storage for a C-style string (char*), you need to add the null-termination character. This means you need to allocate one more char than what is given by strlen(tName) . The same goes for line 663 (in function SaveToFile). As so:

Ptr->Name = new char[strlen(tName)+1];
strcpy(Ptr->Name, tName);
Ptr->Name[strlen(tName)] = '\0'; //set the null-termination character.

In function AddTo_End(), make sure that the Next pointer in NewNode is NULL (better be cautious when there are unknown bugs, even if setting NewNode->Next = NULL; might be redundant after all). The same pretty much holds for AddBefore_InBetween() (but I'm not sure what this function does, similarly, AddAfter_InBetween() is weird, it doesn't seem to actually add a node to the linked-list). Remember that you have no constructor for the Node struct, so it means that the value of Next in a newly created Node could be anything (a "garbage value"), so it needs to be set to NULL explicitly (at least somewhere).

Be const-correct. This usually helps in pointing out silent bugs (like unintentional changes in values). For instance, in function Node* SearchBy_Name(char* tName) , you should take the parameter as const char*. There is no bug there, but making everything const-correct usually helps overall, as a good coding practice.

Although it is probably not a problem, I would usually be a bit more confortable with if(strcmp(tName,i->Name) == 0) as opposed to if(!strcmp(tName,i->Name)) , it is also more idiomatic.

In function DeleteFrom_Start(), you do …

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

C++98 Standard Section 4.2 "Array-to-pointer conversion", paragraph 1:

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue of type “pointer to T.” The result is a pointer to the first element of the array.

As Narue said, arrays and pointers are not the same, however, the standard defines an implicit conversion from an array to an _rvalue_ pointer. An rvalue means that the variable cannot be assigned a value (i.e. it's "read-only", as in, it is usually on the right-side of an assignment, but cannot appear on the left-side (that requires an lvalue)). This is why you cannot, as in your example, do a = p; or something like that, because it would require a conversion of the array "a" into an lvalue pointer, which is not allowed, for obvious reasons.

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

In your header, you need to match the #ifndef linkedlist_H with a #endif at the very end of the header file.

In your cpp file, if you want to use the type listNode, you have to fully specify it, i.e. linkedList::listNode , otherwise the compiler won't find it.

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

No worries, people often use "class" and "object" interchangeably with or without realizing it is wrong to do so. I believe in rigour when it comes to terminology because getting into the habit of using precise terminology improves understanding for yourself and for others.

predator78 commented: I appretiated mike pointing out my error so that I continue to convey what I am saying in a proper fasion. +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>My qs. is while returning by value it would make a copy of the "to be returned temp variable". Wouldn't it do so by calling a copy constructor.

This is called the Return Value Optimization. This is classic. Do not, ever, depend on copy-constructors being called. This means, don't do operations in the copy-constructor that don't pertain to "just copying the object". Obviously, the C++ compilers have some liberty in optimizing away some copy-construction and assignments when it involves temporaries, for obvious reasons. The side-effect that this has is that you have to keep your copy-constructors simple enough that simple copy-semantics still hold (i.e. the copy-constructor should not have any other extra side-effects).

>>Also, when I passed a test object to assignment operator by value, a copy constructor should be called there.Isn't it?

Yes, that's the whole point. If you are going to make a copy of an object that is passed as a parameter to a function, you should pass-by-value and you get a copy of the passed object for free (and with some performance benefits as well).

>>it should also return by value.

I don't see any purpose for returning a value from the assignment operator (at least, not in this context). But if you really want to do that, fine, do it. I'm pretty sure it's not necessary, and certainly wasteful.

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

>>1. Are data structures essentially classes minus methods which can preform actions
on the members that are held inside?

What you are describing are "C-style structs" or, more commonly, "POD-types" (Plain Old Data types). These are not what people would call data structures (or at least, they are an extremely trivial example of a data structure). Data structures typically refer to language-agnostic concepts of how data can be structured, often for a very specific purpose. Examples include binary search trees, linked-lists, sparse-matrix storage patterns, multi-index search trees, space partitioning, etc. These are complex beasts that generally arrange data in a way that optimizes certain operations (e.g. fast search, fast sort, fast nearest-neighbor query, minimal reallocation and copying, non-blocking concurrency, etc.). A data structure is a theoretical and abstract concept. Classes in C++ are a specific implementation (often, an implementation of a data structure and its related functionality).

>>2. In the case that question 1 is true... Why would I then chose to use a data structure over a class as data being stored is usless without being able to preform actions on that data?

Considering POD-types, sometimes, there is just nothing to do really with the data in a standalone fashion. Some things are just very simple bundles of data nothing more, so why should you needlessly put any member functions if none make sense. Also, POD-types, I mean the C++ Standard definition of them, can lead to some performance increase because the compiler is allowed …

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

The code you posted outputs the following on my computer:

Enter you name:sdfs

Your name is:sdfs
Copy constructor called...
Your name is:sdfs
Assignment operator called...
Your name is:

The above is exactly what I would expect. Where is the trouble? Besides the fact that your code has memory leaks and corruptions, and an improper assignment operator.

Here is a bit of explanation of what is going on:

int main(void)
{
    test t1;      //calls the default constructor to create t1.
    t1.getstr();
    t1.display();

    test t2 =t1;  //could call the default constructor and then the assignment operator.
    t2.display(); // but will almost certainly just call the copy-constructor.

    test t3;      //calls the default constructor to create t3.
    t3=t1;        //calls the assignment operator on t3, and the 
    t3.display(); // return value is discarded, no copy-constructor is called.

    return 0;
}

Now, for the bugs in your code.

1) The strlen() function does not count the null-termination character. So, you need to add one character when allocating memory to hold a copy of a string. As such:

p = new char[strlen(t.p) + 1];

2) Be const-correct. Your copy-constructor should not be modifying the object passed to it, so it should be a const reference. As so:

test(const test& t)  //notice const here.
    {
        std::cout<<"\nCopy constructor called...";
        p=new char[strlen(t.p) + 1];   //notice + 1 here.
        strcpy(p,t.p);
    }

3) The assignment operator should, in theory, also take a const reference. But, a more practical solution is to take a copy (i.e. by …

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

There is a special allowance for compilers to optimize away the copy constructor when returning an object by value from a function. Basically, the compiler sees that the returned object is assigned to a variable and thus will use that variable directly, within the function, to create the returned object. This avoids useless copying. Never depend on the fact that the copy-constructor will be called once or twice during a return-by-value and direct assignment at the call-site.

BTW, the copy-constructor should take a const reference. You also need an assignment operator (preferably implemented as a copy-and-swap idiom).

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

>>I am looking for something to compact the clear and push_back in one line..

I don't see any point in doing this, but what about:

v.clear(); v.push_back(4);

or, if you really want it to be one expression:

std::vector<int>(1,4).swap(v);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The OpenGL window always goes from -1 to 1 on both x and y coordinates. You can just take those windows coordinates in pixels and use some simple formulas to transform the ranges [0, pixel_width] and [0, pixel_height] into [-1,1] and [-1,1], and that's it.

If you want to actually know where those mouse clicks end up on the 3D world, that is not really possible unless you specify the depth. If you add a depth value, then you can simply invert the projection matrix (which you can obtain with glGetFloatv(GL_PROJECTION_MATRIX, &m);

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

>>Heard people say c# for big programs,

May I suggest that maybe those people only programmed very small textbook-example-style programs in C++, and then made from "big programs" in C# and found it pretty easy to do. They probably also say "big programs" to mean GUI programs. C# is a RAD language (Rapid Application Development), it isn't surprising, and expected, that people would find it easy to do GUI programs in it, and, as beginners, would be pretty impressed with how "big programs" can be developed rapidly and easily and thus, recommend C# for such tasks. There is probably some truth to it, but, generally, you should not trust some random guys' opinion. You should trust empirical evidence, or, if that is not available, expert opinion (not hear-say or random people).

>> c for fast programs

C is a smaller programming language and thus, it is often more appropriate for very modest hardware (like embedded systems). This may lead some people to think that it is faster, but that is a myth, routinely debunked. C is more light-weight and with less features. Nowadays, applications or systems that actually _require_ the light-weightness of C (or similar languages) are very rare (at least, I think..), but there is an enormous amount of legacy code (e.g. pretty much all major operating systems for example!). Under most benchmark tests out-there, C and C++ are essentially equal in speed and both the fastest out-there (with Java, about 70% slower, and the rest …

iamthwee commented: Good advice and tightly written up. +15
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I expect that the * operator doesnt try to calculate log() if w=0,

C++ cannot make those kinds for simplifications, because operators can be overloaded and thus, it cannot really know that a variable is 0, nor can it assume that 0 * anything = 0, because it might not if you overloaded the * operator to behave differently. C++ will evaluate both operands of the multiplication and then evaluate the product, whether one of the operands is zero or not. And, of course, evaluating a log() function is very expensive and so, it is not surprising, in fact expected, that checking if w == 0 will speed things up quite a bit.

>>But it is now slower! Why?

That's sort-of unexpected. I would not expect this simplification to increase performance much if at all. But if it is slower, there has to be something else going on. What is your test program that tells you this is slower? I would suspect you are inadvertently doing a copy of your "shell" object (which increased in size and thus a bit slower to copy).

When it comes to micro-optimizations like these, the first priority (after compiling with the highest optimization level) is to get rid of any useless transcendental expressions (like log(), exp(), cos(), sqrt(), pow(), etc.) because these are expensive to compute. For example, often, you can get rid of a sqrt root (for example, when computing the Euclidean norm, or distance) if you simply use …

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

remove the -D option

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

If you are going to run this on linux only, I think that the following should do the trick quite well (it works on my computer at least):

#include <stdio.h>

int main() {
  FILE* f_in = popen("ping www.google.com -D -c 4 | grep mdev", "r");

  int rs1 = 0;
  int rs2 = 0;
  fscanf(f_in,"rtt min/avg/max/mdev = %d.%d",&rs1,&rs2);

  pclose(f_in);

  printf("obtained the following seed: %d.%d\n", rs1, rs2);

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

>>To be fair, that's not a common occurrence. I've been writing C++ for nearly two decades now (above average code, in my opinion), and not once have I needed to completely swap the originally chosen container class with a different one.

I guess experience differs. Maybe I have a more cowboyish way of doing some things, but it's not all that uncommon for me. I have done so several times in the past (e.g. for marginal cases where I'm not entirely sure if a vector or list or deque is the more efficient one, so I just test them all on the same generic algorithm that I am doing). I guess, if you are clever enough to always know beforehand which is better, you won't need to do that (but I'm not that clever).

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

Here is a simple example using std::vector:

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

int main(){
	vector<int> tele(32); //initialize to hold 32 integers.
	for(int i = 0; i < 32; ++i) {
		tele[i] = i;
	}
        for(int i = 0 ;i < 32; ++i) {
  	         cout << tele[i];
        }
	system("PAUSE");
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There is a ton of randomness on the internet. You could ping some known website(s) and record to RTT with micro-second precision (which is what most ping programs will give you). That should be random enough for any purpose. Similarly, you can initiate a TCP dump and record the IP packet's ID field of the "first" incoming packet. On a *nix machine, all you need to do is do a few system calls to "ping" or "tcpdump", and parse the output string or file redirection. That should be simple enough to do.

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

I don't understand how your code does compile, it shouldn't. Here are some comments and errors:

class Telegraph{
public:
  Telegraph(){
    int const size = 32; //make this value a static const data member.
    int *telegraph = new int[size]; //telegraph is a static array, this should not be allowed.
  }
	
  ~Telegraph(){
    delete[] telegraph;
  }

  void setTelegraphValues(int *value, int arrayIndex){
    telegraph[arrayIndex] = value;
  }

  int *getTelegraphValues(){
    for(int i = 0; i < 32; i++){
      return telegraph[i];       //this will return only the first element of telegraph, and will stop there.
    }
  }

private:
  //Here, you declare a static array of pointers to integers. The size of the 
  // array should be determined from the initialization list {, , ,} following it
  // but you have no such list (and can't have one for a non-static data member), 
  // and thus, the compiler should not allow this.
  int *telegraph[]; 
};

Now, I am not sure of your intent. My best bet is that you are trying to store an array of pointers to integers. In that case, here is a more suitable implementation using a static array:

class Telegraph{
public:
  static const int size = 32;

  Telegraph() { }

  void setTelegraphValues(int *value, int arrayIndex) {
    telegraph[arrayIndex] = value;
  }

  int *getTelegraphValues(int i) const {
    return telegraph[i];
  }

private:
  int *telegraph[size]; 
};

However, the main function also has major problems. You are storing pointers to integers in your array. And your main function is setting all the array elements to point to the …

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

Ok, so, you mean what is the difference between:

for(GlifPtrVec_t::iterator it = m_Array.begin(); it != m_Array.end(); ++it)
  delete *it;

And:

for(int i = 0; i < m_Array.size(); ++i)
  delete m_Array[i];

You should think of iterators as pointers, that is what they are meant to mimic in a generic way (and they might often be actual pointers). So, say that m_Array_ptr is the raw bits pointer to the start of the array contained in the vector (with type char*), then the two loops translate to this:

char* it = m_Array_ptr;
while( it != m_Array_ptr_end ) {
  delete *it; 
  it += sizeof(Foo*); //assuming Foo* is the type contained in the vector.
};

and:

int i = 0;
for( i < m_Array.size() ) {
  delete *(m_Array_ptr + i * sizeof(Foo*));
  ++i;
};

The former (with iterators) will involve, in each iteration, one condition evaluation and one add-and-assign operation (with a fixed size value). The latter will involve, in each iteration, one condition evaluation, one multiplication, one addition, and one increment (which is basically the same as add-and-assign). It's pretty obvious which is the fastest.

On a style point of view, both are totally fine in the sense that all programmers are very familiar with either styles, and many use a mix of both. But generally, for good practice, it is preferable to use the iterator-based version. The reason is simple. If your loop is not doing random-access, you should stick to a sequential-access format. Obviously, if your loop …

NathanOliver commented: good info +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You forgot the DirectGraph:: .

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

>>The most complicated functions would be trig functions.

You mean like this: cos(x) - x == 0; . Even something as simple as that essentially requires a numerical, iterative root-finding method to solve for the single unknown x. Just put together a little Newton-Raphson root-finder and it should work quite fast. As mentioned before, you could use GiNaC too, and do as follows:

#include <ginac/ginac.h>
using namespace GiNaC;

class Foo {
  private:
    symbol x, y;
    ex expr;
  public:
    struct unknown { };

    Foo() : x("x"), y("y"), expr( cos(x*y) - x - y ) { };

    double solve(unknown aX, double aY) {
      return fsolve(subs(expr,y==aY),x,-3.14,3.14);
    };
    double solve(double aX, unknown aY) {
      return fsolve(subs(expr,x==aX),y,-3.14,3.14);
    };
};

Or something similar to that (I'm not so familiar with GiNaC). And, the solve functions will be the same for any derived class, so you probably won't need to re-implement it.

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

>>is there any advantage/disadvantage to doing everything as a template?
Advantages:
- You get truly generic, expendable implementations.
- You suffer no run-time overhead (and often a speed-up).
- Policy, Traits, and Concepts are much more flexible than base classes or interfaces in OOP.
- Inversion of Control (IoC) can be implemented with no overhead.
- Template specializations and special overloads allow you to write case-specific implementations, thus, improving performance.
- Etc. there are many more that I am forgetting.

Disadvantages:
- The implementation (or definition) of all algorithms and functions have to be distributed with the library (you are forced to provide an open-architecture library, you cannot have pre-compiled libraries).
- Increased compilation times.
- Code bloat, both in terms of having to often mix declarations and definitions, and in terms of creating larger executable with much "duplicated" code (although you are not duplicating that code yourself, the compiler does).
- It is more difficult to achieve run-time polymorphism (requires OOP wrappers).

>>Is there any overheads with writing everything as a template?
No. Except for increased compilation times, but the run-time code will be as efficient or more efficient than any non-templated procedural or OOP equivalent.

>>IS there any time it should be avoided?
If you can suffer the disadvantages mentioned above, then NO.

>>Or is it good practice to write everything as a template unless otherwise needed?
It is never …

eskimo456 commented: very helpful fast reply +1
jonsca commented: I always learn good things from your posts +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I may be wrong here, but isn't the CPM simply solved by formulating the problem as an Action-On-Arc (AOA) graph. Then, you just solve for the solution using a standard shortest-path algorithm (evidently, you multiply the costs by -1 to get a longest-path algorithm). You can, for instance, use the Boost Graph Library which includes several shortest-path algorithms including Dijkstra, A*, Bellman-Ford, etc. You can even export to Graphviz and get a visualization of the graph.

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

Well, first of all, lets get rid of the obvious solutions (that you have ruled out):
1) You can use a symbolic math library. Like GiNaC. Enter the formula as a string expressions, substitute the known variables and ask it to solve for the value of the unknown(s). But the engine will have to do its work at every query, and typically, symbolic math engines are very slow, because this type of work is hard for a computer to do (but pretty easy for a human).
2) You can use a simple root-finding method (like binary search, fixed-point, secant, Newton-Raphson, etc.). That is simple as hell to do, but it is iterative and thus, subject to all the issues of getting a good initial guess, divergence, etc.

Besides using one of the above, I think you are out-of-luck my friend. Unless you have some sort of predetermined structure (as suggested by firstPerson, e.g., you know it is linear or polynomial of some order), there are no general way of starting from an equation in terms of a few unknowns and automatically generating solved solutions from any possible unknown of the equation. I mean, if there was such a thing, there would be far less mathematicians in the Universities! There is no real way to avoid having to enter equations for each case (whether you enter them in a switch-case, as elements in a look-up table, or whatever, it will boil down to the same thing).

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

I doubt that any ABM library is able to provide the kind of performance needed for an image processing task (they don't tend to be that stream-lined, or provide the kind of muscle power needed).

If I were you, I would be looking more towards parallel processing frameworks. Like OpenMP or TBB (Intel's Thread Building Blocks, if you have the funds for it). Because, it seems, in your application, the main thing is to do concurrent processing, the agent-based part is accessory. ABMs are used to develop emergent complexity from the interaction of simple agents, it isn't tailored for high-performance parallel processing, it just isn't the right tool for that. There is significant overhead associated to ABMs which you should only cope with if you have a strong motivation for swarm, emergent behaviours. If your application is simply about doing independent processing concurrently, you don't need to suffer that overhead if you go for simpler parallel computing or distributed computing models with much less overhead.