m4ster_r0shi 142 Posting Whiz in Training
m4ster_r0shi 142 Posting Whiz in Training

What do you mean you can not run it? Create an empty project, add a source file, paste the code and then
build the project. Also, try this version instead -> http://pastebin.com/1Bn12dnS (I fixed the flickering problem).

m4ster_r0shi 142 Posting Whiz in Training

I don't do graphics.

Why not? Doing graphics can be so much fun! I do graphics all the time! :D

Here's something I've been working on lately -> I saw this flash game where the sprite animations where created by applying a series of transformations (scalings, rotations, shearings, translations... etc) on the original sprite. I liked the idea and I thought I'd play around with it a bit. Pretty soon, though, I realized that the library I was using (SFML) didn't directly support any but some trivial transformations, so, I had to manually create the ones I wanted using some rather low level interface (sf::Image::GetPixel / sf::Image::SetPixel). However, the end result was very satisfying. Here's a console version of what I did (sorry about the flickering :/)

#define _WIN32_WINNT 0x0500

#include <windows.h>

#include <iostream>
#include <vector>

#include <cstdlib>
#include <ctime>
#include <cmath>

typedef void (*Callback)(double[2][2], double[2], int, int, int, int, int, int);

struct Color
{
    static const int Default = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
    static const int White   = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
    static const int Red     = FOREGROUND_RED |                                      FOREGROUND_INTENSITY;
    static const int Green   =                  FOREGROUND_GREEN |                   FOREGROUND_INTENSITY;
    static const int Blue    =                                     FOREGROUND_BLUE | FOREGROUND_INTENSITY;
};

struct Bitmap
{
    int width;
    int height;

    std::vector<int> data;

    Bitmap(int width_ = 1, int height_ = 1, int color_ = Color::White) :
        width(width_), height(height_), data(width_ * height_, color_) {}

    int & operator()(int x, int y)       { return data[x * height + y]; }
    int …
m4ster_r0shi 142 Posting Whiz in Training

You can find the functions you need here -> Windows Console Functions

Here, I wrapped them for you:

#include <windows.h>
#include <iostream>

void gotoxy(int x, int y)
{
    COORD pos = { x, y };

    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}

int wherex()
{
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);

    return csbi.dwCursorPosition.X;
}

int wherey()
{
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);

    return csbi.dwCursorPosition.Y;
}

int main()
{
    gotoxy(30, 10);

    std::cout << "Hello, World!";

    int x = wherex();
    int y = wherey();

    gotoxy(0, 0);

    std::cout << "end pos of \"Hello, World!\" = ";
    std::cout << "(" << x << ", " << y << ")" << std::endl;

    std::cin.get();
}
m4ster_r0shi 142 Posting Whiz in Training

I know this is marked as solved, but I believe that
the above example yields duplicate numbers, too.

I think the OP is looking for a shuffling algorithm.

m4ster_r0shi 142 Posting Whiz in Training

What if you put two getchar calls instead of one?

m4ster_r0shi 142 Posting Whiz in Training

I just would like some input/critics/heads up on my class definition and implementation I did for my project.

Looks good. There are a couple of small issues, but other than that looks good. About the small issues now...

Your m_vector doesn't have to be a vector pointer. A vector object would be fine. This would greatly simplify
some things. E.g. your assignment operator (which, by the way, should return a reference) would look like this:

PNVector & PNVector::operator=(const PNVector &other) {
    if (this!= &other)
        this->m_vector = other.m_vector;
    return *this;
}

The rest of your operators could use some const qualifiers.
E.g. PNVector operator+(const PNVector &rhs) [B]const[/B]; Don't forget that at() performs bounds checking, which is unnecessary
in many cases in your code. You could just use operator[] instead.

If you intend to also provide +=, *=, ... etc operators (which is a good idea), you
should implement +, *, ... etc in terms of +=, *=, ... and not the other way around.

I.e. it should look like this:

PNVector & PNVector::operator += (double val)
{
    // ...

    return *this;
}

PNVector PNVector::operator + (double val)
{
    PNVector ret(*this);

    ret += val;

    return ret;
}

Is the only solution to make this work to overload the binary * and / respectively?

Yes. You have to also write global operator overloads (note that both global
and member operators are binary operators, as they accept two arguments).

Finally, note that if …

