레이블이 Programming인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Programming인 게시물을 표시합니다. 모든 게시물 표시

2010년 3월 18일 목요일

[STL::Map] Error occured

#include <iostream>
#include <map>

int main()
{
 std::map<int, int> mapTest ;
 
 for (int i = 0 ; i <10 ; i++)
 {
  mapTest[i] = 10*i ;
 }
 std::map<int, int>::iterator mapIt ;

 mapIt = mapTest.find(10) ;


 /*
 if (mapIt != NULL)
  std::cout << "mapIt = " << mapIt->second << std::endl ;
 */ // Error occur: the iterator might not find out its error.


if (mapIt != mapTest.end())
  std::cout << "mapIt = " << mapIt->second << std::endl ;

 int i ;
 std::cin >> i ;

 return 0 ;
}




My friend saw my source code, and adviced to me that the code will be broken from map's iterator.

So, I simply tested this source. I could find out where the problem occured.

However, I can't explain why the error occurs. I need to study about STL, especially map.




- ps.
This blog is for my English abilities, and I'm not good at communicating in English. If you see grammatic, syntax or logical errors, or if you can't understand clearly, PLEASE COMMENT ON IT. Your comments definitely help me, and I will really appreciate this. :)



2010년 1월 4일 월요일

[Scrap] Struct SYSTEM_INFO (System Programming)


It's from MSDN, and here is the link:
http://msdn.microsoft.com/en-us/library/ms724958(VS.85).aspx



SYSTEM_INFO Structure

Contains information about the current computer system. This includes the architecture and type of the processor, the number of processors in the system, the page size, and other such information.

Syntax

C++
typedef struct _SYSTEM_INFO {
  union {
    DWORD dwOemId;
    struct {
      WORD wProcessorArchitecture;
      WORD wReserved;
    } ;
  } ;
  DWORD     dwPageSize;
  LPVOID    lpMinimumApplicationAddress;
  LPVOID    lpMaximumApplicationAddress;
  DWORD_PTR dwActiveProcessorMask;
  DWORD     dwNumberOfProcessors;
  DWORD     dwProcessorType;
  DWORD     dwAllocationGranularity;
  WORD      wProcessorLevel;
  WORD      wProcessorRevision;
}SYSTEM_INFO;

Members

dwOemId

An obsolete member that is retained for compatibility. Applications should use the wProcessorArchitecture branch of the union.

wProcessorArchitecture

The processor architecture of the installed operating system. This member can be one of the following values.

Value Meaning
PROCESSOR_ARCHITECTURE_AMD64
9

x64 (AMD or Intel)

PROCESSOR_ARCHITECTURE_IA64
6

Intel Itanium Processor Family (IPF)

PROCESSOR_ARCHITECTURE_INTEL
0

x86

PROCESSOR_ARCHITECTURE_UNKNOWN
0xffff

Unknown architecture.

 

wReserved

This member is reserved for future use.

dwPageSize

The page size and the granularity of page protection and commitment. This is the page size used by the VirtualAlloc function.

lpMinimumApplicationAddress

A pointer to the lowest memory address accessible to applications and dynamic-link libraries (DLLs).

lpMaximumApplicationAddress

A pointer to the highest memory address accessible to applications and DLLs.

dwActiveProcessorMask

A mask representing the set of processors configured into the system. Bit 0 is processor 0; bit 31 is processor 31.

dwNumberOfProcessors

The number of physical processors in the system. To retrieve the number of logical processors, use the GetLogicalProcessorInformation function.

dwProcessorType

An obsolete member that is retained for compatibility. Use the wProcessorArchitecture, wProcessorLevel, and wProcessorRevision members to determine the type of processor.

Name Value

PROCESSOR_INTEL_386

386

PROCESSOR_INTEL_486

486

PROCESSOR_INTEL_PENTIUM

586

PROCESSOR_INTEL_IA64

2200

PROCESSOR_AMD_X8664

8664

 

dwAllocationGranularity

The granularity for the starting address at which virtual memory can be allocated. For more information, see VirtualAlloc.

wProcessorLevel

The architecture-dependent processor level. It should be used only for display purposes. To determine the feature set of a processor, use the IsProcessorFeaturePresent function.

If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_INTEL, wProcessorLevel is defined by the CPU vendor.

If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_IA64, wProcessorLevel is set to 1.

wProcessorRevision

