顯示具有 CPP 標籤的文章。 顯示所有文章
顯示具有 CPP 標籤的文章。 顯示所有文章

2015年2月5日 星期四

Different between const int * , int const * and int * const

* Question: 
What different between const int * , int const * , int * const ?

* Answer: 
  • int*                                                           - pointer to int
  • const int * == int const *                     - pointer to const int
  • int * const - const pointer to int
  • const int * const == int const * const - const pointer to const int

  • int **                       - pointer to pointer to int
  • int ** const             - a const pointer to a pointer to an int
  • int * const *           - a pointer to a const pointer to an int
  • int const **            - a pointer to a pointer to a const int
  • int * const * const - a const pointer to a const pointer to an int


* Reference: 

http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-int-const

2015年2月4日 星期三

Difference between std::thread and pthread

* Question: 

What are the differences between std::thread and pthread


* Answer: 
The std::thread library is implemented on top of pthreads in an environment supporting pthreads 
std::thread provides portability across different platforms like Windows, MacOS, and Linux, but may not be complete on all platforms yet.
The C++11 std::thread class unfortunately doesn't work reliably (yet) on every platform, even if C++11 seems available.

* Reference: 
http://stackoverflow.com/questions/13134186/c11-stdthreads-vs-posix-threads

2015年2月3日 星期二

Difference between size_t and std::size_t


* Question: 

What are the differences between size_t and std::size_t



* Answer: 
C's size_t and C++'s std::size_t are both same.
In C, it's defined in <stddef.h> and in C++, its defined in <cstddef> whose contents are the same 
as C header (see the quotation below). Its defined as unsigned integer type of the result of the 
sizeof operator.

* Reference: 
http://stackoverflow.com/questions/5813700/difference-between-size-t-and-stdsize-t


2014年7月31日 星期四

[GCC] error : Sleep was not declared in this scope

Situation:
I got error message when I compiling my c++ code with sleep(1); inline.
"error : Sleep was not declared in this scope"


Solution:
The solution is add folling including message in the head of your code.
#include <unistd.h>


Reference:
http://stackoverflow.com/questions/10976176/c-error-sleep-was-not-declared-in-this-scope

2013年11月26日 星期二

Step by step to compile a C++ program on Ubuntu.

Reference:
http://www.wikihow.com/Compile-a-C/C%2B%2B-Program-on-Ubuntu-Linux

1. Install compiling tool
sudo apt-get install build-essential

2.Create a directory to hold your programs
mkdir -p CCPP/HelloWorld

3. Go into the directory you created.
cd CCPP/HelloWorld

4. Create CPP file
gedit main.cpp

5. Fill code in main.cpp and save it.
#include<iostream>
using namespace std;
int main()
{
    cout << "\nHello World !\n" << endl;
    return(0);
}

6. Compile it.
g++ -Wall -W -Werror main.cpp -o HelloWorldCPP
7. Execute it.
./HelloWorldCPP



2013年6月28日 星期五

Convert from char* to wchar_t*

To Convert char* to wchar_t*

Assume we have a char* string named c

    const size_t cSize = strlen(c)+1;
    wchar_t* wc = new wchar_t[cSize];
    mbstowcs (wc, c, cSize);


Now you have wchar_t* string wc.

You can also refer to http://twnin.blogspot.tw/2012/03/convert-between-char.html for more type to convert.

2013年3月10日 星期日

internal and external iterator

What different between internal and external iterator?


external iterator:
It is a separate class that can step through its container/collection.
So you can control the logic to get the item what you want.


ex.
std::vector<int> v;
for(vint::iterator it=v.begin(), it!=v.end(); ++i)
    std::cout << *it << "\n";




internal iterator:
It is implemented with member functions to step through.
You only can get the items in turn, but it is more easy to use than external iterator.


ex.
MACRO_FOREACH(v)
{
    std::cout << v << "\n";
}


2012年12月7日 星期五

error LNK2005: * already defined in *.lib(*.obj)

Problem:
When I build Seahorse in branch bsquare, sometimes I got lots of linking error like this
error LNK2005: * already defined in *.obj
I’m sure it had been successful built before, but it doesn’t work now.


Solution:
I found it can be avoid if putting /FORCE:MULTIPLE into build options.
Right click on project -> Properties -> Linker -> Command Line -> Additional Options -> add /FORCE:MULTIPLE

(It just a first-add, please see the first reference for root cause.)


