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

Ok... please post the relevant code. Have you tried to figure out the exact point where the program crashes?

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

All you need is to rewrite the value with 2 digit precision after the dot.

Look at setprecision. There are examples that do exactly what you need.

Just read the numbers from the input file, and write them to the output file with the setprecision functionality.

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

The STL stands for Standard Template Library. Like any other template library, it is a header-only library (except for some low-level things, maybe). You already have the source if you have the headers, just look for them. Under linux, they will be either in /usr/include/c++ or /usr/local/include/c++. Under windows, it will depend on your compiler's installation, should not be very hard to find (make a file-search for any one of the STL header files).

Otherwise, you can get the STL source from SGI (original developer of STL).
Or, you can get GCC's implementation of the standard libraries as part of the source distribution of GCC.

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

Is there a reason why you are using such an old compiler? I'm sure that red-hat has some more recent package of GCC available. And yes, you need the function AccumSq to be declared sometime before you use it.

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

So.. $ sudo zypper in codeblocks didn't work?

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

>>What is the point of having a non static const in your class, just asking to learn, no offense.

If you have a piece of data that is constant for the life-time of an object, and is unique to the object, then it could sense to have it as a non-static const data member. However, I cannot think of an example where you would need this, and I have never seen it either. Moreover, if you encapsulate the data member, it cannot be modified by code external to the class anyways (unless it is part of @sergent's code ;) ), and marking a non-static variable as const doesn't improve performance either. So, I would agree that it probably isn't very useful and certainly not common to have non-static const data members (except for references which are sort-of implicitly constant).

>>Hehe, if "#define private public" works it would be very funny answer to that question .)

First, it does work. Second, needless to say, it is very dirty. Finally, it is a good answer to the question (at least a part of a complete answer), where, of course, it would be accompanied by "..and, of course, I would never ever consider writing such evil code.".

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

The problem is simply that your () operator in the LowestPrice is private (which is the default access right for a class). So, you should do either this:

class LowestPrice
{
    public: //notice "public" here.
	bool operator () (const PriceInfo& a, const PriceInfo& b) const
	{
	return a.Low < b.Low;
	}
};

Or this:

struct LowestPrice //notice the "struct" here, which has "public" default access rights.
{
	bool operator () (const PriceInfo& a, const PriceInfo& b) const
	{
	return a.Low < b.Low;
	}
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>If we say rvalue, isn't it going to change in C++0x

Not really, C++0x introduces an additional type of reference, i.e. a rvalue-reference (with the double ampersand). It doesn't change the fact that you cannot bind an rvalue to a non-const reference, in fact, it is very useful because it allows overloading based on rvalue/lvalue distinction, which is not possible in C++98/C++03. As follows:

void foo(double& d) {
  //some code that uses d as a reference to an lvalue.
};

void foo(const double& d) {
  //some code that uses d as a const-reference to an lvalue.
};

void foo(double&& d) {
  //some code that uses d as a reference to an rvalue.
};

The above is not possible in the current standard because, since you cannot provide the third overload, if an rvalue is passed to the function, it will bind to the const-reference, and you cannot distinguish between a const-ref to an lvalue or to an rvalue. So, you cannot safely take the address-of the reference because it could be an address to a temporary. In C++0x, you can be sure that the const-ref will be referring to an lvalue (otherwise the rvalue-ref overload would have been selected), and thus, taking the address-of is safe.


>>Can you please give an example for that?

See this gotw article, under "The Language Lawyer" (the others could be filed under what I mentioned as "other nasty hacker's tricks").

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

smallSet is a type, not a variable. You need to make a object of that type to be able to use it, like you do with "prices".

Also, the loop that starts at line 22 does not make sense. Given how it is, it will start at begin()+1 and end at end(), when it should be from begin() to end()-1. Why not use the idiomatic loop:

for(std::vector<PriceInfo>::const_iterator it = prices.begin(); it != prices.end(); ++it) {
  //..
}

And, anyhow, you have a stray semi-colon at the end of Line 22.

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

Q1)Can we delare constant data members inside a class?

Yes. As a static member with inline initialization if it is a integral type or with a definition statement outside the class if it is not an integral type. As a non-static member, you need to initialize the data member in the constructor's initialization list, and it disables default, compiler-generated copy-constructor and copy-assignment operator (note that references are an example of a data member that is implicitly constant, since it cannot be re-seated).

Q2)does friend function violates encapsulation/data hiding?

No. Not anymore than member functions. Abusive use of friend functions, just like abusive use of "protected" access rights and abusive use of member functions, can violate encapsulation.

Q3)what are the types of polymorhphism you know?

Static and Dynamic. I assume you are not meaning the different types of uses of polymorphism, these are countless. The different types of polymorphism are static, which is realized at compile-time using function and class templates with some generic concept that specifies the expected abstractions and traits ("concepts" in static polymorphism are analogous to "abstract base classes" in OOP), and dynamic, which is realized at run-time using virtual dispatching based on the object's virtual table.