The architecture-dependent processor revision. The following table shows how the revision value is assembled for each type of processor architecture.

Processor Value
Intel Pentium, Cyrix, or NextGen 586 The high byte is the model and the low byte is the stepping. For example, if the value is xxyy, the model number and stepping can be displayed as follows:

Model xx, Stepping yy

Intel 80386 or 80486 A value of the form xxyz.

If xx is equal to 0xFF, y - 0xA is the model number, and z is the stepping identifier.

If xx is not equal to 0xFF, xx + 'A' is the stepping letter and yz is the minor stepping.

 

Examples

For an example, see Getting Hardware Information.

Requirements

Minimum supported client Windows 2000 Professional
Minimum supported server Windows 2000 Server
Header Winbase.h (include Windows.h)

2009년 12월 27일 일요일

[C++] Function Pointer(3) (Solution)



It's my solution file compressed by zip.




* With finishing *

Maybe, it would be last about the test code of the function pointer. Later, I'm not sure whether I'm going to write about the function pointer in my server model (because there are so many extra-informations to explain).




- ps.
This blog is for my English abilities, and I'm not good at communicating in English. If you see grammatic, syntax or logical errors, or if you can't understand clearly, PLEASE COMMENT ON IT. Your comments definitely help me, and I really appreciate this. :)

- Written by Gordon


[C++] Function Pointer(2) (in class & with STL)



* Introduction *
Here is my second experience. I've often used class in C++, and I finally made it.


* Function Pointer in class (code & result)*
#include <iostream>
class cTemp1
{
private :
    int m_X ;
    int m_Y ;
    void (cTemp1::*m_PtrF1)(void) ;    
    int  (cTemp1::*m_PtrF2)(int _x, int _y ) ;
public:
    cTemp1(void);
    ~cTemp1(void);
    void Func1(void) ;
    int     Func2(int _x, int _y) ;
    void Run() ;
};
cTemp1::cTemp1(void) : m_X (5), m_Y(3)
{
    m_PtrF1 = &cTemp1::Func1 ;
    m_PtrF2 = &cTemp1::Func2 ;
}
cTemp1::~cTemp1(void)
{
}
void cTemp1::Func1(void)
{
    std::cout << "cTemp1::Func1" << std::endl ;
}
int     cTemp1::Func2(int _x, int _y)
{
    std::cout << "cTemp1::Func2" << "  X = " << _x+m_X << "  Y = " << _y+m_Y << std::endl ;
    return (_x + m_X + _y + m_Y) ;
}
void cTemp1::Run()
{
    (this->*m_PtrF1)() ;
    int Result = (this->*m_PtrF2)(20, 10) ;
    std::cout << "Result = " << Result << std::endl ;
}
int main()
{
    cTemp1 Instance ;
    Instance.Run() ;
    return 0 ;
}






* Function Pointer in class with STL::map (code & result) *
#include <iostream>

class cTemp2
{
private :
    typedef void(cTemp2::*fPtr)(int _x) ;
    std::map <int, fPtr>        m_Map ;
public :
    cTemp2(void) ;
    ~cTemp2(void) ;
    void Func1(int _x) ;
    void Func2(int _x) ;
    void Func3(int _x) ;
    void Func4(int _x) ;
    void Func5(int _x) ;
    void Func6(int _x) ;
    void Func7(int _x) ;
    void Func8(int _x) ;
    void Func9(int _x) ;
    void Func10(int _x) ;
    void Run() ;
};
cTemp2::cTemp2(void)
{
    // Insert to map
    m_Map[1] = &cTemp2::Func1 ;
    m_Map[2] = &cTemp2::Func2 ;
    m_Map[3] = &cTemp2::Func3 ;
    m_Map[4] = &cTemp2::Func4 ;
    m_Map[5] = &cTemp2::Func5 ;
    m_Map[6] = &cTemp2::Func6 ;
    m_Map[7] = &cTemp2::Func7 ;
    m_Map[8] = &cTemp2::Func8 ;
    m_Map[9] = &cTemp2::Func9 ;
    m_Map[10] = &cTemp2::Func10 ;

}
cTemp2::~cTemp2(void)
{
    // destroy map
    m_Map.clear() ;
}