Reference:
http://stackoverflow.com/questions/10046485/error-lnk2005-already-defined
http://bbs.csdn.net/topics/260087335

2012年11月7日 星期三

error C2731: 'WinMain' : function cannot be overloaded

Error message as title.

My code as below.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)

{
    bala...bala...
}

To fix the issue, change code to
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
    bala...bala...
}

2012年11月3日 星期六

fatal error LNK1181: cannot open input file 'mmtimer.lib'

Error:
fatal error LNK1181: cannot open input file 'mmtimer.lib

Solution:
mmtimer.lib is for OS WinCE
For Windows, It should be winmm.lib

1. go to Project properties->Linker->input
2. remove mmtimer.lib and put winmm.lib instead.

Reference:
http://www.programmer-club.com/showSameTitleN/directx/5570.html

error C3861: '_ASSERTE': identifier not found


Error:
error C3861: '_ASSERTE': identifier not found

Solution:
The reason for this is, there is a crtdbg.h in project. so #include crtdbg.h goes to own crtdbg.h

1. In my case, tt is caused _ASSERTE doesn't defined in wceshunt.
    Please remove path wceshunt\include from include directories.

2. If the path already be removed, such as project icu.
    Please add C:\Program Files\Microsoft Visual Studio 9.0\VC\include to include directories. It should be added ahead wceshunt\include if you don't remove wceshunt from include directories.



2012年9月21日 星期五

[C++] Execute system call in command line.

Example for execute system call for Win32

#include "stdafx.h"
#include "stdlib.h"

int _tmain(int argc, _TCHAR* argv[])
{
    system( "cd c:\\windows\\system32");
    system( "notepad.exe C:\\1.txt");
    return 0;
}

Example for execute system call for WinCE

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    SHELLEXECUTEINFO ExecuteInfo;
    memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
 
    ExecuteInfo.cbSize       = sizeof(ExecuteInfo);
    ExecuteInfo.fMask        = 0;              
    ExecuteInfo.hwnd         = 0;              
    ExecuteInfo.lpVerb       = _T("open"); // Operation to perform
    ExecuteInfo.lpFile         = _T("\\storage card\\myBrowser.exe"); // Application name
    ExecuteInfo.lpParameters = _T("--shell"); // Additional parameters
    ExecuteInfo.lpDirectory  = 0; // Default directory
    ExecuteInfo.nShow        = SW_SHOW;
    ExecuteInfo.hInstApp     = 0;
 
    ShellExecuteEx(&ExecuteInfo);

    return 0;
}

2012年8月25日 星期六

[C++] Sample for Using stdlib to implement Extend Quick Sort function

As last example, I use standard library to implement quick sort again.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>

void quickSortEx(int[], int, bool, int, int);
int cmp(const void* a, const void* b);

int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
    const int count = 10;
    int number[count] = {0};

    printf("Before: ");
    int i;
    for(i = 0; i < count; i++) {
        number[i] = rand() % 100;
        printf("%d ", number[i]);
    }
    printf("\n");

    quickSortEx(number, count, true, 0, count-1);

    printf("Afer: ");
    for(i = 0; i < count; i++)
        printf("%d ", number[i]);

    printf("\n");
    return 0;
}

void quickSortEx(int number[], int count, bool desc, int left, int right)
{
    qsort(number, count, sizeof(number[0]), cmp);

    if (desc)
        std::reverse(number, number+count);
}

int cmp(const void* a, const void* b)
{
    const int x = *static_cast<const int*>(a);
    const int y = *static_cast<const int*>(b);

    if (x == y)
        return 0;

    return x > y ? 1 : -1;
}


Reference:
http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
http://www.cplusplus.com/reference/algorithm/reverse/

2012年8月24日 星期五

[C++] A sample for Extended Quick Sort

I need to implement a function to sort items with specified ascending order.
I modify other's sample as below.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void quickSortEx(int[], int, bool, int, int);
void swap(int &x, int &y);

int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
    const int count = 10;
    int number[count] = {0};
 
    printf("Before: ");
    int i;
    for(i = 0; i < count; i++) {
        number[i] = rand() % 100;
        printf("%d ", number[i]);
    }
    printf("\n");

    quickSortEx(number, count, false, 0, count-1);

    printf("Afer: ");
    for(i = 0; i < count; i++)
        printf("%d ", number[i]);
 
    printf("\n");
    return 0;
}

