triumphost 120 Posting Whiz

Embedded it inside an internal struct. Not sure if you can use lambda functions here but meh I prefer the internal struct.

void RMatrix::RepMatrixf()
{
    const int MAX = 100;   // PROBLEM STARTS BELOW
    struct
    {
        void RepMatrix (int NDR, int size, int PosIR, int calls) // PosIR and calls initates at 0
        {
            if (calls == 0)
                memset(Matrix, 0, sizeof(Matrix));     // clears previous values of matrix **note memset only can set values for 0 or -1 in ints
            static int Row = 0;                        // Row, stored for recursion
            static int RepIndex[MAX];                  // stores positions of variable to be turned true
            for ( ; PosIR < size-(NDR-1); PosIR++)     // Position index Replacement is less than number of digits being replaced
            {
                // Increase of each possible combination index
                RepIndex[calls]=PosIR;                 // sets the replacement value for static array based of which call

                if (NDR==1)                              // NDR is last digit
                {
                    for (int x = 0; x<=calls; x++)       // all possible replacement permutation are changed to false
                    {
                        Matrix[Row][RepIndex[x]]=true;
                    }
                    Row++;                                // row is increased
                }
                if (NDR>1)                             // recursively calls for ever digit in need of being replaced
                {
                    RepMatrix((NDR-1), size, PosIR+1, calls+1);
                }
            }
            return;
        }
    } Inner;

    Inner.RepMatrix(Replace, TotalN, 0, 0);
}
triumphost 120 Posting Whiz

Link to libwsock32.a and any necessary libraries.

In Visual studio you can link by doing #pragma comment(lib, "libwsock32.a");

triumphost 120 Posting Whiz

I do not see what is implicit about it? It's all integers and they are all of the same type.

Test Foo{1, 2, 3} but not Test Foo = {1, 2, 3}

With the above I might as well do Test Foo(1, 2, 3).

Mike's tutorial has:

int_vector v{1,2,3,4,5}; //construction syntax with {} enclosed lists.

int_vector v2 = {6,7,8,9,10};

Yet I cannot do the same :S

If my constructor is not explicit it works. If it is explicit it does not work unless I provide that extra constructor.

triumphost 120 Posting Whiz

I have a Two Test classes that use variadic templates but I made the constructors explicit so that the compiler doesn't convert anything and leave everything as it was.

One class was Array and the other was called 2DArray. When I intialize 2DArray, the compiler was converting its arguments to the ones that Array was intialized with so explicit stopped this and now it strictly requires Array as the arguments. Example:

class TestClass   //Array of ints.
{
    void Insert(){};
    template<typename T, typename... Args>
    TestClass& Insert(T FirstInt, const Args... RemainingInts)
    {
        cout<<(FirstInt);
        Insert(RemainingInts...);
        return *this;
    }

    public:
    explicit TestClass(){};
    TestClass(initializer_list<int> T)
    {
        initializer_list<int>::iterator it = T.begin();
        for (; it != T.end(); ++it)
            cout<<*it;
    }

    template<typename T, typename... Args>
    explicit TestClass(T FirstInt, const Args... RemainingInts)
    {
        cout<<(FirstInt);
        Insert(RemainingInts...);
    }
    ~TestClass(){};
};

class TestArrayClass  //Array of array of ints.
{
    void Insert(){};
    template<typename T, typename... Args>
    TestArrayClass& Insert(T FirstArray, const Args... RemainingArrays)
    {
        cout<<(FirstArray);
        Insert(RemainingArrays...);
        return *this;
    }

    public:
    explicit TestArrayClass(){};
    TestArrayClass(initializer_list<TestArrayClass> T)
    {
        initializer_list<TestArrayClass>::iterator it = T.begin();
        //Push_back all Values onto a vector<Test>
    }

    template<typename T, typename... Args>
    explicit TestArrayClass(T FirstArray, const Args... RemainingArrays)
    {
        cout<<(FirstArray);
        Insert(RemainingArrays...);
    }
    ~TestArrayClass(){};
};

Now if I remove the constructor for the initializer_list, I cannot initialize the class like:

Test Foo = {1, 2, 3, 4, 5} because it said Test from initializer_list would use explicit constructor and refused to compile. If I remove the explicit, then TestArray can be initialized like:

TestArrayClass FooArray = TestArrayClass(1, 2, 3, 4) instead of TestArrayClass(Test(1, 2, 3), …

triumphost 120 Posting Whiz

+1 for that tutorial! + another 1 for removal of the move assignment operator. Bookmarked your tutorial and the post above since no other sites mention this information. I was wondering why they looked the same but also why it said ambiguous overload since the tutorials I was reading said I needed both! One for copying and one for moving.

Now supposed it was a class as simple as in my example. Maybe even the exact same test class. What if it didn't implement copy con or move con and the compiler generated it, would I still use copy/swap idiom? Or would I just do the assignment operator the same as in:

Type& operator = (const Type& T)
{
    if (this != &T)
    {
        this->SomeMember = T.SomeMember;
    }
    return *this;
}

OR would I do the copy-swap? The next thing I read is that I should not (should not have to) implement copy-swap or copy/move constructors for POD types and vector based classes where the underlying type is just simple. Is this true? Does that mean my test class is bad since I used a vector and did the swap on it? Oh and my final question before I feel safe doing it on my own is: Why does your tutorial and some of the other have throw() next to the swap while other tutorials don't? I read on stackoverflow that it is not necessary and neither is noexcept :S

triumphost 120 Posting Whiz

I'm trying to test my copy con and move con as well as their assignment operators. It NEVER gets invoked :S Copy con gets invoked just fine but the assignment operators are never called and neither is the move constructor. How can I test it to make sure it works just right? I've read a TON of tutorials on it to make sure I got everything down to the very last detail but now when it's time to test it, only the copy con is invoked. It doesn't actually load or save a bitmap. It's just a class I called that and put a vector member of a struct so I don't have to use pointers for now.. (Defined as vector<BYTE> Pixels). No implementation, just bare testing.

I just don't want under the hood problems or future problems. It's just a class I created specifically for learning Copy/Move/Swap semantics but I never know if I'll need it.

I'm testing with:

    Bitmaps A = Bitmaps("C:/Meh.bmp");
    Bitmaps B(Bitmaps("C:/Meh.bmp"));
    Bitmaps C = A;

    //I'll write code to test if change on one data member affects that of another object later.

And implementing with:

//Just a huge initiaization list. Copy Constructor:
Bitmaps::Bitmaps(const Bitmaps& Bmp) : Pixels(Bmp.Pixels), Info(Bmp.Info), width(Bmp.width), height(Bmp.height), size(Bmp.size), bFileHeader(Bmp.bFileHeader), TransparentColor(Rgb(0)), DC(0), Image(0){std::cout<<"Copy Constructor Called.\n"}

//Just a huge initialization list. Move Constructor:
Bitmaps::Bitmaps(Bitmaps&& Bmp) : Pixels(0), Info(), width(Bmp.width), height(Bmp.height), size(Bmp.size), bFileHeader(), TransparentColor(Rgb(0)), DC(0), Image(0)
{
    std::cout<<"Move Constructor Called.\n"
    this->Swap(Bmp);
    Bmp.Pixels.clear();  //A vector.
}

Bitmaps& Bitmaps::operator = (Bitmaps Bmp) //Pass …
triumphost 120 Posting Whiz

Ohhhh I see! That never occured to me that such a thing can be done. I have never seen such code before.

I created the class myself and it was a handle returned from CreateThread but there's no way to tell what data it actually holds. All I know is that CreateThread gave me the handle and the compiler kept complaining about it being a pointer member and the move and copy con.

I'll look into your suggestions then I'll implement it but I have to learn it first. Thank you lots! I'll mark it solved in a sec. Hopefully it works.

EDIT: With that implementation, is it still safe to supply a move constructor? Should I supply one or is it just not necessary?

triumphost 120 Posting Whiz

But that's not possible :S I cannot copy a void* with no size. I can't do a memcpy on it because it's a thread I can't do std::copy because the thread has no iterator and no size either. Can't do sizeof(hThread) because it's just a void pointer.

For the Brushes they are also defined as void* so how do I copy that? I understand if I knew the size or if it pointed as something reasonable but in this case it's very difficult. Maybe I can dereference it and attempt to copy but I know almost 100% that it won't work.

I'm not sure that I can copy a thread or an hBrush. It seems closely related to copying the handle of a file and closing one but not the other. Then the other will just dangle there.

Yet the compiler complains about me not providing a copy con or move con. I made one to get it to shut up but the one I made is a shallow copy. Move con is fine. Copy con definitely isn't. When the handle in one object is destroyed, the handle in it's copy is as well. I'm not sure whether to ignore the compiler or not because this is very silly but I always learned that I should do the copy and move when I have pointers.

EDIT: I tried putting it into a Smart Container. Uniqueptr to be exact but it doesn't help. Neither does shared. It still complains.

triumphost 120 Posting Whiz

@Nathan. The reason I was asking was because it's a handle. And it's a handle to a thread. Copying a handle will just make it point to the same data. I understand the move constructor will just steal the pointer to the thread aka the handle but copying? I do not understand the copy part of that.

If I'm to copy a handle, both will still point to the same place because I cannot copy a thread or a Pen/Brush. When the old object gets destroyed, the thread will get destroyed and the handle to the thread in the new object will point no where.

Only thing I can think of is to copy the handle and set the old one to 0. If I set the old one to 0, the Old object will have an invalid handle. Copy con is supposed to copy not steal :S. In the case of Brushes I'm confused though because I'd copy the handle to the brush and then what? I can't just set it to 0. I have to select the object back no? The destructor selects it back..

I'm just not sure how to deal with handles.

triumphost 120 Posting Whiz

Reading an INI file: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724353%28v=vs.85%29.aspx

Use the WINAPI for that unless you plan on doing it manually and iterating through each line and constructing tokens from it.

An INI has the sections and the keys. You want to provide the key and get the value under that section for that key. GetPrivateProfileString does that.

GetPrivateProfileString(Section, Key, DefaultValue, FileName);

You can also write an Ini using WritePrivateProfileString. GetPrivateProfileInt is the same as the string version except that it automatically does the conversion from int to string for you.

If you know all the keys, iterating through them all with a for-loop and storing the values in a vector would help you lots.

triumphost 120 Posting Whiz

"warning: 'class Debug' has pointer data members but does not override 'Debug(const Debug&)' or 'operator=(const Debug&)' [-Weffc++]"

The only pointer member I see here is the HANDLE hTHread. Why should I override my constructors or add a move/copy to this class as the compiler suggests?

class Debug
{
    private:
        HANDLE hThread;
        bool ConsoleActive;
        friend DWORD ThreadProc(LPVOID lpParameter);
        friend long __stdcall WindowProcedure(HWND window, uint32_t msg, WPARAM wp, LPARAM lp);

    public:
        Debug();
        explicit Debug(bool CreateDebugConsole = false, bool CreateDebugWindow = false);
        //Other constructs and destructor..
};

It says the same for:

class Brushes
{
    private:
        HDC     hDC;
        HBRUSH  NewBrush;
        HBRUSH  OldBrush;

    public:
        Brushes(HDC hdc, COLORREF colour);
        //Destructor and other constructors here..
};

I read this tutorial: http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/CLASSES-PTRS.html
It doesn't use the copy swap idiom or something like that but it explained to me the basics. I just don't see a reason to use it for HBRUSH/HPEN or Handles :S?

triumphost 120 Posting Whiz

Ah mike thank you for that lesson! BUT I have seen users delete pointers they have gotten from objects. Some do it because they come from a language such as C# and do not understand when to use delete and others do it just for testing what will happen. So I was just thinking in terms of making an object absolutely fool proof. I myself would not delete a pointer from my own object or some library or anyone else's code unless it provides a way to do that as you mentioned.

But what you have given is the best idea using the std::pairs and iterators. I never thought about that and never thought that anyone would suggest that. That really really does help the most! I was playing around with it at first and using the pointer to the vector to gain access to begin and end iterators. I like the std::pair solution thought so I think I'll go with that.

triumphost 120 Posting Whiz

^Because the accessor functions only allow you to access one element at a time unless a for-loop is used. I want to return the entire array rather than just one element at an index.

triumphost 120 Posting Whiz

How can I create a Modifiable Const vector but make it unable to be resized? Either that OR I want to return a pointer from a function but not allow the user to delete it.

This is my example so far:

class MemberRawArrayVector
{
    private:
        vector<unsigned char> MemberRawArray;

    public:
        MemberRawArrayVector(int Size) : MemberRawArray(Size) {}

        void SetMemberValue(char Value, int Index) { MemberRawArray[Index] = Value; }

        const vector<unsigned char>* GetMemberArray() { return &MemberRawArray; }
};

class RawMemberArray
{
    private:
        unsigned char* RawArray;

    RawMemberArray(int Size) : RawArray(new unsigned char[Size]) {}
    ~RawMemberArray() { delete[] RawArray; }

    void SetMemberValue(char Value, int Index) { RawArray[Index] = Value; }

    unsigned char* GetMemberArray() { return RawArray; }
};

In the first class with vectors, it returns the member array and it is read only to prevent resizing. Thing is, I want to be able to modify the values in it without the SetMemberValue function.

In the second class, I return the raw pointer but as we know, the user can easily delete this pointer before the destructor gets to it. I want to prevent deletion by force! Inother words I want them to have access to the pointer but at the same time not allow them to delete it at all. Only the class should be able to do deletion. I cannot have a const pointer because I need to modify the values it points to.

This is the reason I created the two classes as examples. One has what the other doesn't. The vector can't …

triumphost 120 Posting Whiz
  1. You never used NumCount. Thus you loop went infinitely.
  2. You never incremented total every time they entered a number.
  3. None of your variables were initialized so the values could be anything.
  4. If using codeblocks, right click anywhere in the source editor and press format A-Style. Then you can post it here. It's hard to read code that isn't indented.

    int main(int argc, char* argv[])
    {
        int numCount = 0, total = 0;
        double average;
        cout << "How many numbers do you want to average? ";
        cin>> numCount;
        for (int count = 0; count < numCount; count++)
        {
            int num;
            cout << "Enter a number: ";
            cin >> num;
            total += num;
        }
        average = total / numCount;
        cout << "The average is " <<average<<endl;
    
        cin.get();
        return 0;
    }
    

Edit: WTH? Something is wrong with Daniweb's code parser :S So you have to parse the code twice. At least for me that's how the indentation stayed. I think it's a glitch.

triumphost 120 Posting Whiz

Anyone? I fixed my constructor problem but the casting still does not work correctly.

Is there any way to make this work:

    Box B;
    HWND Desktop = GetDesktopWindow();
    GetWindowRect(Desktop, (LPRECT) &B);

    cout<<B;    //Prints 0, 0, 1366, 768 For X1, Y1, X2, Y2 which is correct!
    cout<<B.W;  //Prints 0 Width. Wrong!
    cout<<B.H   //Prints 0 Height. Wrong!

All I want is for the width and height to work. Is there an operator that performs "(T1*) &T2" Conversion?

triumphost 120 Posting Whiz

I'm a bit confused atm, I don't know when to use const T& or T& or T as a parameter.

Currently I'm doing:

void Resize(std::vector<T> &Vec, const size_t &NewLength)  //Ahh edited the function as a result of Lucaci's answer.
{
    Vec.resize(NewLength);
}


//But thinking of doing:

void Resize(std::vector<T> &Vec, size_t &NewLength)
{
    Vec.resize(NewLength);
}

//And:

void Resize(std::vector<T> &Vec, size_t NewLength)
{
    Vec.resize(NewLength);
}


//The reason I'm thinking like this is because I may have to pad the vector like so:

void Resize(const std::vector<T> Vec, const size_t &NewLength, const T& Padding)
{
    Vec.resize(NewLength, Padding);
}

Now my question is: Which is the best to use? If I use const T&, will it create temporaries every single time? Inother words, will it create a copy of the padding every single time the function is called? Will it create a copy of the padding only once for the resize or will it do it NewLength amount of times or not at all?

Basically I want to know if const T& works the same as T&. I don't want to copy anything as I need the speed. Also what is the difference between const T* vs const T&?

triumphost 120 Posting Whiz

I don't understand what you're asking. I provided an example of what will need to be done.

It works like this:
Reads Information from the file into a vector.
Each indicies in the vector will contain 1 line from the file.
Thus in the example, the vector is of size 6 and contains 6 lines including Start and End.

Tracker will then of course be size 6 as well and the tracker contains a line number and the contents of the line.

So from my example: tracker[0] is "Start", tracker[1] is "Word 1", tracker[2] is "Word 2"... tracker[5] is "End".. etc.

To find out the index of a line, you simply do:

Tracker.find("Word 1")->second    //This will give you index 1 aka line 1 in my example.
Tracker.find("Word 4")->second    //This will give you index 4 aka line 4 in my example.
Tracker.find("End")->second       //This will give you whatever inidices contain the word "End"

//If tracker contains more than one of the same word, it will print the index of every where that it's found.

PrintMultiMapKeyIndicies(Tracker, "Word 4");  //Will print every line Number that is "Word 4"

What you do with the code provided is up to you. It doesn't save the indicies in the key. It saves the contents in the key and when you search for that content, it will give you a line Number/index.

If you want to make a vector or array the same size as the amount of lines found, you do:


       
triumphost 120 Posting Whiz

Read a file into a vector.. For each line in the file, add it to the tracker and keep track of it's index.

Example File:

Start
Word 1
Word 2
Word 3
Word 4
End

It doesn't ignore the "Start" and "End" which you can remove easily so that it ignores. It reads that file, and keeps track of which lines the word was found on and fills a vector with the words, and a tracker with the indicies.

void PrintMultiMapKeyIndicies(std::multimap<std::string, int> &Tracker, const std::string &Key)
{
    std::multimap<std::string, int>::iterator it;
    std::multimap<std::string, int>::iterator last;

    it = Tracker.find(Key);
    if (it == Tracker.end())
    {
        std::cout<< "Key Not Found!" <<std::endl;
        return;
    }

    std::cout<< "The Key: "<< Key <<" is located at the following Indicies:\n" <<std::endl;
    last = Tracker.upper_bound(Key);

    for (; it != last; ++it)
        std::cout<< it->second <<std::endl;
}

int main()
{
    std::vector<std::string> FileContents;
    std::ifstream File("C:/Users/UserName/Desktop/SomeFile.txt", std::ios::in/*| std::ios::binary*/);
    if (File.is_open())
    {
        std::string Line;
        while (std::getline(File, Line))
            FileContents.push_back(Line);
        File.close();
    }

    std::multimap<std::string, int> Tracker;
    for (size_t I = 0; I < FileContents.size(); I++)
        //if (FileContents[I] != "Start" && FileContents[I] != "End")
            Tracker.insert(std::pair<std::string, int>(FileContents[I], I));

    PrintMultiMapKeyIndicies(Tracker, "Word 2");
}
XodoX commented: Thank you +2
triumphost 120 Posting Whiz

It uses a for loop, pairs the index with its value and inserts it into the multimap.

You find the value you want and the multimap will give you the index.

triumphost 120 Posting Whiz

Why does the following code skip the initialization of values of the temporary created?

Box::Box() : X1(0), Y1(0), X2(0), Y2(0), W((X2 < 0 ? -X2 : X2) - (X1 < 0 ? -X1 : X1)), H((Y2 < 0 ? -Y2 : Y2) - (Y1 < 0 ? -Y1 : Y1)) {std::cout<<"Con1";}

Box::Box(RECT B) : X1(B.left), Y1(B.top), X2(B.right), Y2(B.bottom), W((X2 < 0 ? -X2 : X2) - (X1 < 0 ? -X1 : X1)), H((Y2 < 0 ? -Y2 : Y2) - (Y1 < 0 ? -Y1 : Y1)) {std::cout<<"Con3";}

Box::Box(int x1, int y1, int x2, int y2) : X1(x1), Y1(y1), X2(x2), Y2(y2), W((X2 < 0 ? -X2 : X2) - (X1 < 0 ? -X1 : X1)), H((Y2 < 0 ? -Y2 : Y2) - (Y1 < 0 ? -Y1 : Y1)) {std::cout<<"Con2";}

Box::Box(Point UpperLeft, Point LowerRight) : X1(UpperLeft.X), Y1(UpperLeft.Y), X2(LowerRight.X), Y2(LowerRight.Y), W((X2 < 0 ? -X2 : X2) - (X1 < 0 ? -X1 : X1)), H((Y2 < 0 ? -Y2 : Y2) - (Y1 < 0 ? -Y1 : Y1)) {}

Box::~Box(){}




//Testing the default constructor.
Box B;
std::cout<<"B was constructed";
GetWindowRect(SomeWindowHandle, (LPRECT)&B);
cout<<B.W<<endl;

The above prints "Con2, Con1, B Was Constructed" but yet the values of Width(W) and Height(H) are 0! I'm not sure why both constructors were called before it even hits GetWindowRect :S This leads me to believe that when the constructor was called, the initialization of the members were skipped! Why? The stuff inbetween the braces print AND the values of X1, …

triumphost 120 Posting Whiz

So let me get this right. Uhh you want to check the position of specific values in the array and keep track of their position?

I'd probably use std::multimap from the <map> header.

    int TestArray[11] = {3, 9, 5, 1, 4, 2, 7, 8, 11, 10, 4};

    multimap<int, int> Tracker;
    for (int I = 0; I < 11; I++)
        Tracker.insert(pair<int, int>(TestArray[I], I));  //I will be the index.. The values will be the keys. You search for a value, it returns an index.

    multimap<int, int>::iterator it;
    it = Tracker.find(4);
    cout<< it->second <<endl;                    //Using an iterator to access values.

    cout<< (++it)->second <<endl;                    //This will print the second occurence of the value 4.

    cout<< Tracker.find(4)->second <<endl;      //Using an iterator indirectly to access values.

    cout<< (++Tracker.find(4))->second <<endl;  //Finds the second occurence of the value 4.

    cout<< Tracker.find(5)->second <<endl;      //Finds the occurence of the value 5.

All you have to do is enter the value you wish to search for, and it will return the position/index of it.

triumphost 120 Posting Whiz

Well that's easy to fix. You're not keeping track of employee pay in your program.. You're currently just printing it and only keeping track of one Day (A.K.A. the day the user enters). In the for-loop, you simply add up all the pay. As such you get:

    for (Day = 0; Day < workDays; Day++)
    {
        cout << Day + 1 << "\t" << pow(2, Day)* 0.01 << endl;
        pay += pow(2, Day)* 0.01;
    }
triumphost 120 Posting Whiz

The reason is because at the end of your for-loop, Day will be incremented by 1!
In a for-loop, the initialization variable is always incremented at the end! Thus when your for-loop is finished, Day will have a value of 6 and not 5. The solution would be to just minus 1 from Day at the end of the loop. Maybe right before you cout<<Fixed;

It's either that OR you start your initialization at 0:

    for (Day = 0; Day < workDays; Day++)
        cout << Day + 1 << "\t" << pow(2, Day)* 0.01 << endl;
triumphost 120 Posting Whiz

I have the following code to take a bitmap of a portion of the screen specified by the Box Area.

Area is just a struct that holds Width, Height, X1, Y1, X2, Y2 and represents a box. Basically a RECT with additional features.

For some reason, if Box is (0, 0, 100, 100); It will take a perfect screenshot of the 100x100 area. If Box's X1 or Y1 is more than 0 (Ex: (10, 10, 110, 110); It will take a screenshot that is 100x100, except that the first 10 rows and columns will be black! It also does this for any window that I specify that is not the desktop. I cannot figure out why! I tried everything from changing Bitblt to the correct area and offsets, etc.

Any Ideas?

Bitmaps::Bitmaps(HWND Window, Box Area, uint32_t BitsPerPixel) : Pixels(nullptr), width(Area.W), height(Area.H), size(0), TransparentColor(Rgb(0)), DC(0), Image(0)
{
    memset(&Info, 0, sizeof(BITMAPINFO));
    HDC hdc = GetDC(Window);
    BITMAP bmp;
    HBITMAP hbmp = (HBITMAP)GetCurrentObject(hdc, OBJ_BITMAP);

    if (GetObject(hbmp, sizeof(BITMAP), &bmp) == 0)
        ErrorMessage(ERROR_INVALID_WINDOW_HANDLE);

    width = (Area.W == 0) ? bmp.bmWidth : Area.W;
    height = (Area.H == 0) ? bmp.bmHeight : Area.H;

    HDC MemDC = GetDC(0);
    HDC bufferDC = CreateCompatibleDC(MemDC);
    HBITMAP bufferBitmap = CreateCompatibleBitmap(MemDC, width, height);
    DeleteObject(SelectObject(bufferDC, bufferBitmap));

    BitBlt(bufferDC, Area.X1, Area.Y1, width, height, hdc, Area.X1, Area.Y1, SRCCOPY);
    size = ((width * BitsPerPixel + 31) / 32) * 4 * height;

    Info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    Info.bmiHeader.biWidth = width;
    Info.bmiHeader.biHeight = height;
    Info.bmiHeader.biPlanes = 1;
    Info.bmiHeader.biBitCount = BitsPerPixel;
    Info.bmiHeader.biCompression = BI_RGB;
    Info.bmiHeader.biSizeImage = size;
    bFileHeader.bfType = 0x4D42;
    bFileHeader.bfOffBits = …
triumphost 120 Posting Whiz

Hey I have a question. Why is Foo X() wrong? I do that all the time and it uses my classes :S I read that on cplusplus when I started learning classes.

The compiler gives no error even with all options turned on.
Why do I need the equal sign to declare a class like you did?

triumphost 120 Posting Whiz

I've just read a tutorial on Classes Under the hood/behind the scenes.
It says that:

Foo* A = new Foo();

// Is different from:

Foo* B = new Foo;

What in the world? I never put the brackets for my classes like that. Why does the first initialize variables and the second not do the same?

Does this only happen if I use the new operator? Example:

Foo A();

Foo B;

Does it happen for these too? Or is it just the new operator alone?

This tutorial completely threw me off and caught me off guard as now I'm thinking that none of my classes were initialized even though in my constructor I do:

Foo() : VarX(0), VarY(0)
Foo(int X, int Y) : VarX(X), VarY(Y)

Please clear up these details for me.

triumphost 120 Posting Whiz

If it has the dots like that, then it's probably a templated class or a class that takes an int in the constructor..

class xx
{
    public:
        xx();
        ~xx();

        class func// : public xx
        {
            func(int Value){/*do something with value here*/}
            ~func(){}

            operator ()(int Value)
            {
                /*do something with value here*/
            }
        };
};

xx::xx(){}
xx::~xx(){}


int main()
{
    xx meh;
    meh.func(1);
    meh.func(2);
    meh.func(3);
}

I don't know if you can chain them like how you have, but this is a pretty good alternative. Maybe use inheritance and polymorphism if you want that behavior?

EDIT: NVM.. I see it's done already.

triumphost 120 Posting Whiz

Hmm I fixed what you said. The reason I had to cast the std::function was because lpParameter is a void* and I had to turn it into a function inorder to use it. Removing the cast there will not work. Also I have a couple more questions.

  1. What if I want to go from char* to BYTE*? I'd use reinterpret_cast right?

  2. From const char* to BYTE* I'd do: reinterpret_cast<BYTE*>(const_cast<char*>(InitialValue.c_str()))

But I'm skeptical about doing such things because I read that reinterpret casts are very bad. But static_cast doesn't do this sorta thing and neither does dynamic so I'm not sure whether to reinterpret_cast or use c-style casting.

Also some of my functions such as FormatMessage wrapper:

inline void ErrorMessage(DWORD Error, bool ExitProcess = false)
{
    char* lpMsgBuf = nullptr;
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, Error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<char*>(&lpMsgBuf), 0, 0);
    std::cout<<lpMsgBuf;
    if (ExitProcess) exit(Error);
}

//See this cast? reinterpret_cast<char*>(&lpMsgBuf)
//Why do I have to use reinterpret to cast from a pointer?

Are C-Style casts even that bad? I mean they look much neater in code and they are equivalent to whichever of the 4 casts works first. So how can that be a bad thing?

triumphost 120 Posting Whiz

I just learned C++ style casting and the 4 types of casts. I'm not sure if I'm abusing it though.

Examples:

typedef long (*stringFromString)(int, char*) __cdecl;

//TO:

typedef long static_cast<*stringFromString>((int, char*)) __cdecl;



SmartSetup((char*)World.c_str(), (char*)",f5", 765, 503,(char*)"");

//TO:

SmartSetup(static_cast<char*>(World.c_str()), static_cast<char*>(",f5"), 765, 503, static_cast<char*>(""));




memcpy(&INH, (void*)((DWORD)Buffer + IDH.e_lfanew), sizeof(INH));

TO:

memcpy(&INH, static_cast<void*>(static_cast<DWORD>(Buffer) + IDH.e_lfanew), sizeof(INH));



std::function<void()> func = *((std::function<void()>*)lpParameter);

TO:

std::function<void()> func = *(static_cast<std::function<void()>*>(lpParameter));

I'm not sure when I should use re-interpret cast or if I'm abusing this type of cast I'm currently using. Should I leave everything as C-Style cast? How does it affect typedefs when importing from a DLL? How can I cast: (void*) &Meh using C++?? I used a static cast to void*.

triumphost 120 Posting Whiz

I have just came across a class for the first time ever that does not have variables in any of it's declarations but has them in the implementation. Why is this class behaviour allowed? What are the benefits of not putting variable names?

class Testing
{
    public:
        Testing(int, int, int);     //<--- Why is there no variables after int?
};

Testing::Testing(int X, int Y, int Z)   //<--- Variables here.
{
}

Is it the intellisense? I don't use intellisense so I want to know if it affects it and what makes a programmer do this? Benefits? Why does this even compile :S It works but I have no clue why.

triumphost 120 Posting Whiz

People class doesn't have a declaration for the default constructor, String needs to be defined through its namespace.

std::string X. And std::name because you do not have "using namespace std;"

In the people class under the public inheritance, add:

People();

And finally, PrintInfo has no definition.

triumphost 120 Posting Whiz

You haven't provided enough for me to guess what your trying to do..
You also cannot just implicitly convert a HWND to an HDC. It doesn't work like that. Putting the code in order, you can see that you had some HWND's being used as if it was a DC. I tried to fix as much as I can below and GUESS at what you were trying to do. I do not know what "Col" is. It seems to be some sort of 2D array of a struct of integers/unsigned chars but I do not want to guess.

void Meh(HWND hwnd, LPCTSTR szFileName)
{
    Bitmap BM;
    RGBQUAD *pPixels;
    BITMAPINFO bmi = {0};

    HDC hDesktopDC = GetDC(hwnd);
   // HWND hDesktopWnd = GetDesktopWindow();  No need.. Use NULL.
    HDC hCaptureDC = CreateCompatibleDC(NULL);
    int nScreenWidth =  GetSystemMetrics(SM_CXSCREEN);
    int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);

    HBITMAP hCaptureBitmap = (HBITMAP)LoadImage(NULL, szFileName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_DEFAULTSIZE | LR_LOADFROMFILE);
    SelectObject(hCaptureDC, hCaptureBitmap);
    GetObject(hCaptureBitmap, sizeof(BM), &BM);  //I added this.

    BitBlt(hCaptureDC, 0, 0, nScreenWidth, nScreenHeight, hDesktopDC, 0,0, SRCCOPY | CAPTUREBLT);  //Copying the Bitmap File to the DC?

    bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
    bmi.bmiHeader.biWidth = nScreenWidth;
    bmi.bmiHeader.biHeight = nScreenHeight;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;
    bmi.bmiHeader.biCompression = BI_RGB;

    pPixels = new RGBQUAD[nScreenWidth * nScreenHeight];

    GetDIBits(hCaptureDC, hCaptureBitmap, 0, nScreenHeight, pPixels, &bmi, DIB_RGB_COLORS);  //Copy the hBitmap to pPixels?

    //I stopped here because I didn't know what the rest is supposed to be. Are you trying to swap rows and flip the bitmap? Are you trying to edit the file with the pixels from the capture? …
triumphost 120 Posting Whiz

Never tested this but the formula seems correct :S
RGB to CMY: http://www.easyrgb.com/index.php?X=MATH&H=11#text11
CMY to CMYK: http://www.easyrgb.com/index.php?X=MATH&H=13#text13

EDIT: Oh wow.. didn't realize this was a grave dig -_-

void RGBToCMYK(int R, int G, int B, int &C, int &M, int &Y, int &K)
{
    C = 1 - (R / 255);
    M = 1 - (G / 255);
    Y = 1 - (B / 255);

    int TempK = 1;

    if (C < TempK) TempK = C;
    if (M < TempK) TempK = M;
    if (Y < TempK) TempK = Y;
    if (TempK == 1)
    {
        C = M = Y = 0;
    }
    else
    {
        C = (C - TempK) / (1 - TempK);
        M = (M - TempK) / (1 - TempK);
        Y = (Y - TempK) / (1 - TempK);
    }
    K = TempK;
}
triumphost 120 Posting Whiz

I made a temporary variable so my class member variable does not change. For Chars it isn't neccessary but when it comes to 2D arrays of strings, I couldn't think of another way other than to make a temp copy, lowercase it and just match against that.

This was my first time ever encountering a situation where I needed to use explicit. Thank you for the explanation though. I just finished reading up on why it is needed sometimes.

I've never heard of the O(N^ 2) thing before I'll research it before using those functions. Thank you though. Much appreciated and I'll try to keep things to one thread from now on.

triumphost 120 Posting Whiz

This works fine. For any type I create (Example):

BoxArray& operator -= (const Box& B);

BoxArray& operator -= (const BoxArray& BA);

BUT when it comes to my literal types like char's and strings and char*'s, I get Ambiguous overloads:

StringArray& operator -= (const std::string& S);

StringArray& operator -= (const StringArray& SA);

I have no clue why! They are the exact same syntax, it works for all my classes, why does it not work for literal types? I've coded them all the exact same so are Literals special when overloading?

Also for my next question, I'm trying to delete values in a vector and it works but I've been using parallel vectors inorder to do lower-case comparisons such as:

void Delete(char CharToDelete, bool CaseSensitive, bool All)
{
    std::vector<char> Temp = ChrA;  //Copy my original/global vector to a temporary vector.
    if (!CaseSensitive)
    {
        CharToDelete = tolower(CharToDelete);

        for (size_t I = 0; I < Temp.size(); I++)
            Temp[I] = tolower(Temp[I]);
    }

    //Compare the temporary type to the one to delete and remove it from the global vector and temp vector to avoid out of range errors.

    for (size_t I = 0; I < Temp.size(); I++)
    {
        if (Temp[I] == CharToDelete)
        {
            ChrA.erase(ChrA.begin() + I);   //Parallel Deletion..
            Temp.erase(Temp.begin() + I);   //Parallel Deletion..
            if (!All)
                break;
            I = 0;
        }
    }
    return;  //Do not return anything since I already removed it from the global vector too.
}

Is there a better way to do this? The underlying types are just …

triumphost 120 Posting Whiz

You need to link the correct .lib/.dll/.a/.o files to your program.

#pragma comment('lib', "user32.dll"); Would be an example of doing so in Vs2010. I may have made a mistake doing the code above since I don't have access to a compiler to test atm, but it's something like that.

That will dynamically link user32.dll to your exe file. You can do winsock32.a or ws_s32.lib, etc.. Just make sure you link the correct files and your program will compile.

triumphost 120 Posting Whiz

Ahh I fixed the run-time error but the compile time still happens. If I remove the declaration, instead it will say:

error: template-id 'Contains<>' for 'bool CustomType<char*>::Contains(const char*, bool)' does not match any template declaration

note: saw 1 'template<>', need 2 for specializing a member function template

And thank you for taking the time to look through it =] Much Appreciated.