void cTemp2::Func1(int _x) {std::cout << "cTemp2::Func1() is called with " << _x << std::endl ;}
void cTemp2::Func2(int _x) {std::cout << "cTemp2::Func2() is called with " << _x << std::endl ;}
void cTemp2::Func3(int _x) {std::cout << "cTemp2::Func3() is called with " << _x << std::endl ;}
void cTemp2::Func4(int _x) {std::cout << "cTemp2::Func4() is called with " << _x << std::endl ;}
void cTemp2::Func5(int _x) {std::cout << "cTemp2::Func5() is called with " << _x << std::endl ;}
void cTemp2::Func6(int _x) {std::cout << "cTemp2::Func6() is called with " << _x << std::endl ;}
void cTemp2::Func7(int _x) {std::cout << "cTemp2::Func7() is called with " << _x << std::endl ;}
void cTemp2::Func8(int _x) {std::cout << "cTemp2::Func8() is called with " << _x << std::endl ;}
void cTemp2::Func9(int _x) {std::cout << "cTemp2::Func9() is called with " << _x << std::endl ;}
void cTemp2::Func10(int _x) {std::cout << "cTemp2::Func10() is called with " << _x << std::endl ;}

void cTemp2::Run()
{
    int choice ;
    int count = 0 ;
    std::cout << "Enter a number between 1 and 10, 0 to end: " ;
    std::cin >> choice ;
    while (choice >= 1 && choice < 11) {
        std::map<int, fPtr>::iterator MapIt ;
        MapIt = m_Map.find (choice) ;
        if (MapIt->second != NULL) {
            (this->*(MapIt->second))(count) ;
        }
        count ++ ;
        std::cout << "Enter a number between 1 and 10, 0 to end: " ;
        std::cin >> choice ;
    }
    std::cout << "cTemp2::Run() end" << std::endl ;
}
int main()
{
   cTemp2 Instance2 ;
   Instance2.Run() ;
   return 0 ;
}







- ps.
This blog is for my English abilities, and I'm not good at communicating in English. If you see grammatic, syntax or logical errors, or if you can't understand clearly, PLEASE COMMENT ON IT. Your comments definitely help me, and I really appreciate this. :)

- Written by Gordon


[C++] Function Pointer(1) (Global function & using array)



* Introduction *
- A week ago, to parse network packets I used to do 'if' for all case. During optimizations, I turned from 'if' to 'function pointer with map'. I'm going to write about the function pointer as known as possible.


* Basic usage (code) *
#include <iostream>
void     Function1() ;
int        Function2(int _x, int _y) ;
int main()
{
    //////////////////////////////////////////////////////////////////////////
    // Test inside Main function
        // for void Function1() ;
    void (*PtrFunc1)() ;
    PtrFunc1 = Function1 ;
    PtrFunc1() ;
        // for int Function2(int, int) ;
    int  (*PtrFunc2)(int, int) ;
    PtrFunc2 = Function2 ;
    int result = PtrFunc2(20, 10) ;
    std::cout << "Result = " << result << std::endl ;
    return 0 ;
}
void Function1()
{
    std::cout << "Function1" << std::endl ;
}
int  Function2(int _x, int _y)
{
    std::cout << "Function2" << "  X = " << _x << "  Y = " << _y << std::endl ;
    return (_x + _y) ;
}






* Using with array *
#include <iostream>
void    ArrayFunction1(int _x) ;
void    ArrayFunction2(int _x) ;
void    ArrayFunction3(int _x) ;
int main()
{
    int choice ;
    void (*f[3])(int) = {ArrayFunction1, ArrayFunction2, ArrayFunction3} ;
    std::cout << "Enter a number between 0 and 2, 3 to end: " ;
    std::cin >> choice ;
    while (choice >= 0 && choice < 3) {
        (*f[choice])(choice) ;
        std::cout << "Enter a number between 0 and 2, 3 to end: " ;
        std::cin >> choice ;
    }
    return 0 ;
}
void ArrayFunction1( int _x )
{
    std::cout << "ArrayFunction1: _x = " << _x << std::endl ;
}
void ArrayFunction2( int _x )
{
    std::cout << "ArrayFunction2: _x = " << _x << std::endl ;
}
void ArrayFunction3( int _x )
{
    std::cout << "ArrayFunction3: _x = " << _x << std::endl ;
}







Reference : How To C++ Program 4th edition



- ps.
This blog is for my English abilities, and I'm not good at communicating in English. If you see grammatic, syntax or logical errors, or if you can't understand clearly, PLEASE COMMENT ON IT. Your comments definitely help me, and I really appreciate this. :)