void quickSortEx(int number[], int count, bool desc, int left, int right) {
    if(left < right) {
        int i = left;
        int j = right + 1;

        while(1) {
            // To find the item should sort after 'left'
            while(i + 1 < count && (desc ? number[left] < number[++i] : number[++i] < number[left]));
            // To find the item should sort before 'left'
            while(j -1 > -1 && (desc ? number[left] > number[--j] : number[--j] > number[left])) ;
            if(i >= j)
                break;
            swap(number[i], number[j]);
        }

        swap(number[left], number[j]);

        quickSortEx(number, count, desc, left, j-1);
        quickSortEx(number, count, desc, j+1, right);
    }
}

void swap(int &x, int &y)
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}

Reference:
http://caterpillar.onlyfun.net/Gossip/AlgorithmGossip/QuickSort1.htm
http://emn178.pixnet.net/blog/post/88613503-%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%E6%B3%95(quick-sort)

2012年8月23日 星期四

[C++] Sample for String Compare

It is a simple sample for understanding how to implement a function to compare two string.

#include "stdafx.h"
#include <string.h>
#include <iostream>

using namespace std;

int codePointCompare(const char* c1, const char* c2)
{
 int l1 = strlen(c1);
 int l2 = strlen(c2);
        const unsigned lmin = l1 < l2 ? l1 : l2;
        unsigned pos = 0;
        while (pos < lmin && *c1 == *c2)
 {
             c1++;
             c2++;
             pos++;
        }

        if (pos < lmin)
             return (c1[0] > c2[0]) ? 1 : -1;

        if (l1 == l2)
             return 0;

 return (l1 > l2) ? 1 : -1;
}

int _tmain(int argc, _TCHAR* argv[])
{
 char* c1 = new char[1024];
 char* c2 = new char[1024];
 cout << "please input first string:";
 cin >> c1;
 cout << "please input second string:";
 cin >> c2;

 cout << codePointCompare(c1, c2);
 return 0;
}


Reference:
http://trac.webkit.org/changeset/110822/trunk/Source/JavaScriptCore/wtf/text/StringImpl.cpp

2012年8月20日 星期一

[C++] Threading Sample

This is a simple sample for understanding of thread create in C++.

#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <stdio.h>

void myfunc(int n);

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE thd[2];
    DWORD tid;

    printf("Thead Start.\n");

    for (int i=0; i<2; i++)
    {
        thd[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)myfunc, (void*)i, 0, &tid);
        printf("Thread %d is start \n",tid);
    }


    Sleep(1000);

    printf("main is end \n");

    system("pause");
}

void myfunc(int n)
{
    int i;
    for(int i=0;i<5;i++){
        printf("Thread %d, index=%d\n", n, i);
        Sleep(1000);
    }
    printf("Thread %d is over \n", getpid());
}

Reference:
http://wuminfajoy.blogspot.tw/2010/10/c.html

2012年8月16日 星期四

[C++] Create GUID

You can create GUID by using CoCreateGuid API.
I copy example source code from my reference article for memo as below.


#include "stdafx.h"
#include <objbase.h>
#include <string>

using namespace std;

wstring GetGUID()
{
    _TUCHAR *guidStr = NULL;

    GUID *pguid = new GUID;

    CoCreateGuid(pguid);

    // Convert the GUID to a string
    UuidToString(pguid, (RPC_WSTR*)&guidStr);
    delete pguid;
    return wstring(guidStr);
}

int _tmain(int argc, _TCHAR* argv[])
{
wstring guid = GetGUID();
    wprintf(guid.c_str());
    return 0;
}



Reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms688568(v=vs.85).aspx
http://www.dotblogs.com.tw/alonstar/archive/2011/09/05/mfc_32bit_64bit.aspx

2012年7月19日 星期四

Certificate Store Operations

Example to get certificate from system.


#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void MyHandleError(char *s);