EDIT:

I changed the template to (And remove the declarations for both):

template<>
bool CustomType<std::string>::Contains(std::string LiteralType, bool CaseSensitive)
{
    //.........
}

template<>
bool CustomType<const char*>::Contains(const char* LiteralType, bool CaseSensitive)
{
    //........
}


//Had to make one for char* without the const so that it works for that too.
template<>
bool CustomType<char*>::Contains(char* LiteralType, bool CaseSensitive)
{
    //.......
}

Thank you! =]

triumphost 120 Posting Whiz

You did not escape the back-slash character. All strings/literals will have this behaviour as the first back-slash will escape the following character so inorder to have a back-slash, you must escape it with another. You either need to do:

C:\\Directory1\\Directory2\\Music.mp3

OR:
C:/Directory1/Directory2/Music.mp3

Command prompt will complain about the same thing to you. char's will behave the same and so will char*'s that's what I mean by literals. This is why \0 is the same as 0 which is known as the NULL character; usually appended to the literals to terminate them.

triumphost 120 Posting Whiz

Hmm without the <T> it's the same thing no? It still gave the same error.
It's quite long which is why I didn't post the whole thing. I ended up fixing the error late last night. I had to change CustomType& to T& for my overload of the operator []. My only problem now is the Contains function which I tried to specialize but when I do:

#include <windows.h>
#include <iostream>
#include "Templates.hpp"

using namespace std;

int main(int argc, char* argv[])
{
    //StreamFlags(cout);

    const char Meh[] = "MM";
    CustomType<const char*> SA("MM");

    cout<<SA.Contains(Meh, true);

    cin.get();
    return 0;
}

It will give me an error saying I cannot overload Contains with Contains for char*'s. The entire compilable header (Only compiles with Mingw 4.7+ or Codeblocks using Mingw4.7+ due to the variadic template constructors) Lines 51, 53, and 55 which is defined at lines 208, is my problem now:

#ifndef TEMPLATES_HPP_INCLUDED
#define TEMPLATES_HPP_INCLUDED

#include <vector>
#include <assert.h>
#include <sstream>

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

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

        size_t size() const;

        T& operator [](int I);

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

        operator const std::vector<T>& () const;

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

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

        CustomType& operator = (const CustomType &CT);

        CustomType& operator += (const T& t);

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

        CustomType operator + (const T& t);

        CustomType …
triumphost 120 Posting Whiz

How can I do the following but easier? I'm templating a class but I want it so that if typename T is of a literal type such as a string or char, then it can use the following member-function. If not then it cannot use it. I've been using typeid to tell whether one is a char or a string or a non-literal type. But it does not work since I cannot do it for both at the same time unless I overload the function. Is there any other way? I do not want to have to make a whole new templated class specialized for chars and strings, This is currently what I have:

template<typename T>
bool CustomType<T>::Contains(T LiteralType, bool CaseSensitive)
{
    if ((typeid(T).name() == typeid(std::string).name()) || (typeid(T).name() == typeid(char).name()))
    {
        std::vector<T> Temp = TypeData;         //Create  temporary type so the original doesn't change.
        if (!CaseSensitive)
        {
            if (typeid(T).name() == typeid(char).name())  //If it is a char..
                LiteralType = tolower(LiteralType);
            else
                for (size_t I = 0; I < LiteralType.length(); I++)
                    LiteralType[I] = tolower(LiteralType[I]);

            if (typeid(T).name() == typeid(char).name())  //If it is a char..
                for (size_t I = 0; I < Temp.size(); I++)
                    Temp[I] = tolower(Temp[I]);
            else
                for (size_t I = 0; I < Temp.size(); I++)
                    for (size_t J = 0; J < Temp[I].size(); J++)
                        Temp[I][J] = tolower(Temp[I][J]);
        }
        for (size_t I = 0; I < Temp.size(); I++)  //For both of them.
        {
            if (Temp[I] == LiteralType)
                return true;
        }
    }
    return false;
}
triumphost 120 Posting Whiz

Hey when I don't template my classes, I can pass member functions to eachother normally. But when I template it, I get errors. The two functions are defined as so:

CustomType& Delete(int Position);

CustomType& Delete(T ValueToDelete, bool All = false);

CustomType& Delete(CustomType ValuesToDelete);

And Implemented like this:

template<typename T>
CustomType<T>& CustomType<T>::Delete(T ValueToDelete, bool All)
{
    for (size_t I = 0; I < TypeData.size(); I++)
        if (TypeData[I] == ValueToDelete)
        {
            TypeData.erase(TypeData.begin() + I);
            if (!All)
                break;
            I = 0;
        }
    return *this;
}

template<typename T>
CustomType<T>& CustomType<T>::Delete(CustomType ValuesToDelete)
{
    for (size_t I = 0; I < ValuesToDelete.size(); I++)
    {
        this->Delete(ValuesToDelete[I], true);  //The error below points to this line.
    }
    return *this;
}

Used like:

int main()
{
    CustomType<int> CT(1, 5, 4, 7, 9, 14, 23, 89);
    CT.Delete(CT);  //FAILS!
}

//error: no matching function for call to 'CustomType<int>::Delete(CustomType<int>&, bool)'

When my classes aren't templated, these functions work perfectly fine. I do not understand why it doesn't work now :S Any help is appreciated.

triumphost 120 Posting Whiz
  1. You cannot do:cout<<CharIdentifier[250]... You have to do cout<<CharIdentifier.

  2. Not sure if you understood me :S but my laptop is about to die so I'll post what I wrote:

    #include <windows.h>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    
    vector<string> IterateDirectory(const char* DirectoryLocation)
    {
        WIN32_FIND_DATA WFD;
        HANDLE hFind = INVALID_HANDLE_VALUE;
        vector<string> Result;
        char Directory[1024];
        Directory[0] = '\0';
    
        strcat(Directory, DirectoryLocation);  //Append our directory location to a blank char* buffer.
        strcat(Directory, "\\*"); //To find any file, we append \* to the end of the directory location.
    
        hFind = FindFirstFile(Directory, &WFD);  //Try to find the first file in our directory.
        if (hFind == INVALID_HANDLE_VALUE)
        {
            return Result;  //Return an empty vector since we failed to find any files.
        }
    
        do
        {
            Result.push_back(WFD.cFileName);  //Add each file found to the vector.
        }while(FindNextFile(hFind, &WFD) != 0);  //While there are more files, keep going.
    
        FindClose(hFind);  //Clean up our handles.
        return Result;     //Return a copy of our vector of files. You can probably change this to return a bool and pass-by-reference vector.
    }
    
    int main()
    {
        char* Location = "C:\\Users\\Brandon\\Desktop"; //Directory containing Files.
        vector<string> ListOfFiles = IterateDirectory(Location);  //Returned a copy of our internal vector which holds our list of files.
    
        for (vector<string>::iterator I = ListOfFiles.begin(); I != ListOfFiles.end(); I++) //Loop through our vector and print all file names.
            cout<<*I<<endl;  //Prints every file name.
        return 0;
    }
    