- Written by Gordon

2009년 12월 26일 토요일

[Server Programming] Circular Buffer (Ring Buffer)




For the first step to implement an IOCP(Input/Output Completion Port) server model, I simply made a buffer interface to use in the server. I used a buffer which I called "pulled buffer". I'm going to show you my new Ring Buffer with the pulled buffer.


* Pulled Buffer *
I'd used this pulled buffer for blocking-server models. Its principle is very simple.
You can easily understand this. It's assumed to use packets which contains information, (Size+Header) + (Data).

Hypothesize that a 8 bytes pulled buffer(Of course, it should be larger than 8 bytes in real situations)

|  |  |  |  |  |  |  |  |
  0  1  2  3  4  5  6  7

When I receive data, "abc", the buffer would be changed like this.
|a|b|c|  |  |  |  |  |
and I have a message, "xyz", again from the same computer. Then the message will be pushed back.
|a|b|c|x|y|z|  |  |

I have to order to computer to process, and the processed data will be removed, because its size is limited as 8 bytes. To process the packet, I take out "abcx". With this steps, the buffer will be change.
|y|z|  |  |  |  |  |  |

I receive again the packet, "Apple"
|y|z|A|p|p|l|e|  |

During the processing, it's necessary to copy 'yz' to be pulled from the 4th index to the zero index. It's cause to make overhead, so I changed to the Ring Buffer.



* Ring Buffer *
Assume the same situation that I showed. The difference is Ring Buffer has two index (or pointer).
Processing Start Pointer(PS), Writing Start Pointer(WS)  <--- I named it.

|  |  |  |  |  |  |  |  | PS = 0, WS = 0
  0  1  2  3  4  5  6  7

With receiving "abc",
|a|b|c|  |  |  |  |  | PS = 0, WS = 3
and adding "xyz"
|a|b|c|x|y|z|  |  | PS = 0, WS = 6

I order to the computer to process the message, "abcx". Then we can simply change the PS(Processing Start Pointer).
|a|b|c|x|y|z|  |  | PS = 4, WS = 6

And receiving "Apple",
|p|l|e|  |y|z|A|p| PS = 4, WS = 3

It has no copy time, because the messages will be written on current spot according to the PS & WS. However you should be careful about size. Ring Buffer requires large size than the packet size that can be received one time.


* Implementation *

I made it, using C++ language and Microsoft Visual Studio 2008.
"RingContext.h"
////////////////////////////////////////////////////////////////////////
const int BUFFER_SIZE = 16 ;
class cRingContext
{
private :
// Data structure
char m_Buffer[BUFFER_SIZE] ;
int m_Bytes ;
int m_ProcessingStart ;
int m_WritingStart ;
bool m_IsLink ;

// Hiding functions
void _MoveProcessingStart(int __in _index) ;
void _MoveWritingStart(int __in _index) ;
void _ResetProcessingStart() ;
void _ResetWritingStart() ;
void _AddBytes(int __in _Add) ;
int _SetByte(int __in _Bytes) ;
void _CheckIsLink() ;
int _Write(char* __in _Ptr, int __in _Bytes ) ;
int _Read(char* __out _New, int __in _Bytes ) ;
public:
cRingContext(void);
~cRingContext(void);
bool Reset() ;
bool RePlace() ;
// with copy (block)
int WriteToBuffer(char* __in _Ptr, int __in _Bytes)  ;
int ReadFromBuffer(char* __out _Ptr, int __out&_Bytes ) ;
int ObserveBuffer(char* __out _Ptr, int __out &_Bytes) ;
// without copy (non-block)
char* MoveProcessingStart(int __in _Bytes) ;
char* MoveWritingStart(int __in _Bytes) ;
// Get, Set functions
char* GetProcessingPtr() ;
char* GetWritingPtr()  ;
bool GetIsLink() ;
int GetProcessingLength() ; // From ProcessingStart To WritingStart
int GetWritingLength() ; // from WritingStart To BUFFER_SIZE
void Output() ;
};
////////////////////////////////////////////////////////////////////////




I contain the files with header & source too, but I haven't finish to implement the server yet, so it will be changed in many parts. Please understand about it.





- ps.
This blog is for my English abilities, and I'm not good at communicating in English. If you see grammatic, syntax or logical errors, or if you can't understand clearly, PLEASE COMMENT ON IT. Your comments definitely help me, and I really appreciate this. :)