Q4)why do you need virtual functions?

To implement virtual dispatch (function calls which are dependent on the run-time type of the object(s)).

Q5)Can we do something like\
int & = NULL;

No. No. No. 1) I cannot assign or copy-initialize an …

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

>>Is it mandatory to Use static functions for a Singleton class.

I guess you could make a poor implementation of a singleton without a static function, but it is not usual or recommended. Usually the two options are a static function or a free function (non-member function).

The implementation that alwaysLearning0 posted is not only simplified but also generally broken. A more usual and robust implementation is the following:

In singleton.h:

template <typename T>
class singleton_impl {
  private:
    static T& get_instance();
  public:
    operator T&() { return singleton_impl<T>::get_instance(); };
    T& operator*() { return singleton_impl<T>::get_instance(); };
    T* operator->() { return &(singleton_impl<T>::get_instance()); };
    operator T const &() const { return singleton_impl<T>::get_instance(); };
    const T& operator*() const { return singleton_impl<T>::get_instance(); };
    const T& operator->() const { return &(singleton_impl<T>::get_instance()); };

    //usually some additional utility, like operator overloads.
};

In singleton.cpp:

#include "singleton.h"

template <typename T>
T& singleton_impl<T>::get_instance() {
  static T inst;
  return inst;
};

In A.h:

#include "singleton.h"

class A {
  private:
    A(const A&); //non-copyable
    A& operator=(const A&); //non-assignable (note: these two can be done also by inheriting from boost::noncopyable)

    A(); //provide a private default constructor.
  public:
    typedef singleton_impl<A> singleton;
    friend class singleton_impl<A>;

    void print() const;
    //.. whatever implementation of A.
};

Then, in A.cpp:

#include "A.h"

#include "singleton.cpp"

#include <iostream>

template class singleton_impl<A>; //explicit instantiation

A::A() {
  //...
};

void print() const {
  std::cout << "Hello World!" << std::endl;
};

//...

Finally, you can use it as:

#include "A.h"