m4ster_r0shi 142 Posting Whiz in Training

I think the OP is looking to modify the value at runtime

Why? Reading the original post, I gather that the OP is trying to do something like this:

#include <iostream>
using namespace std;

struct AbstractEvent
{
    static int counter;

    static int get_next_id();

    static void init_event_ids();

    virtual int get_type() = 0;

    virtual ~AbstractEvent() {}
};

struct ConcreteEventA : AbstractEvent { static int type; int get_type() { return type; } };
struct ConcreteEventB : AbstractEvent { static int type; int get_type() { return type; } };
struct ConcreteEventC : AbstractEvent { static int type; int get_type() { return type; } };

// more concrete events ...

int AbstractEvent::counter = 0;
int AbstractEvent::get_next_id() { return counter++; }

int ConcreteEventA::type = AbstractEvent::get_next_id();
int ConcreteEventB::type = AbstractEvent::get_next_id();
int ConcreteEventC::type = AbstractEvent::get_next_id();

// more concrete event type initializations  ...

int main()
{
    ConcreteEventA a1, a2;
    ConcreteEventB b1, b2;
    ConcreteEventC c1, c2;

    AbstractEvent & ea1 = a1, & ea2 = a2;
    AbstractEvent & eb1 = b1, & eb2 = b2;
    AbstractEvent & ec1 = c1, & ec2 = c2;

    cout << ea1.get_type() << endl;
    cout << eb1.get_type() << endl;
    cout << ec1.get_type() << endl;

    cout << boolalpha << endl;

    cout << (ea1.get_type() == ea2.get_type()) << endl;
    cout << (ea1.get_type() == eb2.get_type()) << endl;
}

You can achieve the same functionality simply doing this:

#include <iostream>
using namespace std;

struct AbstractEvent
{
    virtual const void * get_type() = 0;

    virtual ~AbstractEvent() {}
};

struct ConcreteEventA : AbstractEvent { const void * get_type() { static const …
m4ster_r0shi 142 Posting Whiz in Training

What's wrong with simply using the address of m_type as the unique ID you want?

Here's an example -> http://www.cplusplus.com/forum/general/33296/#msg179678

m4ster_r0shi 142 Posting Whiz in Training

While multithreading is indeed the way to go in such cases, I believe the OP might be able to get away with just a _kbhit call.

#include <windows.h>
#include <conio.h>

#include <iostream>

int main()
{
    int counter = 0;
    char ch = 0;

    while (true)
    {
        ch = 0;

        if (_kbhit()) ch = _getch();

        // hit esc to quit
        if (ch == 27) break;

        std::cout << counter++;

        if (ch) std::cout << ' ' << ch;

        std::cout << std::endl;

        Sleep(150);
    }

    return 0;
}

By the way, something I've been wanting to ask for a while now, what does the 's' in "jsw" stand for?

sergent commented: much easier then Narue's. Same thing I had in mind! +5
m4ster_r0shi 142 Posting Whiz in Training

I found a video course like that: http://video-courses-online.com/programming-courses-online/c-course.php

Why pay for it when there are plenty free ones out there? Here's one of the few I find decent -> decent C++ video tutorial

m4ster_r0shi 142 Posting Whiz in Training

Yeah, I had a similar problem too when I started playing with SFML.
The solution is simple, but I don't really understand how/why it works...

The main problem is this here -> sf::Shape Rect2 = sf::Shape::Rectangle(50, 0, 70, 20, sf::Color::Blue); .
It should be -> sf::Shape Rect2 = sf::Shape::Rectangle(0, 0, 20, 20, sf::Color::Blue); Rect2.Move(50, 0); .

This works fine for me:

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>

using namespace std;

bool isCollision(int x, int y, int x2, int y2)
{
    if (abs(x2 - x) > 20 || abs(y2 - y) > 20)
		return false;
	else
		return true;
}

int main()
{
    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "My SFML Window");
    sf::RenderWindow Warning(sf::VideoMode(400, 225, 32), "WARNING!");
    sf::Shape Rect = sf::Shape::Rectangle(0, 0, 20, 20, sf::Color::Red);
    sf::Shape Rect2 = sf::Shape::Rectangle(0, 0, 20, 20, sf::Color::Blue);

    Rect2.Move(50, 0);