That's as far as I got. It should work. I used Iterators, you can use vector Indicies instead if you're unconfortable with iterators:

for (int I = 0; I < …
triumphost 120 Posting Whiz

Ahh well in that case that's a bit different. Do you know the location of the file? If so then you can just search the directory for the files:

From MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365200%28v=vs.85%29.aspx

That's a very good example. Of course you can simplify it and put the found names into a char* buffer if you wish.

triumphost 120 Posting Whiz

I don't know if you mean reading the file's name? OR whether you mean reading data from the file and outputting a list of names from the data.

//Read a file's contents and output it to a string. For your purpose, you can even use GetLine which I have not demonstrated.

    #include <iostream>
    #include <fstream>

    using namespace std;

    int main ()
    {
      int length;
      char * buffer;

      ifstream is;
      is.open ("dudaroo.dat", ios::binary );

      // get length of file:
      is.seekg (0, ios::end);
      length = is.tellg();
      is.seekg (0, ios::beg);

      // allocate memory:
      buffer = new char [length]; //can use std::vector<char> instead if you don't want to allocate and delete buffers.

      // read data as a block:
      is.read (buffer,length);
      is.close();

      std::string Data;
      Data.append(buffer, length);
      delete[] buffer;


      //Data now contains all the data from the file.

      //Use String.Find to find names within the file.
      //OR use Boost::Regex to find names with a specified pattern.

      return 0;
    }

As stated before, you can use getline with a while loop so that you can get each line in the file and search it for the playernames.

triumphost 120 Posting Whiz

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

That's what I read to learn template compilation. It says that putting everything in the header can bloat your executable though.

triumphost 120 Posting Whiz

Ahh well i was thinking that if I pass the struct to something like CreateDIBitmaps or if I pass it as a pointer, it won't fill in the Inner struct with values. Correct?

My XYZ and RGB structs are the same so I'll use RGB as an example:

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

Now if the struct is un-named, it will fill in all the values right?
I can do RGB P = {16777215}; and R, G, B gets filled with 255, 255, 255, 0.

When I name my struct "Inner" it does not happen unless I access those values specifically through the name or an object of that struct.

I asked about the #Pragma pack because I learned from researching online that it will keep the alignment the same and that I can change the alignment. So I thought that by putting it, I can change an anonymous union to the same as a struct without a name? That way both will have the same alignment no?

My Idea:

typedef struct XYZ //Somehow turn this into a union with pragma pack?
{
    uint32_t Color;
    union          //Somehow turn this into a struct
    {
        uchar X, Y, Z;
    };
} *pXYZ;

I was trying to think of a way to make it legal all day but I can't come up with anything. And if I switch union with struct and vice-versa, …

triumphost 120 Posting Whiz

I've read that anonymous structs are a compiler extension and codeblocks allows them as long as -pedantic-errors are not enabled.

My question is, since it is not legal in C++, what would be the legal equivalent of:

typedef union XYZ
{
    int Color;
    struct
    {
        BYTE X, Y, Z;
    };
} *XYZ;

See if I name the struct i'd have to access it using it's name/object. If I switch the struct and the union, then the layout is completely different and as such changing one affects the other.

Also would #Pragma pack affect it?

triumphost 120 Posting Whiz

How can I cast a class to another type? Example:

class Point
{
    Point(int X, int Y);
};

Point A(10, 10);
POINT P = (POINT)A;
A = (Point)P;


//I've tried:

Point::Point(POINT P) : X(P.x), Y(P.y), Color(0) {} //Constructor.

Point& Point::operator ()(POINT P)
{
    if (X != P.x && Y != P.y)
    {
        X = P.x;
        Y = P.y;
        Color = 0;
    }
    return *this;
}

How do I go the other way around? I've tried doing the reverse the exact same way but it doesn't work. Did I do the above correctly?

triumphost 120 Posting Whiz

Anyone? This is my new copy constructor and move constructor as well as my non-throwing swap function. I'm skeptical on if I did it all correctly. I'm also not sure how to initalize BitmapInfo and bFileheader in the members initialization list :S Any help is appreciated.

//Copy Con:

Bitmaps::Bitmaps(const Bitmaps& Bmp) : Pixels(((Bmp.width * Bmp.height) != 0) ? new RGB[Bmp.width * Bmp.height] : nullptr), width(Bmp.width), height(Bmp.height), size(Bmp.size), DC(0), Image(0)
{
    std::copy(Bmp.Pixels, Bmp.Pixels + (width * height), Pixels);
    Info = Bmp.Info;
    bFileHeader = Bmp.bFileHeader;
}

//Move Con:

Bitmaps::Bitmaps(Bitmaps&& Bmp) : Pixels(nullptr), width(Bmp.width), height(Bmp.height), size(Bmp.size), DC(0), Image(0)
{
    this->Swap(Bmp);
    Bmp.Pixels = nullptr;
}

//Copy Assignment Operator:

Bitmaps& Bitmaps::operator = (Bitmaps Bmp)
{
    this->Swap(Bmp);
    return *this;
}

//Move Assignment Operator:

Bitmaps& Bitmaps::operator = (Bitmaps&& Bmp)
{
    this->Swap(Bmp);
    return *this;
}

//My swap function:

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);
}