int main() {
  A::singleton s;
  s->print();
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

From the print out, it is clear that the stride is correct, so the use of M_pGSLData->tda is not going to solve the problem, although it is recommended to use that value and not assume another (like M_uCols). Clearly, the value of the pointer M_start is being set to the value 1, sometime between the first and second printout. First, I would not recommend that you duplicate the matrix information (like start-pointer, size1 and size2), this will inevitably require some assumption about how GSL deals with the data, or way too many updating of the state, and there is no tangible gain to doing this. Use the data in M_pGSLData directly as much as possible.

As for why your M_start pointer gets overwritten with the value 1, that's hard to tell without complete code. You must identity what objects are directly next to the m_1 object in memory and how they could write memory out-of-bound that would spill over to the m_1 object.

Also, remember that GSL is pretty notorious for having memory corruption problems because of lot of its code is hand-made translations from fortran by not-so-good programmers (good scientists, but not good programmers), which is very error-prone. We almost destroyed a robot once because of a memory corruption problem that was internal to some GSL code (guess why I don't ever "just use" GSL code anymore, I always carefully scrutinise it before).

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

hash_map is deprecated. You should use unordered_map instead. It is a C++0x standard feature, but most compiler vendors support it already, without having to compile with the C++0x experimental support flag. Other than that, I am not familiar with std::hash, so I don't know how to solve your problem. But std::hash should be in the <utility> header.

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

I'm not familiar with serialization yet, so forgive me if I state something wrong. Basically, if I understand correctly after perusing a Boost example, what this permits is that the state of a class object is written to file. This file can then be used at a later time to recover that state of the object. So, that would mean in my predefined planets, I would serialize an object of the Planet class with all the settings that pertain to my predefined Earth, for example. That would yield a file that basically describes all the settings of the Planet class to make it a predefined Earth, e.g., mass, atmosphere, gravity field etc. Then, through deserialization at a later stage, the state of the predefined Earth can be recovered for use. Is that correct?

That is correct.

Given that that's correct, is the idea that you serialize your object once and store the generated file in the library so that users only have to deserialize? Or do you serialize and deserialize everytime you run code in the library?

The idea is the store the generated file so that the user only have to deserialize. Of course, you can also provide a program that generates all the predefined model files as well, such that the user can generate fresh ones if needed.

why is this better than storing the serializable data in the class itself?

Because it does not put "magic numbers" in your code. If you are not happy …

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

The parameters of a function only exist as long as the function is executing. When the function has finished, its parameters disappear. They don't need to be "reset" before the second call. When you call the function, you provide the arrays it should work on, and the second time you call, you just provide different arrays it should work on and it will work on those arrays instead. Function parameters are not global variable that exist all the time, they simply take the values that are passed to the function when it is called, then can be used inside the function, and when the function is over, these variables disappear (literally). In your specific case, the parameters are arrays, so they are passed as pointers to the first element of the array, at every call, they are assigned to point to whatever array you provided when you called it.

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

First, static local variables are created once, the first time control flows over them. So, for a singleton (which is what CVSystemDLL is) you would only need this as implementation of pInterface->m_pFactory:

static CVSystemDLL* ret = new CVSystemDLL;
  return ret; //let ret be implicitly cast to void* (don't use '(void*)ret')

Furthermore, dynamic memory allocation is not needed, you could do:

static CVSystemDLL ret;
  return &ret; //let ret be implicitly cast to void* (don't use '(void*)ret')

Now, the observation about the (void*) cast is valid at the call-site as well. You should not use the (void*) to cast pointers because the behavior is to perform a reinterpret_cast which has undefined behavior, by definition (C++98 Standard clause 5.2.10/3). The same rational goes for casting the void* back to IVSystemDLL*. This sequence of casts has undefined behavior, especially if it is across a module boundary. To perform the call-site cast, you need to use static_cast, and that's the only option.

VSystemDLL *pSystem = static_cast<IVSystemDLL*>(Plat_GetInterface( "vsys.dll", SYSDLL_INTERFACE_VERSION ));

Finally, what happens in Plat_GetInterface? I suspect you are doing this:

HMODULE dlhdl = LoadLibrary("vsys.dll");
  typedef void* (*InterfaceFactProc)(char*);
  InterfaceFactProc get_fact = (InterfaceFactProc) GetProcAddress(dlhdl, "InterfaceFactory");
  typedef void* (*InterfaceFactoryFuncPtr)();
  InterfaceFactoryFuncPtr fact = (InterfaceFactoryFuncPtr) get_fact();
  void* ret = fact();
  FreeLibrary(dlhdl);
  return ret;

If this is what you are doing, then I am not at all surprised that you are getting an access violation. You cannot use anything that has been obtained from a DLL after you have freed it. That includes pointers to exported functions …

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

The form std::string test("hello"); is called a "direct-initialization". This is essentially a direct call to whatever constructor matches the parameters given. Direct-initialization is the only accepted form in a class constructor's initialization list.

The form std::string test = "hello"; is called a "copy-initialization", because it is meant as a initialization of the new object with a copy of another, and the standard does not permit much else (this will be expanded a bit in the upcoming standard). You will find the relevant clause in the C++ Standard 8.5/14. What is special about the copy-initialization can be summarized (extract from the standard text) to:

If it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression(s) as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.

Otherwise, user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed.

In plain english, it means that the right-hand-side needs …

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

>>Why do you ask?

Because it is a homework problem in which the prof said not to use STL algorithms, I guess. This is a typical homework problem to teach people how to do basic string or array manipulations. Ironically, it is also a typical interview question to see if people know STL algorithms well, and can avoid implementing trivial algorithms when they are already available in standard libraries.

@OP:
Did you try anything? Post some code and we can start from there. If you just need a solution to the problem, you would be happy with Narue's code. If you need a solution to the problem without STL, then somebody wants you to learn something, we want you to learn something, you should want to learn something, and thus, you should try to solve it yourself. If you need inspiration, try to just read on how std::unique works.

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

First, in response to thelamb and JasonHippy, dynamic_cast is not needed in this case, and if you have created the CVSystemDLL class in a separate DLL, then dynamic_cast will not work in the exe (if that is what is being done).

Second,
>>If it's related to the problem, the code that I'm using has the code to create new CVSystemDLL's in a DLL. And the code that gets one, and calls main is in an EXE, would that make a difference?

It can make a huge difference! There are several things that could be problematic when doing this. Here are a few sources of problems (DLLs and EXEs are referred to as "modules"):
1) On windows, modules have separate heaps. This means that memory allocated in one module cannot be deallocated in another. If your class does such a thing, expect a crash or access violation or heap corruption. This also means that anything that is created by a module will be invalid as soon as the module is un-loaded, if you try to access them, you will get an access violation because those pointers will no longer be pointing to memory that is in the virtual addressing space of the application.
2) Modules which are not compiled with the exact same compiler with the exact same compiler options (optimizations, debug symbols and hooks, etc.) cannot be expected to be compatible, as far as C++ features are concerned (C functions and types are OK). This …

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

Would I then have to overload the constructor for every single combination of the option parameters? Or is there are way by which I can just have one long parameter list in the constructor, and that if the user doesn't pass a specific optional parameter, that the compiler knows how to parse the rest of the parameter list using just one constructor definition?

This is exactly what the Boost Parameter Library does. You can pass parameters in a simple "identifier = value" comma-separated list, where order doesn't matter, and you can make any of the parameters optional with some default value. Normally, you should be able to program a single function, you won't need overloads. Of course, it is somewhat verbose when you create a function to be called this way because it requires using several MACROs that are very complex under-the-hood (uses Boost PreProcessor Lib.). But, the point is that it makes the call-site syntax simple and clear (which is the point of writing library code: put all the complex construct under-the-hood to expose the simplest and clearest possible interface to the user).

The way I've set things up now is that the user creates the predefined Earth, with all the preloaded settings, and then uses a set-function to reset the value of the mass. Do you have a suggestion as to a better way to go about doing something like this?