- Written by Gordon



2009년 12월 25일 금요일

[C++] '\0' & '\n'


With testing length of characters, I discovered very harm misunderstanding.
I usually wrote '\n' to mean 'NULL', but it's terribly wrong.


Here is my source code.


* Code *
#include <iostream>
#include <string.h>
#include <locale.h>

int main()
{
char* Str1 = "Count." ;
char* Str2 = "Count.\0" ;
char* Str3 = "Count.\n" ;
wchar_t* wStr1 = L"Count." ;
wchar_t* wStr2 = L"Count.\0" ;
wchar_t* wStr3 = L"Count.\n" ;

std::cout << "Length of " << Str1 << " =" << strlen(Str1) << std::endl ;
std::cout << "Length of " << Str2 << " =" << strlen(Str2) << std::endl ;
std::cout << "Length of " << Str3 << " =" << strlen(Str3) << std::endl ;

wprintf(L"Length of '%s' : %d\n", wStr1, wcslen(wStr1) );
wprintf(L"Length of '%s' : %d\n", wStr2, wcslen(wStr2) );
wprintf(L"Length of '%s' : %d\n", wStr3, wcslen(wStr3) );

// to stop to destroy
int i ;
std::cin >>  i ;
return 0 ;
}






If you are a student who studies C++, let you guess the result.
Here is the result.

* Result


I have known '\n' means 'NULL', but it didn't.
'\n' means 'ENTER'.!!
'\0' means 'NULL'.







[Scrap] length of characters (I/O Function)



strlen, strlen_l, wcslen, wcslen_l, _mbslen, _mbslen_l, _mbstrlen, _mbstrlen_l



 prototype
size_t strlen( const char *str );
size_t strlen_l( const char *str, _locale_t locale );

size_t wcslen( const wchar_t *str );
size_t wcslen_l( const wchar_t *str, _locale_t locale );

size_t _mbslen( const unsigned char *str );
size_t _mbslen_l( const unsigned char *str, _locale_t locale );

 size_t _mbstrlen( const char *str );
 size_t _mbstrlen_l( const char *str, _locale_t locale );




Each of these functions returns the number of characters in str, excluding the terminal NULL. No return value is reserved to indicate an error, except for _mbstrlen, which returns -1 if the string contains an invalid multibyte character.



 Example from MSDN
// crt_strlen.c
// Determine the length of a string. For the multi-byte character
// example to work correctly, the Japanese language support for
// non-Unicode programs must be enabled by the operating system.

#include <string.h>
#include <locale.h>

int main()
{
   char* str1 = "Count.";
   wchar_t* wstr1 = L"Count.";
   char * mbstr1;
   char * locale_string;

   // strlen gives the length of single-byte character string
   printf("Length of '%s' : %d\n", str1, strlen(str1) );

   // wstrlen gives the length of a wide character string
   wprintf(L"Length of '%s' : %d\n", wstr1, wcslen(wstr1) );

   // A multibyte string: [A] [B] [C] [katakana A] [D] [\0]
   // in Code Page 932. For this example to work correctly,
   // the Japanese language support must be enabled by the
   // operating system.
   mbstr1 = "ABC" "\x83\x40" "D";

   locale_string = setlocale(LC_CTYPE, "Japanese_Japan");

   if (locale_string == NULL)
   {
      printf("Japanese locale not enabled. Exiting.\n");
      exit(1);
   }
   else
   {
      printf("Locale set to %s\n", locale_string);
   }

   // _mbslen will recognize the Japanese multibyte character if the
   // current locale used by the operating system is Japanese
   printf("Length of '%s' : %d\n", mbstr1, _mbslen(mbstr1) );

   // _mbstrlen will recognize the Japanese multibyte character
   // since the CRT locale is set to Japanese even if the OS locale
   // isnot.
   printf("Length of '%s' : %d\n", mbstr1, _mbstrlen(mbstr1) );
   printf("Bytes in '%s' : %d\n", mbstr1, strlen(mbstr1) );  
 
}



 Its result
Length of 'Count.' : 6
Length of 'Count.' : 6
Length of 'ABCァD' : 5
Length of 'ABCァD' : 5
Bytes in 'ABCァD' : 6







You can see the same thing at this page:
http://msdn.microsoft.com/en-us/library/78zh94ax.aspx

from MSDN