int _tmain(int argc, _TCHAR* argv[])
{
    //--------------------------------------------------------------------
    // Copyright (C) Microsoft.  All rights reserved.
    // Declare and initialize variables.

    HCERTSTORE  hSystemStore;              // System store handle
    PCCERT_CONTEXT  pDesiredCert = NULL;   // Set to NULL for the first call to CertFindCertificateInStore
    PCCERT_CONTEXT  pCertContext;


    //-------------------------------------------------------------------
    // Open the My system store using CertOpenStore.

    if(hSystemStore = CertOpenStore(
         CERT_STORE_PROV_SYSTEM,            // System store will be a virtual store
         0,                                 // Encoding type not needed with this PROV
         NULL,                              // Accept the default HCRYPTPROV
         CERT_SYSTEM_STORE_CURRENT_USER,    // Set the system store location in the registry
         L"MY"))                            // Could have used other predefined  system stores including Trust, CA, or Root
    {
       printf("Opened the MY system store. \n");
    }
    else
    {
       MyHandleError( "Could not open the MY system store.");
    }



    //-------------------------------------------------------------------
    // Find the certificates in the system store. 
    while(pCertContextEnum=CertEnumCertificatesInStore(
          hSystemStore,
          pCertContextEnum)) // on the first call to the function, this parameter is NULL  on all subsequent                calls,  this parameter is the last pointer returned by the function
    {
        if(CertGetNameString(
           pCertContextEnum,
           CERT_NAME_SIMPLE_DISPLAY_TYPE,
           0,
           NULL,
           pszNameString,
           128))
        {
            printf("\nCertificate for %s \n",pszNameString);
        }
        else
           fprintf(stderr,"CertGetName failed. \n");
    } // End of while.



    //-------------------------------------------------------------------
    // Get a certificate that has the string "ninna.tw@gmail.com" in its subject. 

    if(pDesiredCert=CertFindCertificateInStore(
          hSystemStore,
          MY_ENCODING_TYPE,             // Use X509_ASN_ENCODING
          0,                            // No dwFlags needed 
          CERT_FIND_SUBJECT_STR,        // Find a certificate with a subject that matches the string in the next parameter
          L"ninna.tw@gmail.com",     // The Unicode string to be found in a certificate's subject
          NULL))                        // NULL for the first call to the function In all subsequent calls, it is the last pointer returned by the function
    {
      printf("The desired certificate was found. \n");
    }
    else
    {
       MyHandleError("Could not find the desired certificate.");
    }
    //-------------------------------------------------------------------
    // pDesiredCert is a pointer to a certificate with a subject that 
    // includes the string "ninna.tw@ gmail.com ", the string is 
    // passed as parameter #5 to the function.


    //-------------------------------------------------------------------
    // Close the stores.

    if(hSystemStore)
        CertCloseStore(
            hSystemStore,
            CERT_CLOSE_STORE_CHECK_FLAG);

    printf("All of the stores are closed. \n");

return 0;
}

//-------------------------------------------------------------------
// This example uses the function MyHandleError, a simple error
// handling function, to print an error message and exit 
// the program. 
// For most applications, replace this function with one 
// that does more extensive error reporting.

void MyHandleError(char *s)
{
    fprintf(stderr,"An error occurred in running the program. \n");
    fprintf(stderr,"%s\n",s);
    fprintf(stderr, "Error number %x.\n", GetLastError());
    fprintf(stderr, "Program terminating. \n");
    exit(1);
} // end MyHandleError




You should add dependency for using static functions.
Right click on project -> Property -> Linker -> Input ->Additional Dependencies -> add crypt32.lib



Reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa382037(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa382363(v=vs.85).aspx

2012年5月17日 星期四

[C++] error C2662 cannot convert 'this' pointer from 'const class' to 'class &


Look at following sample
class myClass
{
public:
    int get();
private:
    int m_member;
};

int myClass::get()
{
    return m_member;
}

int main()
{
    const myClass own;
    own.get();  // compiling error
    return 0;
}

A const object try to call non-const function, it is risk to change value of const object.
For the reason, we have to define myClass::get() to be a const function so that we could call the function by a const object.
int myClass::get() const

Or we also can define own to be a non-const object.
myClass own;


Reference: 
http://hi.baidu.com/idealsoft/blog/item/629ae129a7f14afb99250af4.html http://forums.codeguru.com/archive/index.php/t-416873.html

2012年4月16日 星期一

Error C2724 : 'static' should not be used on member functions defined at file scope

I do a stupid thing like below, so got message Error C2724 : 'static' should not be used on member functions defined at file scope

XXX.h
static void functionA();

XXX.cpp
static void functionA()
{
    // do something  
}

We have to remove the key word static from XXX.cpp, or the compiler will regard they are two different functions.
Further more, if you call the functionA(), you may also got the message, error LNK2019: unresolved external symbol