Oh yes. There are better ways to do this. Personally, I just use serialization …

m4ster_r0shi commented: This is an awesome post. +5
alwaysLearning0 commented: another great post +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I have not heard or seen any book or resources online which are a "generic guide to using external libraries in C++". I think the problem with writing such a guide is the shear amount of possibilities. There are APIs, header-only libraries, source-file-only libraries, different programming paradigms, some have special build tools (like qmake for Qt), etc.

Generally, you need to follow the instructions on the website of the library as best as you can. And remember that some libraries are not extremely well-written, and the author(s) might be overstating the portability of the code (if you hear things like "my lib should compile with any standard C++ compiler", don't trust that because "should compile" means it wasn't really tested, and a "standard C++ compiler" doesn't really exist in practice).

To add to JasonHippy's post, if using binaries, make sure that the binary was not only compiled for the correct platform, but also that it was compiled with the same compiler that you are using. Be aware that there are special steps to take if you need to use a binary that was compiled with another compiler, and it may not be successful at all, in which case, you need to recompile from source code.

A few more pieces of advice:
1) Don't introduce external dependencies which only solve trivial problems, prefer to write your own code from scratch if it's simple enough. I'm not saying you should reinvent the wheel all the time, I'm simply …

kvprajapati commented: Good post. +15
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Examples of real serialization methods or libraries are:

Boost.Serialization

Google's protobuf

JSON

Serialization requires two things: a way to deconstruct an object tree into a buffer from which the tree can be reconstructed (which usually requires some form of type identification), and a way to read and write the buffer that is compact, system-agnostic and easy to parse (e.g. XML, JSON, protobuf, etc.).

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

>>wc -l = lines in a file including blank lines on nix

Actually, I didn't know that (I don't know all *nix commands). I guess you are referring to my mention of sloccount to count the lines of code. This program is very different (try it), it doesn't just count the number of lines in a text file, it recognizes which kind of source code it is, disregards the comment-only lines (for whatever way comments are marked in the programming language of each file), disregards empty lines, and produces a true LOC count of for almost any programming language. It also produces nice little statistics and folder break-downs. It also evaluates the man-year measures and cost of software. So, it is no equivalent to "wc -l", if you count empty-lines and comments in your LOC count, you are grossly overestimating it.

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

>>What do you mean here?

The normal semantics of stream operators, as I understand them, is: cout << str : A string is added to the output stream. cin >> str : A string is extracted from the input stream.

The important part is "added" and "extracted". For operator >>, I expect data to be take out of the left-hand-side to overwrite the right-hand-side variable. For operator <<, I expect data to be copied from the right-hand-side to be "appended" to the left-hand-side. So, str >> cout , if you apply the conventional semantics, would mean that you take an output stream object out of a string object to replace cout. That doesn't make sense, the semantics have to be inverted in order for this operator to mean what it does.

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

>>Apparently, you're not allowed to do this.

I doubt that very much. What is your source for this information?
As far as I know, and I'm pretty sure of this, there is nothing wrong with that loop. You are certainly allowed to modify the value element (second) with a map iterator (of course, the "first" part cannot be modified, it is const). Especially considering the fact that the alternative (the loop you showed) is far less efficient, it runs in O(NlogN) instead of O(N) for the original loop.

The problem that you are having is memory corruption, and one of the very annoying things about memory corruption problems is that small changes in the code changes the memory layout a little bit, and makes the problem "invisible", but it is still there. This is the case for your code. You took a perfectly valid piece of code, replaced it by another perfectly valid piece of code, and, all of a sudden, the problem disappears. It didn't disappear, the memory corruption is simply no longer affecting anything critical. But this is a time-bomb. There is no telling what is being corrupted and what effect that might have (at best, it does nothing, at worse it corrupts the results of your calculation). And, more importantly, you could make another trivial modification to your code, and the memory corruption problem will come back. This is not over.

You must review the code very carefully, and try to spot any …

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

This really is eating me inside because I remember seeing the exact same symptoms in a project. It was a very long time ago, and I'm having trouble remembering what the problem was, but I do remember it was painful to find. I can at least say a few things:

First, it is not a corruption of the vtable, because you mentioned that you did inspect the this pointer within the called member function, you would not be able to reach that point if the vtable was corrupt.

Second, from your description, there is no reason why this shouldn't work. There is something you neglected to mention. The devil is in the details.

You must first wield out any possible API and ABI mismatch problems:

First, make sure there are no old versions of the source code or header files that are remaining in your code-base, they are liable to silently corrupt the build.

Second, make sure that you clean and purge all your binaries and that you make a fresh build of the entire code-base. It goes without saying that all the code has to be build with the same compiler and the same compiler options.

The purpose of the above two steps is obviously to make sure that you don't have things like function prototypes in a header that doesn't correspond to the compiled code but links to it anyways (yes, it is possible). The second problem is ABI mismatch, meaning that …

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