    while (App.IsOpened())
    {
        sf::Event event;

        while (App.GetEvent(event))
        {
            if (event.Type == sf::Event::Closed) App.Close();
            if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Escape)) App.Close();
            if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Right)) Rect.Move(5.0, 0);
            if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Left)) Rect.Move(-5.0, 0);
            if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Down)) Rect.Move(0, 5.0);
            if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Up)) Rect.Move(0, -5.0);

            int x = Rect.GetPosition().x;
            int y = Rect.GetPosition().y;
            int x2 = Rect2.GetPosition().x;
            int y2 = Rect2.GetPosition().y;

            if (isCollision(x, y, x2, y2))
                Warning.Clear(sf::Color::White);
            else
                Warning.Clear(sf::Color::Black);
        }

        App.Clear();
        App.Draw(Rect);
        App.Draw(Rect2);
        App.Display();
        Warning.Display();
    }
}

You might also want to check this out:

#include <SFML/Graphics.hpp>
#include <iostream>

const int SCREEN_WIDTH=320;
const int SCREEN_HEIGHT=240;
const …
m4ster_r0shi 142 Posting Whiz in Training

C++ does not allow nested functions either.

Technically, true. But there are workarounds -> nesting functions in C++
However, I'm quite sure that this is not what the OP is looking for...

m4ster_r0shi 142 Posting Whiz in Training

Damn. I really have to start to familiarize myself with the upcoming standard.

m4ster_r0shi 142 Posting Whiz in Training

Thats pretty cool.

Haha, thanks! :D

