triumphost 120 Posting Whiz

What you did is already correct.. the reserve allowed it to survive the clear..

Your vector will have a size of 0 but a capacity of 10000. All information in the vector is lost and cannot be accessed. If an access is attempted, it will assert out of range. Basically it will crash your program if you try to access a position in the vector for any type that is not integral.

vector<string>being accessed will crash your program.
vector<int/short/double/long> being accessed will not crash your program, but every value in the vector will be 0.

for (int I = 0; I < myVector.size(); I++)  //Will do NOTHING if you have cleared it.

for (int I = 0; I < myVector.capacity(); I++)  //Will do 10000 iterations based on your reserved size.

Now I do not currently have a compiler with me to test with iterators so i'm not sure how that would work but I'm sure you can test it:

for (std::vector<T>::iterator it = myVector.begin(); it != myVector.end(); ++it or something of the sort.

triumphost 120 Posting Whiz

Yesterday I took a dive into smart pointers and wasn't sure when I should use them vs. Raw pointers. I found out they are quite useful but they do not work all the time for me.

Example of working:

char* Buffer = new char[1024];
fread(buffer, 1, sizeof(buffer), infile);  //took out the while loop for this example.
delete[] Buffer; Buffer = nullptr;


//Changed to:
std::unique_ptr Buffer(new char[1024]);
fread(buffer.get(), 1, sizeof(buffer), infile);  //took out the while loop for this example.
//I never have to do delete[] correct?

In the above, I had to use .get() to pass my pointer to fread and various other functions. My problem comes when I try to do:

//Raw ptr works well..

char* pFile;
char* pMemory = new char[SomeSize];
pFile = pMemory;
memcpy(pFile, Buffer, dwHeader);

pFile = (char*)((DWORD)pFile + jmpSize);


//Smart ptr.. :S I'm confused..

std::shared_ptr<char[]> pMemory(new char[SomeSize]);
std::shared_ptr<char[]> pFile(pMemory);  //The same as pFile = pMemory? Also had to declared pFile after pMemory.
memcpy(pFile.get(), Buffer, dwHeader);

pFile.get() = (char*)((DWORD)pFile.get() + jmpSize);   //Errors :S

Questions:
How do I assign to my ptr? Is is supposed to be shared or unique? I know unique uses move semantics so only one can owner can have the raw ptr. So I used shared since that's what the equal sign does right?

Is there any moment in time where I should use a Smart pointer vs. a Raw pointer (Referring to a bitmap class where there is a member pointer to a struct that is deleted in …

triumphost 120 Posting Whiz

Hey after reading the tutorial, I implemented this:

//Copy constructor
Bitmaps::Bitmaps(const Bitmaps& Bmp) : Pixels(((Bmp.width * Bmp.height) != nullptr) ? new RGB[Bmp.width * Bmp.height] : nullptr), width(Bmp.width), height(Bmp.height), size(Bmp.size), DC(0), Image(0)
{
    memcpy(Pixels, Bmp.Pixels, Bmp.size);
    memcpy(Info, Bmp.Info, sizeof(Bmp.Info));
    memcpy(bFileHeader, Bmp.bFileHeader, sizeof(Bmp.bFileHeader));
}

//Move constructor.
Bitmaps::Bitmaps(Bitmaps&& Bmp) : Pixels(((Bmp.width * Bmp.height) != nullptr) ? new RGB[Bmp.width * Bmp.height] : nullptr), width(Bmp.width), height(Bmp.height), size(Bmp.size), DC(0), Image(0)
{
    Bmp.Pixels = nullptr;
}

//Assignment operator
Bitmaps& Bitmaps::operator = (Bitmaps Bmp)
{
    Bmp.swap(*this);
    return *this;
}

//Swap no-throw?
void Bitmaps::swap(Bitmaps& Bmp) //throw()
{
    std::swap(Pixels, Bmp.Pixels);
    std::swap(Info, Bmp.Info);
    std::swap(width, Bmp.width);
    std::swap(height, Bmp.height);
    std::swap(size, Bmp.size);
    std::swap(bFileHeader, Bmp.bFileHeader);
}

It tells me that I need to intialize Info and bFileHeader in the member initialization list.. and I'm not sure if I did this all right :S I got the idea of the operator = and the swap but not the construction. I still do not understand why I need to use the using std::swap instead of just putting std::swap like I did above. I used the Nullptr instead of the 0.

I wasn't sure if to put the throw() infront of the swap or not as some forums say the no throw is better :S I also wasn't sure what to do with my HDC dc and HBitmap Image.

triumphost 120 Posting Whiz

Well I like to learn as much code as I can in a day and I just came across the copy constructor. I do not understand when I need to use it. Do I need to use it for every class I make?

I came across it after getting the error: 'class Bitmaps' has pointer data members but does not override 'Bitmaps(const Bitmaps&)' or 'operator=(const Bitmaps&)' [-Weffc++]

So I googled it as usual and came across the copy constructor and assignment vs. copy constructor.
Now after reading the documentation, it tells me that if I have a class already constructed, I can assign another class to it without the copy constructor. If the class is being initialized by another, I need a copy constructor.

Already assigned class:

class Point
{
   int x, y;

   public:
        Point(int X, int Y);
};

Point A(10, 10);
Point B(5, 5);

A = B; //Uses assignment operator?

Unassigned class:

class Point
{
       int x, y;

       public:
            Point(int X, int Y);
};

Point B(5, 5);

Point A = B;  //Copy constructor? This currently works fine for me without it :S

Now the code that gives me a problem is defined as so:

class Bitmaps
{
    private:
        PRGB Pixels;               //Pointer to a union.
        BITMAPINFO Info;           //This has to be initialized in member list with Constructor() : Info(0)?
        int width, height, size;
        BITMAPFILEHEADER bFileHeader;

    protected:
        HDC DC;
        HBITMAP Image;

    public:
        ~Bitmaps();                 //Deletes Pixels aka pointer. Deletes Image and releases DC.

        Bitmaps(const char* FilePath); …
triumphost 120 Posting Whiz

Ahh Thanks for the info. I had to ask because I was taught that this->X = X will fix the shaddowing so I went and changed all my classes to "Shaddow" and after reading your post I had to change them back.

Then I enabled all warnings on codeblocks and it complained until it couldn't complain anymore. Just fixed it Thank you.

triumphost 120 Posting Whiz

Why does this say shaddowing? If I change my member X and Y to _X, _Y then when I access my class via the dot operator, it shows FOUR values..

Current Class:

class Point
{
    public:
        int X, Y;

    Point(int X, int Y);
    ~Point();
};

Point::Point(int X, int Y) : X(X), Y(Y) {}

Previous class that shows x, y, X, Y:

class Point
{
    public:
        int Y, Y;

    Point(int x, int y);
    ~Point();
};

Point::Point(int x, int y) : X(x), Y(y) {}

How can I stop the compiler from telling me it's shaddowing but at the same time only have the class members show in my intellisense instead of both class and function members?

Codeblocks and VS2010 and VS2012 RC do this :S

Also why should I include <complex> to use std::abs instead of including math.h and using fabs?

I'm trying to compare floating point values using:

#define VERYSMALL  (1.0E-150)
#define EPSILON    (1.0E-8)

bool Extended::Equal(double a, double b)
{
    double absDiff = std::abs(a - b);
    if (absDiff < VERYSMALL)
        return true;

    double maxAbs  = max(std::abs(a), std::abs(b));
    return (absDiff/maxAbs) < EPSILON;
}
triumphost 120 Posting Whiz

So I should not do char meh[Size]; instead I should use char* meh = new char[Size];?

And thanks for the thorough explanation :)

triumphost 120 Posting Whiz

I'm trying to figure out why I should convert all my unsigned ints/shorts to size_t.

I'm doing the things below but I'm not sure which one to use and which type to iterator my for-loop with:

unsigned short Size()
{
   return vector.size();
}


int Size()
{
   return vector.size();
}

unsigned int Size()
{
   return vector.size();
}

size_t Size()
{
   return vector.size();
}


for (unsigned short I = 0; I < Size(); I++)
{
    //...................
}

I looked up the difference and it says that the size can vary from machine to machine and that size_t is the sizeof a pointer but then I was thinking that there would be no way someone would allocate a vector of 4.2b so I decided 65535 is enough so I used unsigned short but then I thought maybe that's too small so I decided unsigned int then came across size_t and now I'm confused which to use between the them all. The short? int? unsigned int? unsigned short? size_t? long?

As for my pointer question, after using delete[] on a pointer, should I then set that pointer to = 0? Example:

char* Meh = new char[1024];
delete[] Meh;
Meh = 0;

also why does the compiler allow me to do char Meh[vector.size() + 1] without having to use the new keyword?

triumphost 120 Posting Whiz

That didn't work :c

I solved it just now with:

                char Buffer[NewValue.size() + 1];
                for (size_t I = 0; I < (NewValue.size() + 1); I++)
                    Buffer[I] = NewValue[I] != 0xA ? NewValue[I] : 0;
                dwError = RegSetValueEx(hKey, KeyToEdit.c_str(), 0, KeyType, (LPBYTE)&Buffer, NewValue.size() + 1);

See that NewValue.size() + 1? I was using strlen(Buffer) + 1 instead but when I changed it to the above, it writes everything.

triumphost 120 Posting Whiz

Currently I'm reading Multi-String values from the registry. These strings are double null terminated and single null delimiters are between each one. So below I have the following where these are declared as so:

std::string KeyToRead, Result; DWORD KeyType.

Now I'm returning an std::string aka Result. So I iterated my Buffer (Data) and appended each null delimited string to my Result.

                case REG_MULTI_SZ:
                {
                    char Data[dwSize];   //Not sure why Codeblocks allows this :S?
                    dwError = RegQueryValueEx(hKey, KeyToRead.c_str(), 0, &KeyType, (BYTE*)Data, &dwSize);
                    char* ptr = Data;
                    while (*ptr)
                    {
                        Result.append(ptr);
                        Result += "\n";
                        ptr += strlen(ptr) + 1;
                    }
                }
                break;

This all works fine and dandy but I'm not sure why it allows me to declare char Data[dwSize] without using the new operator.

Anyway doing the reverse is where I get difficulty. I'm trying to turn my string into Double Null terminated string so that I can write it back to the registry but it doesn't work at all. Instead, it writes strings with no spaces or newlines.

EDIT: I got it to add spaces and newlines but I'm not sure if it's a good way of doing it and not sure how to add the extra '\0' at the end.

        if (KeyType == REG_MULTI_SZ)
        {
            char Buffer[NewValue.size()];    //again not sure how the compiler allows this :S
            for (int I = 0; I < NewValue.size(); I++)
            {
                Buffer[I] = (NewValue[I] != '\n') ? NewValue[I] : '\0';  //This works but I'm not sure how …
triumphost 120 Posting Whiz

instead of Test((void*)F); I just did Test(F); and it worked but like you said, I should get used to the C++ style casting so I replaced it with the static cast you have above. I have to read a tutorial on C++ style casting though as I only know the C-style.

For now I'll mark the thread solved. +Rep+ to you sir :)

triumphost 120 Posting Whiz

Hey is that (void) needed? I removed the void and it still worked :S so is there a need for casting? Also is there a way to do it with class functions? I have problems doing that with Class Functions since I don't have the grasp of it yet.

//Where X is just a class that has the functions previously posted but working.

int main()
{
    Debug X;
    std::function<void()> F = std::bind(X.DebugWindow, "one", "two", 100, 100);  //Also tried: &Debug::DebugWindow
    X.Run(&F);
}

//I cannot pass X's functions to it?

Other than that, it works fine if I do not pass it class functions. And it works fine without the void* but I'm not sure why it works without the cast?

triumphost 120 Posting Whiz

Why does the below crash? My pointer is still alive and is constructed in the main so it should not die until main returns :S

I was using this with createthread a while back but my Mingw4.5 never supported it. I just upgraded to 4.7 but now this crashes and if I use it with CreateThread, it does not crash but rather it prints nothing. So I decided to do the following to test why CreateThread did nothing with the pointer but instead I get a bad crash.

void Meh(int X, int Y)
{
    std::cout<< X <<" | "<<Y;
}

void Test(LPVOID lpParameter)
{
    std::function<void()> func = *((std::function<void()>*)lpParameter);
    func();
}

void Run(std::function<void()>* F)
{
    Test((void*)&F);
}


int main(int argc, char* argv[])
{
    //std::cout.flags(std::ios::boolalpha);

    std::function<void()> F = std::bind(Meh, 10, 10);
    Run(&F);

    return 0;
};
triumphost 120 Posting Whiz

Ahh that seems like a headache. Uh what could happen if it's not initalized and I do assume? Though I will not, I just want to know.

triumphost 120 Posting Whiz

I have a header file that I include into my main.cpp file. I want to set some flags when this file is included.

std::cout.flags(std::ios::boolalpha);

I want to set that automatically how can I do this? I tried:

#ifdef DEFINES_HPP_INCLUDED
    std::cout.flags(std::ios::boolalpha);
#endif


//Gives me the error:
//error: 'cout' in namespace 'std' does not name a type|

Or better yet, how can I enable that for all streams automatically?

triumphost 120 Posting Whiz

I'm trying to understand recursion and stack overflows.

First, why does this not cause a stack overflow? Is it because the function returns every time and that the stack isn't populated upon each call?

void Meh()
{
}

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

Two, What is the difference between the two below? They both seem the exact same to me except one uses a base function aka the forward declaration and the other calls itself.. Will both of them result in the same stack overflow? Will they BOTH overflow at all? Both never seem to return to me so the Bleh recursion should overflow exactly like Meh's?

void Meh()
{
    Meh();
}


//Versus..

void Bleh();  //Forward Declaration.

void BaseR()
{
   Bleh();   //Call the forward..
}

void Bleh()
{
   BaseR();  //Call the base..
}
triumphost 120 Posting Whiz

The code below gives me a Narrowing conversion from int to uint32_t:

typedef union RGB
{
    uint32_t Color;
    struct
    {
        unsigned char B, G, R, A;
    };
} *PRGB;



inline RGB Rgb(int R, int G, int B) {RGB Result = {((R & 255) << 16) | ((G & 255) << 8) | (B & 255)}; return Result;}

Error:

warning: narrowing conversion of '((((R & 255) << 16) | ((G << 8) & 65535)) | (B & 255))' from 'int' to 'uint32_t {aka unsigned int}' inside { } [-Wnarrowing]

What I do not understand is why it tells me ((G << 8) & 65535)).. Where in the world does the 65535 come from :S

triumphost 120 Posting Whiz

This may or may not be what you are trying to accomplish:

#include "stdafx.h"

using namespace System;

array<Byte^>^ StringToByteArray(String^ Str)
{
    array<Byte^>^ bytes = gcnew array<Byte^>(Str->Length);
    for(int I = 0; I < Str->Length; I++)
    {
        bytes[I] = Byte(Convert::ToByte(Str[I]));
    }
    return bytes;
}


int main(array<System::String ^> ^args)
{
    array<Byte^>^ bytes = gcnew array<Byte^>(4);
    bytes = StringToByteArray("WTF");
    for (int I = 0; I < 3; I++)
        Console::WriteLine(bytes[I]);
    Console::ReadKey();
    return 0;
}
triumphost 120 Posting Whiz

There is no point to putting "using std::cout". All you need is: "std::cout" The using keyword can be removed.

triumphost 120 Posting Whiz

three = one + two.
one's feet and inches will change too right if i use feet+= FI.feet?
please correct me if im wrong.

Ahh yes you are correct. Try:

FeetInches FeetInches::operator + (const FeetInches& FI)
{
    FeetInches Temp;
    Temp.Feet += this->Feet + FI.Feet;
    Temp.Inches += this->Inches + FI.Inches;
    Temp.Simplify();
    return Temp;
}

FeetInches FeetInches::operator - (const FeetInches& FI)
{
    FeetInches Temp;
    Temp.Feet -= this->Feet + FI.Feet;
    Temp.Inches -= this->Inches + FI.Inches;
    Temp.Simplify();
    return Temp;
}

As per why not to use namespaces in headers. It's because if two namespaces have a class or function of the same name, the "Using" keyword will cause confusion between which one to "use".

doing Namespace::Function. Will explicitly imply which one to use so that the function does not get mixed up with another one of the same name.

Example:

Two header files have:

Namespace Something1
{
    class string
    {
    };
}

Namespace Something2
{
    class string
    {
    };
}


//As you can see both namespaces contain a class called string.

//If do you do:

using namespace Something1;
using namespace Something2;

//How will the compiler know which string to use?
//Thus to fix this confusion, you do:

Something1::string;  //the compiler knows to use String from the something1 namespace.
Something2::string;  //the compiler knows to use String from the something2 namespace.
triumphost 120 Posting Whiz

In your assignment operator, you should be checking for self assignment. In your addition/subtraction operators, I'm not sure that you need that temp there. Your ostream works right out of the box. The reason you're getting these errors is because the files aren't added to your debug and release upon compilation.

If using codeblocks, right click the header and implementation files and press remove. Right click the project and add files. Hold control and click both files to add both of them. Check off Debug AND Release. Compile and it works.

I've made the changes to your assignment operator and the addition/subtraction. I don't think there is a problem returning a copy of the object to the stream but there will be a problem returning a copy of the stream to itself.. So a reference is returned. At least that's the way I see it.

Header:

#ifndef FEETINCHES_H_INCLUDED
#define FEETINCHES_H_INCLUDED

#include <iostream>
#include <cstdlib>

using namespace std;

class FeetInches
{
    private:
        int Feet;
        int Inches;

    public:
        FeetInches(int F = 0, int I = 0);
        int GetInches() const;
        int GetFeet() const;
        void Simplify();
        const FeetInches& operator = (const FeetInches& FI);
        FeetInches& operator + (const FeetInches& FI);
        FeetInches& operator - (const FeetInches& FI);
        friend ostream& operator << (ostream& Str, const FeetInches& FI);
};

#endif // FEETINCHES_H_INCLUDED

Implementation:

#include "FeetInches.h"

FeetInches::FeetInches(int F, int I) {Feet = F; Inches = I;}

int FeetInches::GetInches() const {return Inches;}

int FeetInches::GetFeet() const {return Feet;}

void FeetInches::Simplify()
{
    if (Inches > 0)
    {
        Feet = …
triumphost 120 Posting Whiz

Can anyone check my memory class and suggest changes or things I may need? I'm writing it so that I don't have to worry about deleting anything everytime I allocate.

#include <iostream>

template<typename T>
class Memory
{
    private:
        size_t size;
        T* data;

    public:
        explicit Memory(size_t Size) : size(Size), data(new T[Size]){}
        ~Memory()
        {
            if (data)
                delete[] data;
        }

        Memory(Memory& Block) : size(Block.size), data(new T[Block.size])
        {
            //if (data)
                //delete[] data;
            std::copy(Block.data, Block.data + size, data);
        }

        /*
        Memory(Memory& Block) : size(Block.size)
        {
            if (data)
                delete[] data;
            data = new T[Block.size];
            std::copy(Block.data, Block.data + size, data);
        }
        */

        Memory& operator = (Memory& Block)
        {
            if (this != &Block)
            {
                delete[] data;
                size = Block.size;
                data = new T[size];
                std::copy(Block.data, Block.data + size, data);
            }
            return *this;
        }

        size_t Size() const
        {
            return size;
        }
};
triumphost 120 Posting Whiz

What's a fast way to fill a union/struct of integral members with ALL Zeroes?

RECORD* UNION = {0};

void ZeroStruct(int X, int Y)
{
    UNION = new RECORD[X * Y];
    int K = 0;

    for (int I = 0; I < X; I++)
        for (int J = 0; J < Y; J++)
        {
            UNION[K].X = 0;
            UNION[K].Y = 0;
            UNION[K].Z = 0;
            UNION[K].Magnitude = 0;
            UNION[K].Direction = 0;
            UNION[K].Angle = 0;
            ++K;                
        }
}

It's not slow but I want to know what's a faster way as depending on user input, X and Y can be very large and this method may or may not take long. Also with this method, I have to set each member of the union to 0.

triumphost 120 Posting Whiz

Cannot do that because I iterate it via the size() function from STD::Vector. Thus it throws this error about passing const XXXXXXX as 'this' argument of XXXXXXXXX discards qualifiers.

I use this iteration:

for (int I = 0; I < BoxArrayCore.size(); I++)

and if the Box is found within BoxArrayCore then I remove it with BoxArrayCore.erase(BoxArrayCore.begin() + I);

as BoxArrayCore is my internal vector.

triumphost 120 Posting Whiz

Ahh but the reason I was asking is because if I declare something like:

BoxArray is actually a vector at the core that holds an array of boxes.

BoxArray& Delete(Box &BoxToDelete, bool All = false);

BoxArray BA;
BA<<Box(1, 1, 1, 1)<<Box(2, 2, 2, 2);
BA.Delete(Box(1, 1, 1, 1));  //Will fail as it's not defined.
BA.Delete(B);                //Works perfectly fine.

It will tell me that there is no definition for that operation. I cannot overload Delete twice (one with reference and one without) because it will become ambiguous according to my compiler; which is understandable.

Yet the following works fine with/without the reference:

    BoxArray& Delete(Box BoxToDelete, bool All = false);  //Without reference.

    BoxArray BA;
    BA<<Box(1, 1, 1, 1)<<Box(2, 2, 2, 2);
    BA.Delete(Box(1, 1, 1, 1));  //Delete a box made on the fly.
    Box B(2, 2, 2, 2);
    BA.Delete(B);                //Delete a box pre-constructed.

Anyway I will mark this thread as solved. +Rep+ to both for the great answers.
I will stick to the rule that for arrays leave it as pass by value and for normal variables leave it as pass by value.

triumphost 120 Posting Whiz

Ahh thank you but how do I know whether to do:

BX& operator += (const BX &B)
{
    X1 += B.X1;
    Y1 += B.Y1;
    X2 += B.X2;
    Y2 += B.Y2;
    W = (X1 < 0 ? -X1 : X1) + (X2 < 0 ? -X2 : X2);
    H = (Y2 < 0 ? -Y2 : Y2) + (Y1 < 0 ? -Y1 : Y1);
    return *this;
}

Instead of:

Box operator += (Box B)  //Difference is the Address Of.
{
    X1 += B.X1;
    Y1 += B.Y1;
    X2 += B.X2;
    Y2 += B.Y2;
    W = (X1 < 0 ? -X1 : X1) + (X2 < 0 ? -X2 : X2);
    H = (Y2 < 0 ? -Y2 : Y2) + (Y1 < 0 ? -Y1 : Y1);
    return *this;
}

OR

bool operator == (const Box &B, const Box &B2) //Are the Boxes the same?
{
    return ((B.X1 == B2.X1) && (B.X2 == B2.X2) && (B.Y1 == B2.Y1) && (B.Y2 == B2.Y2));
}

Versus

bool operator == (const BoX &B2) //Are the BoXes the same?
{
    return ((this->X1 == B2.X1) && (this->X2 == B2.X2) && (this->Y1 == B2.Y1) && (this->Y2 == B2.Y2));
}

I read this on C++ Wiki but I don't know when to use which one:

    // binary operator as member function
    Vector2D Vector2D::operator+(const Vector2D& right)const {...}

    // binary operator as non-member function
    Vector2D operator+(const Vector2D& left, const Vector2D& right) {...}

    // binary operator as non-member function with 2 …
triumphost 120 Posting Whiz

Is it possible to overload one operator more than once? I have a struct that is just my idea of a C++ Box. I'm trying to increase the size of a box using an integer or another box.

I'm trying to do:

Box X(0, 0, 0, 0);
Box Y(1, 1, 1, 1);

X + 3;  //X should now be  (0, 0, 3, 3);

X + Y;  //X should now be (1, 1, 4, 4);

But I get these errors because the operator isn't defined. But I already defined the + operator for integers yet it says it's not defined. I think I'm mis-using the friend keyword. Should my == operator be friend? The error I get is:
undefined reference to operator+(Box, int)'|

I defined it at the very last 13 lines of the implementation file.

Header File:

struct Box
{
    int X1, Y1, X2, Y2, W, H;
    Box();                                                                               //Default Constructor.
    Box(int X1_, int Y1_, int X2_, int Y2_);                                             //Alternate Constructor.
    Box(Point UpperLeft, Point LowerRight);
    ~Box(){};                                                                           //Destructor.

    Box& operator ()(int x1, int y1, int x2, int y2);

    Box& operator ()(RECT B);

    friend bool operator == (const Box &B, const Box &B2);

    friend inline bool operator != (const Box &B, const Box &B2);

    Box operator += (Box B);

    Box operator -= (Box B);

    Point MidPointBox (const Box &B);

    Box& PointToBox(Point UpperLeft, Point LowerRight);

    Box& operator = (const Box& B);

    bool Contains(Point P) const;

    bool Contains(const Box& B) const;

    friend ostream& operator << (ostream& Str, const Box &B);

    friend inline …
triumphost 120 Posting Whiz

Switch to Codeblocks even though I love the Dev-C++ interface, the Mingw for it is far outdated.

Also you need to post more detail and probably the function because we cannot guess what you need help with/what the problem may be.

triumphost 120 Posting Whiz

Ahh Solved! You're correct lol. When I don't close the file handle, it crashes so bad. I close it and it works perfectly fine; with the changes you suggested.

triumphost 120 Posting Whiz

Hey I followed your advice and made the changes. I modified it for flipping the rows and stuff but I cannot get it to save. I also saw that you didn't use the BytesPerPixel thing so I implemented that. I also had to do absolute value of height for loading 32 bit bmps since it was a bad alloc when it was negative.

Loading with this works flawless:

    width = Info.bmiHeader.biWidth;
    height = Info.bmiHeader.biHeight;
    size = Info.bmiHeader.biSizeImage;

    unsigned char* TEMP = new unsigned char[size];             //SIZE As BYTES.
    SetFilePointer(hFile, bFileHeader.bfOffBits, 0, FILE_BEGIN);
    ReadFile(hFile, TEMP, size, &Read, 0);
    CloseHandle(hFile);

    unsigned char* BuffPos = TEMP;
    height = (height < 0 ? -height : height);
    int BytesPerPixel = Info.bmiHeader.biBitCount / 8;
    Pixels = new RGB[width * height * BytesPerPixel];       //WIDTH * HEIGHT * BYTES-PP

    for (int I = 0; I < height; I++)
    {
        for (int J = 0; J < width; J++)
        {                                                                 //Flips The ScanLines/Rows.
            Pixels[(height - 1 - I) * width + J].B = *(BuffPos++);
            Pixels[(height - 1 - I) * width + J].G = *(BuffPos++);
            Pixels[(height - 1 - I) * width + J].R = *(BuffPos++);
            Pixels[(height - 1 - I) * width + J].A = (Info.bmiHeader.biBitCount > 24 ? *(BuffPos++) : 0);
        }
        if(Info.bmiHeader.biBitCount == 24)
            BuffPos += width % 4;
    }

    delete[] TEMP;
}

Now I tried to apply the reverse to the Saving but it crashes when it reaches: cout<<"This far";

The code is as follows:

bool BMPS::Save(const char* FilePath)
{
    DWORD Written; …
triumphost 120 Posting Whiz

Ahhhh thank you lots!!! I almost had that. I was using BYTE* instead of unsigned char and I wasn't sure how to get the bytes into the Pixels of type RGB so i deleted it all and used what I posted. I also used the Dib because I was told it'd make drawing on an HDC easier which I have accomplished via the Dib.

I will try exactly what you told me and I'll post back here if unsuccessful. THANK YOU SO MUCH! I spent hours on that lol. Was indeed quite busy learning it all :). ++REP++

triumphost 120 Posting Whiz

I have a union defined as so:

typedef union RGB
{
    unsigned Color;
    struct
    {
        unsigned char B, G, R, A;
    };
} *PRGB;

I'm reading 32 bit and 24 bit bitmaps. I'm trying to Read Pixels from my RGB union and set pixels as well. I know bitmaps are sometimes stored upside down and sometimes up-right. How can I set the pixels at a specific position in the bitmap to a color?

I tried:

RGB BMPS::GET(int x, int y)
{
    return Pixels[y * width + x];
}

void BMPS::SET(int x,int y, RGB color)
{
    Pixels[y * width + x] = color;
}

But sometimes the changed pixels never show and sometimes when they do, they are on the opposite end of the bmp. I'm told I need to flip the bitmap which is contained in my union but I don't know how to flip the union upside down. I'm also told I need to pad the 24 bit bmp but not the 32 bit bmp. I have no idea how to do that using scanlines even though I read a ton of tutorials on this so I used CreateDIBitmap instead as shown below:

HeaderFile:

#ifndef BITMAPS_HPP_INCLUDED
#define BITMAPS_HPP_INCLUDED

#include "GDIPlus.h"

class Bitmap
{
    private:
        PRGB Pixels;
        BITMAPINFO Info;
        int width, height, size;
        BITMAPFILEHEADER bFileHeader;

    protected:
        HDC DC;
        HBITMAP Image;

    public:
        ~Bitmap();

        Bitmap(){}
        Bitmap(const char* FilePath);

        bool Save(const char* FilePath);

        HDC ReturnDC(){return DC;}

        int Width(){return (width < 0 ? -width : width);}

        int Height(){return (height …
triumphost 120 Posting Whiz

From a class I wrote a while back.. I used: <td(.*?)</td>
which is a non greedy regex so it will return all matches. Anyway this is the stuff I was speaking of. I used it to create a stock ticker that grabbed Stocks from a website and display their values, etc..

PregMatchAll is actually from PHP but I sorta translated it to Cpp. StrPos will just convert the regex matches to a position in the file. Substr will get us the info between the tags.

void preg_match_all(string Source, boost::regex &expression, string &ID)
{
       try
       {
           std::string::const_iterator start, end;
           start = Source.begin();
           end = Source.end();
           boost::smatch what;
           boost::match_flag_type flags = boost::match_default;

           while(boost::regex_search(start, end, what, expression, flags))
           {
                //Destination = boost::regex_replace(Source, expression, "");
                ID = what[0];
                start = what[0].second;
           }
       }
       catch(exception &e)
       {
           cout<<"Exception Caught.. Function: preg_match_all.\n\n";
       }

    return;
}


static size_t strpos(string Data, string Regex, int Offset, int SizeOf_Regex, int additional)
{
    size_t Found = 0;
    try
    {
        Found = Data.find(Regex.c_str(), Offset, SizeOf_Regex) + additional;
    }
    catch(exception &e){}

    return Found;
}

string  DataHolding = "Some HTML File";  //This will be our source.

int main()
{
   size_t Start, End;
   boost::regex SnExpression("<[a-z]+ class=\"wsod_smallSubHeading\"", boost::regex::icase);
   boost::regex SxExpression("<h1 class=\"wsod_fLeft(.*)\" style=\"margin-top:6px;\">", boost::regex::icase);

   string StockID, StockX;
   preg_match_all(DataHolding, SnExpression, StockID);   //Match the first part of the tags..
   preg_match_all(DataHolding, SxExpression, StockX);    //Match the end tag..

   Start = strpos(DataHolding, StockX, 0, StockX.size(), StockX.size());  //Get The position of the END of the start tag.
   End = strpos(DataHolding, StockID, Start, StockID.size(), -1);         //Get the position of the BEGINNING of …
triumphost 120 Posting Whiz

Allman style.. the others are so difficult to track which braces match which.. well for me at least.

triumphost 120 Posting Whiz

I'm trying to have my function return an OPENFILENAME struct. Problem: It returns it fine and everything except that I cannot print the filetitle :S At the moment, it prints the path of the file perfectly fine but when it comes to printing the file title via cout, it prints a bunch of random characters and I have no clue why. Please help me.

OPENFILENAME OpenFileDialog(bool InvertSlashes = false)
{
    OPENFILENAME OFN;
    char FilePath[MAX_PATH];
    char FileTitle[MAX_PATH];

    ZeroMemory(&OFN, sizeof(OFN));
    OFN.lStructSize = sizeof(OFN);

    OFN.lpstrInitialDir = 0;
    OFN.lpstrFile = FilePath;
    OFN.lpstrFile[0] = '\0';
    OFN.nFilterIndex = 1;
    OFN.nMaxFile = sizeof(FilePath);
    OFN.lpstrFileTitle = FileTitle;
    OFN.lpstrFileTitle[0] = '\0';
    OFN.nMaxFileTitle = sizeof(FileTitle);
    OFN.lpstrFilter = "All Files\0*.*\0\0";
    OFN.lpstrDefExt = 0;
    OFN.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;

    if (GetOpenFileName(&OFN) != 0)
    {
        if (InvertSlashes)
        {
            string TempFilePath = OFN.lpstrFile;
            replace(TempFilePath.begin(), TempFilePath.end(), '\\', '/');
            strcpy(OFN.lpstrFile, TempFilePath.c_str());
        }
    }
    return OFN;
}




int main()
{
    OPENFILENAME Test = OpenFileDialog();
    cout<<Test.lpstrFile<<endl;        //Prints perfectly fine.
    cout<<Test.lpstrFileTitle<<endl;   //Prints random characters.
}
triumphost 120 Posting Whiz

Line 53 as well..

ostream &Circle::operator << (ostream &mystream,Circle &c)

triumphost 120 Posting Whiz

Double Buffer the form.. Click it and set the buffering property to double.

triumphost 120 Posting Whiz

Here try this.. I missed a bracket above and a couple other details as I wrote that on the spot without a compiler.. Also I didn't notice that you had both Age AND Money for your constructor. Thus instead we change all the int's to a pair or a map and add the ostream operator. In codeblocks this looks much easier on the eyes! Looks way harder on this forum due to the extra large font..

#include <windows.h>
#include <iostream>
#include <vector>
#include <assert.h>
#include <map>

using namespace std;

class Members
{
    private:
        vector< pair<int, int> > Data;

    public:
        Members(int age = 0, int money = 0);
        ~Members(){}


        int size();
        pair<int, int>& operator [](int I);
        const pair<int, int>& operator [](int I) const;
        operator const vector< pair<int, int> >& () const;
        Members& operator ()(int age = 0, int money = 0);
        Members& operator << (const pair<int, int>& t);
        friend ostream& operator << (ostream& Str, const Members& Pairs);
        Members& Insert(int Index, pair<int, int> ValueToInsert);
        Members& Remove(int Index);
};

Members::Members(int age, int money)
{
    Data.push_back(make_pair(age, money));
}

int Members::size(){return Data.size();}   //Just return the size of the vector.

pair<int, int>& Members::operator [](int I)
{
    assert(I >= 0 && !Data.empty());        //Make sure the indicies accessed are correct.
    return Data[I];                     //return the value at that position in the vector.
}

const pair<int, int>& Members::operator [](int I) const
{
    assert(I >= 0 && !Data.empty());        //Make sure the indicies accessed are correct.
    return Data[I];                     //return the value at that position in the vector.
}

Members::operator const vector< …
triumphost 120 Posting Whiz

For how it could be done see:

class Members
{
    private:
        vector<int> Data;

    public:
        Members(){}
        Members(int I);
        ~Members(){}


        int size();
        Members& operator [](int I);
        operator const vector<int>& () const;
        Members& operator ()(int I);
        Members& operator << (const int& t);
        Members& Insert(int Index, int ValueToInsert);
        Members& Remove(int Index);
};

int Members::size(){return Data.size();}   //Just return the size of the vector.

Members& Members::operator [](int)  //Don't forget to overload the const version of this.
{
    assert(I >= 0 && !Data.empty());        //Make sure the indicies accessed are correct.
    return Data[I];                     //return the value at that position in the vector.
}

Members::operator const vector<int>& () const
{
    return Data;
}

Members& Members::operator ()(int I)
{
    Data.push_back(I);      //Same thing as below.. Insert every int into the vector.
    return *this;
}

Members& Members::operator << (const int& I)    //Overloads the insertion operator.
{
    Data.push_back(I);      //Every int inserted gets pushed back to the vector.
    return *this;
}

Members& Members::Insert(int Index, int ValueToInsert)
{
    //Code to insert at a position in the vector. ;) I'll leave this up to you. It's about 1 line
    return *this;
}

Members& Members::Remove(int Index)
{
    //Code to remove a value at that position in the vector. I'll also leave this up to you.
    return *this;
}


//Finally you use it like:

Member X(1);
X(2);
X(3);
X<<4<<5<<6<<7;
X<<8;

for (int I = 0; I < X.size(); I++)
    cout<<X[I]<<endl;

Now you can learn to overload the rest of the operators to check for equality, ostream for printing them, etc.. but this class is a bit …

triumphost 120 Posting Whiz

What should I be using? Should I be using _T? or L? Or Neither?
I know some functions end with the A for Ansi and some end in W for the Unicode version but I have no clue what I want to use.

if I use _T would I have to change all my strings to wstrings? if I use L would I have to do that too?

if I use _T would I have to change all my MessageBoxes to MBW or MBA or just MB? What about StrLen would I change that too? Also some functions require lengths vs character bytes. Does this affect it?

Ohh and I almost forgot. What is the difference between _Unicode and Unicode :S

triumphost 120 Posting Whiz
//For .Net:

enum {F9_KEYID = 1, F10_KEYID = 2} ;
RegisterHotKey(0, F9_KEYID, MOD_NOREPEAT, VK_F9);
RegisterHotKey(0, F10_KEYID, MOD_NOREPEAT, VK_F10);


MSG msg = {0};
PeekMessage(&msg, 0, 0, 0, 0x0001);   //0x0001 means No Repeat..
TranslateMessage(&msg);
switch(msg.message)
{
    case WM_HOTKEY:
        if(msg.wParam == F9_KEYID)
        {
            MessageBox::Show("F9 Pressed");
        }
        else if(msg.wParam == F10_KEYID)
        {
            MessageBox::Show("F10 Pressed");
        }
}


For WinAPI:
while(GetMessage(&msg, 0, 0, 0))
{
    if(msg.message == WM_HOTKEY)
    {
        switch(HIWORD(msg.lParam))
        {
            case F9_KEYID : MessageBox.Show(NULL, "Key Pressed", "F9 Pressed", MB_OK); break;    //I may have mucked up my parameters here but excuse me. I'm a bit tired. I think I need to switch caption with the message. One is Caption, Other is text. Don't remember.
            case F10_KEYID : MessageBox.Show(NULL, "Key Pressed", "F10 Pressed", MB_OK); break;
            default: MessageBox.Show("some other hot key was pressed");
        }
    }

    //Translate.. Dispatch.. whatever else..
}
triumphost 120 Posting Whiz

You could TRY getting a handle to the window, using SendMessage WM_GetText and see if you get the text. If you do, sort through it for the variable you want..

Another way would be to hook the program and grab the information you want. Also one other way I can think of is to ReadProcessMemory. This should be used if you know how to get the memory address of the variable you want to read.

triumphost 120 Posting Whiz

Write the variable to a file everytime it changes, read it with your other program.

triumphost 120 Posting Whiz

Hey you solved the first problem but unfortunately the templated class still throws like 50m errors unless everything is inside the class.

I researched it and apparently it's common to define the templated functions in the class itself :S Apparently boost does this.

Anyway my entire templated class HEADER looks like and all my definitions are in the CPP file but that gives errors like mad:

template <typename T>
class CustomType
{
    private:
        vector<T> TypeData;
        void Insert(){}
        template<typename A, typename... Args>
        CustomType& Insert(A FirstArg, const Args... RemainingArgs);

    public:
        CustomType(){}
        ~CustomType(){}

        template<typename A, typename... Args>
        CustomType(A FirstArg, const Args... RemainingArgs);

        int size();

        CustomType& operator [](int I);

        const CustomType& operator [](int I) const;

        operator const vector<T>& () const {return TypeData;}

        bool operator == (const CustomType &CT) const;

        bool operator != (const CustomType &CT) const;

        CustomType& operator = (const CustomType &CT);

        CustomType& operator >> (const T& t);

        void SetLength(size_t NewLength);

        template<typename A, typename... Args>
        CustomType& operator ()(A FirstArg, const Args... RemainingArgs);

        inline ostream& operator << (ostream& Str, const CustomType &CT);
};

Since the above gives errors I just put all the definitions back inside the class of the header instead.

triumphost 120 Posting Whiz

:D I always read all of mike's posts. Him, Narue, Ancient Dragon, Lambdabeta, and Deceptikon. Even if its pages long. Turns out he's right though because it was taking me 5 mins to compile 13k lines of code that was IN the classes..

I separate them and it's a lot more than 13k but it compiles in roughly a 10-20 seconds. So.. I actually think that it NEEDS to be separated. Also when compiling, it only re-compiles the file I changed which is a huge benefit! But I still cannot get my operator overloads working. Especially the ostream and the questions I posted in my last post above.

triumphost 120 Posting Whiz

Can't I do that same thing with variadic templates? I don't know how though :S

triumphost 120 Posting Whiz

Currently I use:

DWORD ThreadProc(LPVOID lpParameter)
{
    void (* function)() = (void (*)())lpParameter;
    function();
    return 0;
}

void Threading(HANDLE &hThread, DWORD &ThreadID, void* FunctionToPass)
{
    hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, (void*)FunctionToPass, 0, &ThreadID);
}

And I want to call it like:

Handle hThread; DWORD ThreadID;

Threading(hThread, ThreadID, AnyFunctionHere);

That way my Threading Function will create a thread and run any function. How can I pass it a function that has 0 or more parameters?

triumphost 120 Posting Whiz

I know that the C-Style cast aka (Type)Variable is basically trial an error of all the casts put together. At least that's what I was taught.

Example:

(double) Variable would be equivalent to trying all of the following and whichever works first, that's used:

const_cast<double> Variable
reinterpret_cast<double> Variable
static_cast<double> Variable.

Whichever of the above works is the one the program will use. Now in the above, it never uses dynamic_cast. I'm not sure why but I read up on dynamic casting and apparently its to do with upcasting and downcasting.

Btw, static_cast is used when you know the type your casting from doesn't need a runtime check to be casted to another type. It's used to put reverse implicit conversions and put additional restrictions. I personally only used this on classes so far.. I usually prefer to use C-Style casting though.

That's about it. Dynamic cast someone else will have to explain because I don't know it.

triumphost 120 Posting Whiz

Create a WINAPI/Win32 Application.. Remove all the callbacks and stuff.. Use WinMain instead and it will have no console.

triumphost 120 Posting Whiz

Hey I'm having a problem Splitting them.. I split everything and they all compile but there's actually two problems.

One is a template class and the other is the overloading of operator << with ostream.. My other operators also give the same problem if they have two arguments.
Operator problem:

//File.HPP

class Point
{
   Point(){}    //One.. I don't know if I should put the braces here or outside the class.
   ~Point(){}   //Same as above.

   friend ostream& operator << (ostream& Str, const Point &PT);  //Declaration.   
}

//File.CPP

inline ostream& Point::operator << (ostream& Str, const Point &PT)
{
    Str<<"("<<PT.X<<", "<<PT.Y<<")";
    return Str;
}

//Gives the error: error: 'std::ostream& Point::operator<<(std::ostream&, const Point&)' must take exactly one argument|
//Whereas when inside the class I get no error :S

Template Problem:

#ifndef TEMPLATES_H_INCLUDED
#define TEMPLATES_H_INCLUDED
#include <iostream>
#include <vector>

using namespace std;

template <typename T>
class CustomType
{
    private:
        vector<T> TypeData;

    public:
        CustomType(){}
        ~CustomType(){}

         //Other definitions here..
        CustomType& operator >> (const T& t);

        void SetLength(size_t NewLength);
        inline ostream& operator << (ostream& Str, const CustomType &CT);
};

#endif // TEMPLATES_H_INCLUDED

//Then In the .CPP file I put the definitions but it Errors like mad.

When I put all the definitions for the template in the header file inside the class, I get no errors :S Same with the operators. As for the constructor, should I leave the braces in there since its default anyway? And it's so small :S