LOL! @WaltP: Pretty good timing for this thread! Don't you think?

Yet another example of "I compile this with DevC++ and it doesn't work, but it works with other IDEs like ..".

@OP: I agree with both posters. Stick to one generation of C++ code, that is, the current standard, and standard-only. Follow WaltP's recommendation on that. Don't follow example codes or tutorials that are too outdated or non-standard (and seeing "iostream.h" or "conio.h" is a pretty good indication of that). But I would also recommend you pick another IDE besides DevC++, like Code.Blocks or Visual Studio, and try to pick a recent version.

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

>>By code snippets I mean pressing Tab at the right time and generating a stub for an event handler, an if-block, or something else,
Yeah, I know. I understand you can save typing with that. I personally find it annoying, and rarely useful. But I can understand that it is helpful for GUI code, because GUI library often require a bit of special code.

I do, however, value "code-completion" very much. This is when you type the first few letters of an identifier and the IDE gives a list of possible matches, and simply pressing tab or enter puts the rest of the name. That is very useful because it allows you to have long and descriptive variable names without additional typing effort. And, I would say, this is the primary reason that I use an IDE to code and not an enhanced text editor (like emacs or vim). The problem is, my code is heavily templated (generic programming and template meta-programming) which makes it very difficult for code-completion to work in a timely fashion. So far, I have only found KDevelop 4 to be able to keep up (both VS and Code.Blocks are just too slow and resource-hungry when code-completion is enabled when coding my stuff).

>>BTW, what kind of setup are you using,

Basically, quite opposite to yours. I code almost exclusively on Linux (Kubuntu 11.04). I use KDevelop as an IDE. I use a rolling version of

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

What about code snippets? Refactoring tools? I actually use C++/CLI too. A task list? Disassembly output? Class Diagrams? I use C#, F#, and sometimes VB also, does Code::Blocks support these languages? Why would I want to switch to an environment that doesn't have a drag & drop designer, that seems like a pretty stupid thing to do when using C# or VB. Also, C++/CLI is a pretty powerful language, allowing me to use the .NET framework as well as native C++, I don't really want to do without.

Ahh. Much to learn, you have. My young Padawan...

On a more serious note, different tasks require different tools. You seem to be happy with the tool you have, for the tasks that you do. It doesn't mean others would find VS appropriate for theirs. For example, by my perspective:

>>code snippets?
Useless. I need neither example codes, nor pre-made start-up code, I don't think any experienced programmer would need them.

>>Refactoring tools?
Refactoring tools are over-rated. If your library is so big you cannot refactor it by hand, don't do so. If your library is not too big, refactor by hand, the result will usually be better (although I heard VS2010 is pretty good for automated refactoring).

>>C++/CLI
If not doing .NET, this is useless, and a nuisance.

>>task list?
An old fashion TO-DO list works fine, a doxygen-generated TODO list is also good. I file this under "bells and whistles".

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

>>Could the reason he's wasting his time is to learn to program,

Maybe it is to learn that trying to outdo the compiler is more often than not a waste of time. I think that is a very valuable lesson, makes you focus on the important things. I agree that if you are learning the basics of writing functions, rewriting built-in math functions is as good as anything else (especially since you have a "correct" function to compare your results against). But citing "for the purpose of learning" to justify anything is a bit lame because everything can be justified for its learning-value, so it goes without saying, as far as I'm concerned. And learning-value is very subjective, so I prefer to exclude it from my judgement of the usefulness of doing something in programming. So, when I say "waste of time" it's implied that I mean "waste of time (except if it has learning-value to you)", you could attach that caveat to every one of my statements about the usefulness of anything in programming.

Reimplementing a built-in math function will teach you, in order:
0) how to compute a math expression.
1) how to write a function.
2) how to call a function.
3) how to test a function for correctness.
3a) basic issues of numerical analysis (round-off errors, numerical stability, etc.)
4) that built-in functions are very efficient compared to hand-rolled code.
5) that beating the performance of a …

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

>>Anyone can share their knowledge here??

First of all, don't expect this approximate series to give reasonable results for x > 1.0 (and less than -1, of course), there are theorems that prohibit that. Also, you need to compile with highest optimization level for this kind of applications.

I actually tested your code, and some with my own improvements, to see if it actually outperformed the built-in log() function, and it does, by 40% (with optimization at max). With no optimizations during compilation, your method outperforms the built-in function by 25%, but I made a slightly better version which outperforms the built-in function by about 75%. That version is this (simply reduces the number of multiplication to a minimum):

inline double log_approx2(double x) {
  return x*(1.0 - x*(0.5 - x*(1.0/3.0 - x*(0.25 - x*(0.2 - x/6.0)))));
};

Compiler: GCC 4.5.2 (x86_64-linux-gnu)

With no optimization, I get:
built-in function: 10 million evaluations in 386 milliseconds.
your versions: 10 million evaluations in 280 milliseconds.
my improved version: 10 million evaluations in 100 milliseconds.