There is a bug in the code above though... It won't work for some edge cases
(e.g. 52 is mapped to "aa" (as is 53) instead of "Z"). I realised it too late to edit
it and correct it (BTW, what's this thing with the 30 minute limit to editing? Why
can't I edit my posts whenever I want?). PRINT_LETTER should look like this:

#define PRINT_LETTER(r, unused, n) \
BOOST_PP_REPEAT(BOOST_PP_ADD(BOOST_PP_DIV(BOOST_PP_SUB(n, 1), 52), 1), \
                LETTER, BOOST_PP_ADD(BOOST_PP_MOD(BOOST_PP_SUB(n, 1), 52), 1)) "\n"

I never gave enough time to learn metaprogramming

In this case, I think I'll seize the opportunity to show off a little bit more :P

I'll do the same thing using just template metaprogramming (no boost preprocessor tricks). Note that the end
result won't be the same. What I got using preprocessor metaprogramming was a literal constant just the way
I wanted it. I can't do that using just template metaprogramming (AFAIK). The best I can do in this case is fill an
existing array with values generated during compilation. The filling itself will still be made while the program runs.

Let's begin with something simple. A template that generates code that prints the numbers 0 ... 9.

#include <cstdio>

template <int MAX_I, int CUR_I = 0>
struct PrintLoop
{
    static void RUN()
    {
        printf("%c\n", CUR_I + '0');

        PrintLoop<MAX_I, CUR_I + 1>::RUN();
    }
};

template <int MAX_I>
struct PrintLoop<MAX_I, MAX_I>
{
    static …
m4ster_r0shi 142 Posting Whiz in Training

This isn't much of a challenge as it is now, so I decided to do the interesting stuff during compilation.

EDIT: A boost preprocessor array can't have more than 25 elements. That's why I had to split the letters like that.

#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/comparison/less.hpp>
#include <boost/preprocessor/arithmetic/add.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/arithmetic/div.hpp>
#include <boost/preprocessor/arithmetic/mod.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/array/elem.hpp>
#include <boost/preprocessor/control/if.hpp>

#define LETTERS_a_m (13, ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"))
#define LETTERS_n_z (13, ("n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"))
#define LETTERS_A_M (13, ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"))
#define LETTERS_N_Z (13, ("N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"))

#define LETTER_LOWER(n) \
BOOST_PP_IF(BOOST_PP_LESS(n, 13), \
    BOOST_PP_ARRAY_ELEM(n, LETTERS_a_m), \
    BOOST_PP_ARRAY_ELEM(BOOST_PP_SUB(n, 13), LETTERS_n_z))

#define LETTER_UPPER(n) \
BOOST_PP_IF(BOOST_PP_LESS(n, 13), \
    BOOST_PP_ARRAY_ELEM(n, LETTERS_A_M), \
    BOOST_PP_ARRAY_ELEM(BOOST_PP_SUB(n, 13), LETTERS_N_Z))

#define LETTER(z, n, letter_id) \
BOOST_PP_IF(BOOST_PP_LESS(letter_id, 27), \
    LETTER_LOWER(BOOST_PP_SUB(letter_id, 1)), \
    LETTER_UPPER(BOOST_PP_SUB(letter_id, 27)))

#define PRINT_LETTER(r, unused, n) \
BOOST_PP_REPEAT(BOOST_PP_ADD(BOOST_PP_DIV(n, 52), 1), LETTER, BOOST_PP_MOD(n, 52)) "\n"

#include <cstdio>

#define INPUT (1)(2)(4)(8)(16)(32)(50)(64)(100)(128)(150)

int main()
{
    const char * output = BOOST_PP_SEQ_FOR_EACH(PRINT_LETTER, ~, INPUT);

    printf(output);
    fflush(stdout);

    return 0;
}

Compiler output:

.file	"main.cpp"
	.def	___main;	.scl	2;	.type	32;	.endef
	.section .rdata,"dr"
LC0:
	.ascii [B]"a\12b\12d\12h\12p\12F\12X\12ll\12VV\12xxx\12TTT\0"[/B]
	.text
.globl _main
	.def	_main;	.scl	2;	.type	32;	.endef
_main:
	pushl	%ebp
	movl	%esp, %ebp
	andl	$-16, %esp
	subl	$16, %esp
	call	___main
	movl	$LC0, (%esp)
	call	_puts
	movl	__imp___iob, %eax
	addl	$32, %eax
	movl	%eax, (%esp) …
mrnutty commented: show off +13
m4ster_r0shi 142 Posting Whiz in Training

The problem is here -> if(i = rhs.size - 1) . It should be -> if(i == rhs.size - 1)

m4ster_r0shi 142 Posting Whiz in Training
m4ster_r0shi 142 Posting Whiz in Training
m4ster_r0shi 142 Posting Whiz in Training

And if you want to do both with one container, you can always use boost::multi_index :P

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>

#include <functional>
#include <utility>
#include <iostream>
#include <string>

using namespace boost::multi_index;

class Dictionary
{
    typedef std::pair<std::string, std::string> Pair;

    struct ordered {};
    struct hashed  {};

    typedef multi_index_container
    <
        Pair,
        indexed_by
        <
            ordered_unique<tag<ordered>, identity<Pair> >,
            hashed_unique <tag<hashed>,  member<Pair, std::string, &Pair::first> >
        >
    > Container;

    typedef Container::index<ordered>::type data_ordered;
    typedef Container::index<hashed >::type data_hashed;

public:

    void Insert(const std::string & english, const std::string & french)
    {
        data.get<ordered>().insert(Pair(english, french));
    }

    void PrintAll()
    {
        data_ordered::const_iterator cur_it = data.get<ordered>().begin();
        data_ordered::const_iterator end_it = data.get<ordered>().end();

        for (; cur_it != end_it; ++cur_it)
        {
            std::cout
                << cur_it->first  << " -> "
                << cur_it->second << std::endl;
        }
    }

    std::string Find(const std::string & english)
    {
        data_hashed::const_iterator it;

        it = data.get<hashed>().find(english, boost::hash<std::string>(), std::equal_to<std::string>());

        if (it != data.get<hashed>().end())
            return english + " -> " + it->second;
        else
            return english + " not found...";
    }

private:

    Container data;
};

int main()
{
    Dictionary dictionary;

    dictionary.Insert("hi",   "salut");
    dictionary.Insert("dog",  "chien");
    dictionary.Insert("god",  "dieu" );
    dictionary.Insert("blue", "bleue");

    dictionary.PrintAll();

    std::cout << std::endl;

    std::cout << dictionary.Find("hi")    << std::endl;
    std::cout << dictionary.Find("hello") << std::endl;
};

Output:

blue -> bleue
dog -> chien
god -> dieu
hi -> salut

hi -> salut
hello not found...
m4ster_r0shi 142 Posting Whiz in Training

Tori Amos - A Sorta Fairytale -> http://www.youtube.com/watch?v=I-5o77_tSrs

m4ster_r0shi 142 Posting Whiz in Training

I am a little confused now,so i first sort them and then put them in hashtable?

Mmm... Not really. When you put them in the hashtable the order is lost.

i am not sure how i can use std::maps never used it before! could you please provide an example ?

There are plenty on the net. Try googling "std::map example".

If you want to stick to your hashmap being an array of pointers, it's probably better that you use a set to sort your data
when you want to print it. Though, note that the hash collision problem is still there. You have to address it somehow.

#include <iostream>
#include <string>
#include <set>

using namespace std;

struct is_less
{
    bool operator()(const string * pstr1, const string * pstr2)
    {
        if (pstr1 == 0) return false; // nulls should
        if (pstr2 == 0) return true;  // go at the end

        return *pstr1 < *pstr2;
    }
};

int main()
{
    string * pstr_arr[10] =
    {
        0,
        new string("world"),
        0,
        0,
        new string("hello,"),
        new string("violet"),
        0,
        new string("red,"),
        0,
        0
    };

    typedef set<const string *, is_less> SetType;

    SetType sorted(pstr_arr, pstr_arr + 10);

    SetType::const_iterator cur_it = sorted.begin();
    SetType::const_iterator end_it = sorted.end();

    for (; cur_it != end_it && *cur_it != 0; ++cur_it)
        cout << **cur_it << " ";

    return 0;
}
m4ster_r0shi 142 Posting Whiz in Training

Of course the words won't be sorted. If you want them to be, use std::map instead,
as mike suggested. std::map's lookup time complexity isn't that bad (it's O(logn)).

Alternatively, you can stick to your hashmap, but then you'd have to copy your words to another container and
sort them there whenever you want to print them, which would not be very wise if you want to print them often.

Another interesting option is to make your hashmap an array of 26 std::maps and your hash function work like
this -> If the word's first letter is 'a' put it in dictionary[0], else, if the word's first letter is 'b', put it in dictionary[1], etc...

This way,

(1) dictionary will be a sorted container for every i,

(2) for each i < j, any word in dictionary will be
less (lexicographically) than any word in dictionary[j].

m4ster_r0shi 142 Posting Whiz in Training

What do you have trouble with in particular? Using for loops? This
will help then -> http://www.cplusplus.com/doc/tutorial/control/#for

Here's some pseudocode:

for ( each element in dictionary )
{
    if ( current_element != 0 )
    {
        print "english word = "
        print current_element->english
        
        print ", "
        
        print "french word = "
        print current_element->french
        
        print newline
    }
}
m4ster_r0shi 142 Posting Whiz in Training

Sure, a loop would be fine. You can use a for loop to scan the dictionary array. In each iteration, if the
current pointer is NULL, do nothing. Else, print what you want (the english word, the french word, or both).

m4ster_r0shi 142 Posting Whiz in Training

Replace all occurrences of hash with hashing . Not just the declaration, but the calls and the definition too! :P

EDIT: Oh, ok, you figured it out.

m4ster_r0shi 142 Posting Whiz in Training

Oh, are you using visual studio? Try replacing hash with hashing in the code above.

Or... What did you mean? Which code doesn't work? The modified version of your code? Or the example in the link?

m4ster_r0shi 142 Posting Whiz in Training

There are a couple of things that need to be fixed.

(1) This is a problem -> p = (Translator*)malloc(sizeof(Translator)); because malloc doesn't call constructors. This means that the underlying
string objects are not initialized properly (perhaps some internal pointers
are not set?). Therefore, the program crashes when you try to use them below.

The solution to this is to simply use new instead of malloc -> p = new Translator; (2) You also have an out-of-bounds problem in your hash function. How do you
know that your string's size will always be 99? It should look more like this:

int hashing (string s)
{
    int total = 0;

    for (int j = 0; j < s.size(); j++)
        total = total + (int)s[j];

    return total % 99;
}

Since you've made it this far by yourself, I'll give you a simple implementation for
searchDef, because there is another important problem that I want to point out.

Here's your code slightly modified and with searchDef added:

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

struct Translator
{
    string english;
    string french;
};

Translator * dictionary[99] = { 0 };

void mainMenu();
int hash(string s);
void addDef();
void searchDef();
Translator * createNode(string a, string b);
void quit ();

int main()
{
    while (true) mainMenu();
}

void mainMenu()
{
    int choice;

    cout
        << "Welcome to English-French translator\n"
        << "What do You want to do ?\n"
        << "1. add Definition to Dictionary\n"
        << "2. …
m4ster_r0shi 142 Posting Whiz in Training

But i dont get it why did i have to put new before and the point is and don't really understand what 'new' does..

Check this out -> http://cplusplus.com/doc/tutorial/dynamic/

i've done these things before without getting any error

Using a pointer without initializing it is undefined behaviour. You simply were lucky :P If you want
to refresh your knowledge on pointers, check this out -> http://cplusplus.com/doc/tutorial/pointers/

m4ster_r0shi 142 Posting Whiz in Training

And I need world peace. If you can give me that, I'll gladly give you a class of string.

m4ster_r0shi 142 Posting Whiz in Training

These -> 15 32 50 32 15 are the coefficients of the polynomial you'd get if you
multiplied the polynomials 3*x^2 + 4*x + 5 and 5*x^2 + 4*x + 3 together.

Useful links -> Discrete Convolution, Cauchy Product

m4ster_r0shi 142 Posting Whiz in Training

The problem is that you never create a cs_EnableOverrideAction object in main.
What you create in main is just an uninitialized pointer that could point to anything.

This will work fine -> cs_EnableOverrideAction * enableit = new cs_EnableOverrideAction; This would also work find -> cs_PureFunction * enableit = new cs_EnableOverrideAction; And, of course, if you want to be nice to your OS, you should delete enableit; when you're done with it.

EDIT: Also, in such cases, it's good to make the destructor of your base class virtual, too.

m4ster_r0shi 142 Posting Whiz in Training

It depends.

If n denotes the number of rows (or columns - it's the same, since it doesn't make sense to
check if a rectangular matrix is symmetric), then the above algorithm's complexity is O(n^2).

But if n denotes the number of elements, then, yes, the above algorithm's complexity is O(n).

m4ster_r0shi 142 Posting Whiz in Training

Can you tell us what you want to do with the array? We may be able to suggest a better solution.

m4ster_r0shi 142 Posting Whiz in Training

I want to do the same thing with a 3D vector. How would the code look?

You can do it like this:

vector<vector<vector<float> > > vec (5, vector<vector<float> > (5, vector<float> (5, 0) ) );

The above creates a 5 x 5 x 5 3D vector, with all initial values set to zero.

How do I index a 3D vector like this?

You can do it like this:

vec.at(1).at(2).at(3) = 5.5;

//or, if you don't want bounds checking...

vec[1][2][3] = 5.5;

However, for performance reasons, it would be better to create
a wrapper around a 1D vector that mimics 3D behaviour, like this:

#include <iostream>
#include <vector>

template <class T>
class Vector3D
{
public:

    Vector3D(unsigned size_i_, unsigned size_j_, unsigned size_k_):
        size_i(size_i_), size_j(size_j_), size_k(size_k_)
        { data.resize(size_i*size_j*size_k); }

    Vector3D(unsigned size_i_, unsigned size_j_, unsigned size_k_, const T & default_value):
        size_i(size_i_), size_j(size_j_), size_k(size_k_)
        { data.assign(size_i*size_j*size_k, default_value); }

    T & operator () (unsigned i, unsigned j, unsigned k)
        { return data[i*size_j*size_k + j*size_k + k]; }

        // or, if you want bounds checking...
        // data.at(i*size_j*size_k + j*size_k + k);

    const T & operator () (unsigned i, unsigned j, unsigned k) const
        { return data[i*size_j*size_k + j*size_k + k]; }

        // or, if you want bounds checking...
        // data.at(i*size_j*size_k + j*size_k + k);

    //...

    // more member functions
    // (e.g. resize etc...)

    //...

private:

    unsigned size_i;
    unsigned size_j;
    unsigned size_k;

    std::vector<T> data;
};

int main()
{
    Vector3D<int> v3d(2,3,4,100);

    v3d(1,2,3) = 0;

    std::cout << v3d(0,1,2) << std::endl;
    std::cout << v3d(1,2,3) << std::endl; …
m4ster_r0shi 142 Posting Whiz in Training

Note that you have to #define _WIN32_WINNT 0x0500 before
including windows.h in order to be able to use GetConsoleWindow.
It says so in the remarks section of the relevant link posted above.

m4ster_r0shi 142 Posting Whiz in Training

Ok, since nobody has replied yet, I thought I'd give it a shot.
Warning -> I'm not an expert, at all. I just started learning python.

The above statement prints 7, left zero padded, so that the total
number of digits is 3. You can also put 3 in the format string instead:

print('%03d' % 7)
m4ster_r0shi 142 Posting Whiz in Training

And if you want to stick to the current standard, you can always use boost lambdas:

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>

int main()
{
    using namespace boost::lambda;

    std::vector<int> items(25);
    std::map<int, int> counts;

    for (int i = 0; i < 25; ++i) items[i] = i % 7;

    for_each(items.begin(), items.end(),
        ++bind(&std::map<int, int>::operator[], &counts, _1) );

    typedef std::map<int, int>::iterator::value_type  BigType;

    for_each(counts.begin(), counts.end(),
        std::cout
            << constant( "number " ) << bind(&BigType::first,  _1)
            << constant(" appears ") << bind(&BigType::second, _1)
            << constant(" times\n" )
            );

    return 0;
}
m4ster_r0shi 142 Posting Whiz in Training

I don't know what you mean by saying "hook", but if you want to hide the console cursor, you can do it like this:

#include <windows.h>
#include <iostream>

int main()
{
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO cursor_info;

    GetConsoleCursorInfo(console, &cursor_info);

    cursor_info.bVisible = false;

    SetConsoleCursorInfo(console, &cursor_info);

    std::cout << "See? No cursor! -> ";

    Sleep(3000);
}

Useful links:

http://msdn.microsoft.com/en-us/library/ms683163(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms686019(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms682068(v=vs.85).aspx

m4ster_r0shi 142 Posting Whiz in Training

If your answers are like mine ("yes" and "no"), then perhaps you need another approach.

Okay. This will work fine (and I have to put a semicolon at the end, otherwise it won't compile):

#define LOOP_BODY \
do { \
\
    dx =  cos(atan(slope)) * line_length; \
    dy = -sin(atan(slope)) * line_length; \
\
    mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0); \
    MouseMove(dx, dy); \
    mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0); \
\
    Sleep(25); \
} while(0)

What's the next test?

m4ster_r0shi 142 Posting Whiz in Training

How about something less tricky.

I was referring to the algorithm. Tweaking the parameters (slope_max, slope_change and line_length) can
produce interesting results. Making slope_change and line_length variable can also yield very interesting results.

Like for example using a function instead of some hacky multi-line macro.

There's nothing wrong with hacky multi-line macros. On the contrary, they make my code more boost-like :D

m4ster_r0shi 142 Posting Whiz in Training

How about something less tricky. Something like this:

#include <windows.h>
#include <iostream>
#include <cmath>

bool IsPressed(int vkey) { return GetAsyncKeyState(vkey) >> 15; }

void MouseMove(int dx, int dy)
{
    POINT point; GetCursorPos(&point);
    SetCursorPos(point.x + dx, point.y + dy);
}

const double slope_max    = 1.35;
const double slope_change = 0.15;

const double line_length  = 16;

#define LOOP_BODY \
    dx =  cos(atan(slope)) * line_length; \
    dy = -sin(atan(slope)) * line_length; \
\
    mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0); \
    MouseMove(dx, dy); \
    mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0); \
\
    Sleep(25);

int main()
{
    std::cout << "hit F8 to begin" << std::endl;

    while (!IsPressed(VK_F8)) Sleep(25);

    double slope, dx, dy;

    for (slope = 0;           slope < slope_max; slope +=  slope_change) { LOOP_BODY }
    for (slope =  slope_max;  slope > 0;         slope -=  slope_change) { LOOP_BODY }
    for (slope = 0;          -slope < slope_max; slope += -slope_change) { LOOP_BODY }
    for (slope = -slope_max; -slope > 0;         slope -= -slope_change) { LOOP_BODY }
}
sergent commented: Thanks! I don't have time right now, I will try that soon! +4
m4ster_r0shi 142 Posting Whiz in Training

How about using virtual functions?

#include <iostream>

using namespace std;

struct A
{
    virtual void print_me() const {}

    virtual ~A() {}
};

struct B : A
{
    void print_me() const
    {
        cout << "Hello, I'm B!" << endl;
    }
};

struct C : A
{
    void print_me() const
    {
        cout << "Hi there, I'm C!" << endl;
    }
};

void print(const A & obj)
{
    obj.print_me();
}

int main()
{
    B b;
    C c;

    print(b);
    print(c);
}
m4ster_r0shi 142 Posting Whiz in Training

I will be very disappointed if this thread doesn't turn into a C vs C++ flamewar...

m4ster_r0shi 142 Posting Whiz in Training

The setw manipulator has the same problem. It only affects the next output operation.
AFAIK, there is no way you can avoid setting the width over and over again.
Maybe someone else knows better though. Here's a simple hackish solution:

#include <iostream>
#include <sstream>

using namespace std;

class ostream_w : public ostream
{
    unsigned w;

public:

    ostream_w(ostream & os_, unsigned w_): w(w_)
    {
        rdbuf(os_.rdbuf());
    }

    template <class T>
    ostream_w & operator << (const T & t)
    {
        width(w);

        static_cast<ostream &>(*this) << t;

        return *this;
    }

    // necessary for endl
    ostream_w & operator << (ostream & (*pf)(ostream &))
    {
        pf(static_cast<ostream &>(*this));

        return *this;
    }
};

int main()
{
    ostream_w cout_w6(cout, 6);

    cout_w6.setf(ios::right);

    for (int row = 0; row <= 12; ++row)
    {
        for (int column = 0; column <= 10; ++column)
        {
            stringstream buffer;

            buffer << row << ":" << column;

            cout_w6 << buffer.str();
        }

        cout_w6 << endl;
    }

    return 0;
}
m4ster_r0shi 142 Posting Whiz in Training

If you want to modify something inside a function, you should pass it by reference ;)
This will work -> void change(float (*[B]&[/B]d)[3], float (*e)[3]) { d = e; }

m4ster_r0shi 142 Posting Whiz in Training

As pseudorandom suggested, the first step would be to convert the integer to a string.
Alternatively, if you want to skip that step, you could just get a string from the user.

Now, let's take a look at the algorithm...

Suppose the user enters this -> "1234567890" . The result of add_commas("1234567890") should
be this -> "1,234,567,890" . One way to use recursion would be to make your function work as follows:

add_commas("1234567890") = 

add_commas("1234567") + "," + "890" = 

( add_commas("1234") + "," + "567" ) + "," + "890" = 

( ( add_commas("1") + "," + "234" ) + "," + "567" ) + "," + "890" = 

( ( "1" + "," + "234" ) + "," + "567" ) + "," + "890" = 

( "1,234" + "," + "567" ) + "," + "890" = 

"1,234,567" + "," + "890" = 

"1,234,567,890"

That is, if the string's length is 3 or less, add_commas should return the string intact. Otherwise, it should
break it into two parts, the right one consisting of the 3 rightmost digits and the left one being the rest
of the string. Then, the function should return add_commas(left_part) + "," + right_part Useful link -> http://cplusplus.com/reference/string/string/substr/

Encrypted hint -> Difdl!uif!uisfbet!J!tubsufe/

m4ster_r0shi 142 Posting Whiz in Training

Megha Chatterji, Vicky Bilani - Mere Naseeb Mein... -> http://www.youtube.com/watch?v=4jjH-oNv-r4

m4ster_r0shi 142 Posting Whiz in Training

Show me yours and I'll show you mine.

Am I the only one who keeps misinterpreting that?

sergent commented: lol +4
m4ster_r0shi 142 Posting Whiz in Training

error: expected initializer before '*=' token

Hmmm... I don't know about that. This here works fine for me:

#include <iostream>

using namespace std;

int main()
{
    double population = 100;

    double annualBirth = 0.75;
    double annualDeath = 0.25;

    for (int i = 1; i <= 10; i++)
    {
        cout << "Year " << i << "   population: " << population << endl;

        population *= (1 + annualBirth - annualDeath);
    }

    return 0;
}

New population = Starting population * (1 + birth rate) * (1 - death rate)

I see. Well, in C++ you could write this as -> population *= (1 + annualBirth ) * (1 - annualDeath); However, note that it's quite different than the one I suggested above.

Mine works like this:

temp1 = old_population * annualBirth;
temp2 = old_population * annualDeath;

new_population = old_population + temp1 - temp2;

Your book's works like this:

temp1 = old_population * annualBirth;
temp2 = (old_population + temp1) * annualDeath;

new_population = old_population + temp1 - temp2;

Pick whichever one you like :P