However, with optimizations turned on to the max (-O3), I get:
built-in function: 10 million evaluations in 10 milliseconds.
your versions: 10 million evaluations in 6 milliseconds.
my improved version: 10 million evaluations in 6 milliseconds.

Which goes to show that the compiler can do a lot more optimizations than you can. Trust your compiler, don't waste your time doing micro-optimizations like this, unless you have solid …

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

@m4ster_r0shi:
>>Something like this would work fine: (overloading operator >>)

I should point out that operators >> and << are left-associative, so overloading operator >> like you did is going to be problematic when combining several calls. So, this is not recommended, especially since it inverts the normal semantics of C++ stream operators.

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

The problem is clear, and has been answered already. std::bad_alloc is the exception that is thrown when dynamic memory allocation fails. Generally, the most likely reason why dynamic allocation can fail is because it would require more memory than you have available on your computer. When allocating a 150,000 x 150,000 array, it comes to no surprise that you run out of memory, that's about 84 Gb (I think that a system which can produce or at least emulate 84Gb of contiguous RAM memory is very rare).

Try to avoid needing such a large amount of memory at once in your program.

BTW, to catch the exception, you do:

#include <iostream>

int main() {
  try {
    float * huge_array = new float[150000 * 150000];
    //...
    delete huge_array;
  } catch(std::bad_alloc& e) {
    std::cout << "Could not allocate the required memory, failed with error: '" << e.what() << "'" << std::endl;
    return 1;
  };
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Definitely a bunked include path

Try to locate the header files manually in the hard-drive. Possibly, add all the sub-directories to the include path list. Make sure you have all the dependencies met.

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

>>but unfortunately, we're using Windows V_V.

If I had a dime for everytime I heard that...

You can actually get pdftotext for Windows as well.

And libtranslate is an open-source library, so you can try to either port it to windows or just grab the relevant parts of the source code.

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

If under Linux, you can use the "pdftotext" command (from package "poppler-utils"). Then, you can use "libtranslate-bin" package to install a text translator program and use it with "translate-bin" command. So, your problem can be entirely solved by:

$ pdftotext my_file.pdf my_file.txt
$ translate-bin -s google -f en -t fr my_file.txt > mon_fichier.txt

You only need to wrap these two calls in a shell, and you are done.

Ancient Dragon commented: you made it too easy :) +17
alwaysLearning0 commented: thats great! :) +3
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You can use Qt. Do this in a terminal window:

$ sudo apt-get install libqtcore4 libqtgui4 libqt4-dev qt4-qmake qt4-doc qt4-demos qt4-assistant qt4-designer qtcreator qtcreator-doc

Some of the above might be redundant, but what the heck. And most of it is probably installed already as part of the distro or as dependency of other, already installed packages (since Qt is pretty wide-spread in Linux GUI world).

At that point, you should be able to make a project like this one:

#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget window;

    window.resize(250, 150);
    window.setWindowTitle("Simple example");
    window.show();

    return app.exec();
}

Save it to file "simple_example.cpp", go to that directory in a terminal, and run:

$ qmake -project
$ qmake
$ make
$ ./simple_example

If the above works, and it should (in the tradition of Linux being automatic and easy), then your setup is working, at least basically (you can browse synaptic for anything that starts with "libqt" for more plugins and add-ons, like opengl, sql, xml, svg, etc.). The above is just a simple example, the more usual approach is to design the GUI window using Qt Designer (by dragging and dropping GUI elements, instead of having to code everything in), save it to some .ui files, implement some event handlers (called "slots" in Qt), and create a qmake project file. It is a slightly more involved building process, but nothing to be afraid of.

There are plenty of tutorials on Qt. Like …

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

>>ok so i'll always need a default constructor even when i add other constructors

You can do both at the same time using default parameters, this is very common. For example, consider this simple class that represents a 2D vector:

class Vector2D {
  public:
    double x,y; //two data members to hold the x and y coordinates. 
    //you can have a constructor that takes the two coordinates to initialize the object with,
    // by providing default parameters ("= 0.0"), the constructor can also be called with no parameters
    // in which case they will have values (0.0,0.0)
    Vector2D(double aX = 0.0, double aY = 0.0) : x(aX), y(aY) { };
};

The above is very useful to provide both a parametrized constructor and a default constructor at the same time, also making it explicit what the default values are.

To create the objects, you would do this:

int main() {
  Vector2D obj1; //created with default constructor.
  Vector2D obj2(4.0,2.0); //created with the parametrized constructor.
  std::cout << "obj1 is (" << obj1.x << "," << obj1.y << ")" << std::endl;
  std::cout << "obj2 is (" << obj2.x << "," << obj2.y << ")" << std::endl;
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The best for C++0x right now is certainly GCC 4.6.1. If you are willing to build from source (which could be pretty hard for Windows), then you can also use 4.6.2. The current development version is 4.7.0, but it is experimental, and from personal experience with it, I don't recommend using it just yet, and it only adds a few trivial aspects of C++0x. Also, except for regex library, GCC has a pretty full implementation of the C++0x standard libraries.

I would expect that ICC is (or will be) pretty strong on the concurrency features, which is the major C++0x feature that is lacking from GCC right now. This is because Intel are pretty strong on concurrent programming.

For the last main option, MSVC 2010, I wouldn't expect it to be any decent until at least some years from now, considering the time it took MSVC series of compilers to get reasonably compliant to C++98 (about 10 years).

Moral: Be patient, remember that as we speak there is only one compiler that is fully compliant to the current standard (i.e. Comeau). You should not consider doing production code in C++0x, without build-switches to revert to the current, supported standard.

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

>>The O/S is know to be a geek's O/S.

Am I the only one who finds it ironic that, within a thread in which you try to break the parroting of "it is known that DevC++ is bad", you are parroting the idea that "Linux is known to be a geek's OS". This is indeed a very old misconception that is being parroted all over the place by people who don't know Linux (I suggest you investigate that matter for yourself). The only thing "automatic" about windows is that it is pre-installed on most PCs, the rest is just a succession of frustrating hassle and time wasted to get anything done with it. In linux, any software is just one command-line away, while on windows you need to search on the web, download a few candidates, launch the install, enter a bunch of irrelevant configurations, press "next" a thousand times, and while you're doing that, you're not doing anything else (or even worse, you have to make a trip to a computer store and buy the software and bring it home). That's not to mention constantly being aggravated by "automatic" updates and by virus protection, scanning and cleaning. Anyways, let's not start a debate on that...

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

>>CB current version is 10.5 and is distributed with gcc version 4.4.1 copyright 2009. Is that not the same as current version of MinGW without CB?

The current release version of GCC is, of course, 4.6.1 (from June 27 2011). Of course, it takes a little while longer to get working on an archaic OS like Windows (with MinGW). So, the current version of GCC on MinGW's repository is 4.5.2 (released by GCC in december 2010, and ported to MinGW in january 2011). If you compile from source, you have 4.6.2 and 4.7.0 (experimental) available as well.


>>I suspect a bunch of parrots just jumped on the bandwagon.

I do admit that I am a parrot when it comes to DevC++. But I did, like many others here, see several threads that report bizarre problems, and after suggesting to upgrade for a more recent IDE/Compiler setup, problems were fixed.

If I recall, many of the problems people encounter with DevC++ have to do with using a recent version of Windows (Vista or 7) and getting problems with crashes at execution. This is the main problem with using an out-of-date setup, you risk that the run-time libraries, headers or ABIs will be no longer compatible with the OS it's running in or the libraries it is linking to (especially when using non-microsoft compilers and run-time libraries).

As far as DevC++ being good or bad, in the context of using it when it was up-to-date, …

ddanbe commented: Nice. +14
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The answer is:
- I don't know.
- Boost.Program-options
- Boost.Date-time

Let me elaborate:

For the first problem, "IsDebuggerPresent", it is the first time I hear of such a function, I have no idea if it has or can have an equivalent in Linux. As far as I know, you do either debug builds or release builds, so there is no need for a run-time check for a debugger being possibly present. I might be wrong.

For the second problem, "GetCommandLine", I would recommend you switch entirely to Boost.Program-options for both Linux and Windows. This is a cross-platform library that will allow you to create a global object that captures, parses, and holds all data from the command-line (as you specify the possible user-inputs and capture the command-line input at the start of main()). This will be better in either cases, windows or linux.

For the third problem, I would recommend you use Boost.Date-time. Again, this is a cross-platform library which is implemented such that it takes the most precise timer available on the current platform. Basically, you ask for local_time in microseconds or nanoseconds and you will get it to the best possible precision available. You should probably switch entirely to that library for both OSes also.

As a final note, when porting code between OSes, you definitely want to take an approach like that of Boost. This means, you should wrap all the OS-specific in compact …

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

You forgot to implement the assignment operator, which usually implies implementing a swap function as well. As so:

class Street
{
private:

	int stretNumber;
	string name; 
	int numberHouses ;
	int *ListHouses ;
public :
	Street();
	Street(int, string, int);
	//Street(const  Street & otherStreet);
	Street(const  Street & Street1);
	void destroyHouses();
	void inputRoomsInHouses();
	void displayHouses();
	void print();
	~Street();

        //friend swap function:
        friend void swap(Street& lhs, Street& rhs) throw() {
          using std::swap; //include std:: to ADL
          swap(lhs.stretNumber,rhs.stretNumber);
          swap(lhs.name,rhs.name); 
          swap(lhs.numberHouses,rhs.numberHouses);
          swap(lhs.ListHouses,rhs.ListHouses);
        };

        //A copy-and-swap assignment operator:
        Street& operator=(Street rhs) { //pass-by-value (copy)
          swap(*this,rhs);              //swap
          return *this;                 //return
        };
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As m4ster_r0shi said, you can use a different comparator to get a descending order for the sorting. I would just add that you can use the standard one instead of a custom compare() function, as so:

std::sort(fitness, fitness + 250, std::greater<double>()); //the default comparator is 'std::less<double>()'

And yes, definitely, an array (or an std::vector or std::deque) will be more efficient than a list in this case.

As this is a genetic algorithm, I would recommend you use a "tournament selection" instead of using all the data. For example, say you have 250 individuals and you plan to choose the "best" 50 for reproduction. Then, instead of sorting the entire array of 250 elements, you can pick 10 tournaments involving 10 random individuals from the population, sort those small 10-individual arrays and pick the best 5. This will be much more efficient and perform very well (I know by experience).

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

That's the wrong way to do things in C++.

Here is an example of the "normal" way to write code in C++. Say you have a function called Foo() and a main() function to test it. Then, this is the way you split it:

In Foo.h, declare the function Foo(), without implementing it (just a declaration):

//first, you need some "header-guards" to avoid multiple inclusions.
#ifndef FOO_H
#define FOO_H

//declaration of the function:
void Foo();

#endif //end of header-guard

Then, in the Foo.cpp file, you need:

#include "Foo.h" //include the header for the function declarations.

#include <iostream> //include whatever other thing you need.

//here is the function definition (or implementation):
void Foo() {
  std::cout << "Hello World!" << std::endl;
};

And finally, in the Foo_test.cpp, you have a test program with a main() function:

#include "Foo.h" //include the header, not the .cpp

int main() {
  Foo();  //call the function
  return 0;
};

Then, you compile both cpp files and link them together to create the executable. With GCC, it is:

$ g++ -Wall Foo.cpp Foo_test.cpp -o Foo_test
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You can achieve something reasonably close to what you want with this:

#include <iostream>
#include <string>

int main() {
  std::cout << "Hello";
  std::string tmp;
  std::getline(std::cin,tmp,'\n');
  std::cout << "there" << std::endl;
  return 0;
};

This will just have the effect of printing the second part when the user presses enter (and it will ignore any other characters typed, but they will still display on the screen, and so will the enter character (it will make a new line)).

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

I haven't gone through the code in detail, it is too much. But it looks to me like you are doing an exhaustive search of all possible future move sequences in a chess game. I could hardly expect this to finish running any time soon. It may not be an infinite loop, just a really really long one.

Even if you decided to use this algorithm, you have to use loops, not functions. This kind of indirect recursive function calls will create very deep nesting and you will get a "stack-overflow" error, eventually.

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

CodeBlocks on windows.

KDevelop on Linux (Kubuntu). I agree with rubberman that IDEs can get in the way of effective coding (make you waste time on setting up projects and settings, and load times and stuff), but KDevelop is not one of those that do. It's by far the one I like the best, but I generally use it essentially as a text editor (i.e. I compile and debug in a terminal opened next to my IDE, but not because KDevelop doesn't provide that, just that I prefer it that way). In that spirit, the two main characteristics that I like are friendliness to third-party software (compiler, debugger, GUI designing tool, build system, etc.) and fast code completion (and code highlighting, and thus, the background, real-time code analysis required). I tend to write a lot of heavily templated code (generic programming and template meta-programming) and very few IDE code completion systems can keep up with that, KDevelop is one of them, while Visual Studio 2010, CodeBlocks, QtCreator, and Eclipse all fail miserably or are way to slow to be useful (e.g. VS2010 needs 4 of my processors running at full speed to analyse the code fast enough to produce useful code completion suggestions in due time).

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

Where are the fft and fft_rec function declared and defined? How are you compiling fft_test?

Possible solution: mark the fft and fft_rec functions as 'inline' if they are defined in a header file.

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

The const at the end of a member function means that the member function will not and cannot modify the state of the object on which the member function is called on.

A member function has a hidden parameter, the "this" pointer which points to the object on which the member function is called. In that sense, you could picture it like this:

struct Foo {
  int value;
  void Bar() {
    std::cout << this->value << std::endl;
  };
};

int main() {
  Foo f;
  f.value = 42;
  f.Bar();
};

//the above could be considered equivalent to:
struct Foo {
  int value;
};

void Foo_Bar(Foo* this) {
  std::cout << this->value << std::endl;
};

int main() {
  Foo f;
  f.value = 10;
  Foo_Bar(&f);
};

With a const at the end of the member function declaration, the above becomes:

struct Foo {
  int value;
  void Bar() const {
    std::cout << this->value << std::endl;
  };
};

int main() {
  Foo f;
  f.value = 42;
  f.Bar();
};

//the above could be considered equivalent to:
struct Foo {
  int value;
};

void Foo_Bar(const Foo* this) { //notice that "this" is now a pointer to const Foo object
  std::cout << this->value << std::endl;
};

int main() {
  Foo f;
  f.value = 10;
  Foo_Bar(&f);
};

That is the picture to keep in mind. cv-qualifiers at the end of the member function declarations are the cv-qualifiers of the object to which the 'this' pointer points to.

This was necessary in your case because once you have …