alones.kr/blog로 사이트 이전했습니다. 관련 공지

Alones world : Location : Tag : GuestBooks : Admin : New Article : Alones Wiki : Joinc TeamBlog
Alones world 블로그에 오신것을 환영해요^^
gidaeyeo@gmail.com
171
238
353108

Add to Google Reader or Homepage

 Subscribe in a reader

현재 접속 자 수
hit counters
------------
Recently Popular Posts
------------
'c++'에 해당되는 글 7건




  • initial version: 2007.06.28

컴퓨터가 리틀 엔디안과 빅 엔디안 중 어느 것을 사용하고 있는지 확인하는 코드입니다.

첫 번째 방법은 int 변수에 값을 넣고 변수의 주소를 (char*)로 casting 해서 하위 비트 형으로 만들고 값을 확인하는 방법입니다.

코드는 아래와 같을 것입니다.

int x = 1;if(*(char *)&x == 1) // 하위 비트 부터 값이 채워짐
        printf("little-endian\n");
else
                printf("big-endian\n");


//

두 번째 방법은 다음과 같이 union을 이용해서 하위 비트에 해당하는 두 번째 element의값을 확인하는 방법입니다. 코드는 아래와 같을 것입니다.

union{
        int i;
        char c[sizeof(int)];
} x;

x.i = 1;
if(x.c[0] == 1)
        printf("little-endian\n");
else
        printf("big-endian\n");

//


최신 내요은 아래 wiki에서 확인할 수 있습니다.
 in my wiki: http://alones.byus.net/moniwiki/wiki.php/c_cpp_tips_little_big_endian?action=show
크리에이티브 커먼즈 라이센스
Creative Commons License
Trackback 0 : Comment 7
http://alones.byus.net/tt/trackback/691
From. BlogIcon thedino 2007/06/28 00:53Delete / ModifyReply
ㅋㅋ위에 코드가...제가 다니는 회사..입사시험 문제에 나왔었는데..
뭐하는 코드인지 적으시오..........이렇게..ㅋ
저두 그때 처음 봤었는데..시험문제 풀면서 감동 받았죠..ㅋㅋㅋ
신입 시험에서 거의 일년만에 맞춘 사람이 나왔다는...ㅋㅋㅋㅋ//(자랑중)
BlogIcon alones 2007/06/28 01:14Delete / Modify
ㅎㅎ ^^ Cool~

그 문제를 시험 문제에서 처음 봤다면 (그 것도 신입 사원 시험이라는 긴장 속에서)

무슨 상상을 했을까요. 흐~

From. BlogIcon 이건우 2007/06/29 16:26Delete / ModifyReply
저는 아래와 같이 사용합니다.

int b = 1;
char a = 0;

a = (char) b;

if( a == 1 ) printf("little!";);
else printf("big!";);

Little Endian 방식의 장점을 살려보는 거죠...^^'
BlogIcon alones 2007/06/28 09:31Delete / Modify
흐흐 첫 번째 방식을 좀 더 간단히 썼군요.

스말일이 넘치고 있습니다~
From. BlogIcon oliver bjerrehus nude 2008/05/23 04:30Delete / ModifyReply
재미있는 아주 지점. 감사.
From. BlogIcon teen sex on the rag 2008/05/23 05:00Delete / ModifyReply
유용한 정보. 좋은 디자인.
From. BlogIcon rap sex 2008/05/23 05:40Delete / ModifyReply
이 위치는 아니라 유익한뿐 재미있는다!

  • initial version: 2007.06.15

목차

1 Introduction
2 Signature
3 Inside
4 Usgae
5 References
6 See Alos

1 Introduction #

STL의 Container (std::list, std::vector, etc)들의 모든 elements를 변환할 때 사용한다 (의미하는 그대로). algorithm에 포함된 것 답게 unary (단항) operator나 binary (이항) operator를 parameter로 받아서 처리해준다. 즉, std::vector의 모든 elements를 1씩 증가 시켜주거나 prefix로 특정 문자를 붙이는 경우 사용할 수 있을 것이다.

2 Signature #


다음과 같이 두 가지 원형을 제공한다.

template < class InputIterator, 
class OutputIterator, class UnaryOperator >
OutputIterator transform
( InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperator op ); template < class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperator > OutputIterator transform
( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result, BinaryOperator binary_op );
//

첫 번째 것은 단항 연산자를 이용해서 입력으로 들어오는 container의 처음과 끝 iterator를 처리해주고 결과를 output conatiner의 iterator에서 차례로 넣어 준다. 두 번째 것은 이항 연산자를 이용해서 첫 번째 container (first1 ~ last1)와 두 번째 container의 시작 (frist2) 부터를 처리해서 output containter의 iterator에 차례로 넣어 준다.

3 Inside #


Visual C++ 6.0은 위 두 개 원형을 다음과 같이 구현해두었다. 설명 그대로이다.

// TEMPLATE FUNCTION transform WITH UNARY OP
template<class _II, class _OI, class _Uop> inline
        _OI transform(_II _F, _II _L, _OI _X, _Uop _U)
        {for (; _F != _L; ++_F, ++_X)
                *_X = _U(*_F);
        return (_X); }
// TEMPLATE FUNCTION transform WITH BINARY OP
template<class _II1, class _II2, class _OI, class _Bop> inline
        _OI transform(_II1 _F1, _II1 _L1, _II2 _F2, _OI _X,
_Bop _B)
{for (; _F1 != _L1; ++_F1, ++_F2, ++_X) *_X = _B(*_F1, *_F2); return (_X); }
//

4 Usgae #

다음의 간단한 예는 10,20,30,40,50이 elements로 들어있는 vector를 unary operator를 이용해서 1씩 증가시키고 binary operator를 이용해서 최초 vector와 1씩 증가한 vector를 더하는 예이다.

#include <iostream>
#include <algorithm>
#include <vector>

// 1씩 증가 시키는 unary operator
int op_increase (int i)
{
        return ++i;
}

// 두 수를 더하는 binary operator
int op_sum (int i, int j)
{
        return i+j;
}

int main ()
{
  std::vector<int> first;
  std::vector<int> second;
  std::vector<int>::iterator it;

  // 첫 번째 container
  // 10, 20, 30, 40, 50
  for (int i=1; i<6; i++)
          first.push_back (i*10);

  // 두 번째 container size 할당
  second.resize(first.size());

  // usage 1
  // 첫 번째 container의 elements를 
  // op_increase unary operator를 이용해서 
  // 1씩 증가
  // 결과 11, 21, 31, 41, 51
  std::transform (first.begin(), first.end(),
                                  second.begin(),
                                  op_increase);

  // usage 2
  // 첫 번째 container의 elements와
  // usgae 1의 결과 container를
  // op_sum인 binary operator를 이용해서 
  // 더함
  // 결과 21, 41, 61, 81, 101
  std::transform (first.begin(), first.end(),
                              second.begin(),
                              first.begin(),
                              op_sum);

  // 결과 출력
  std:: cout << "first contains:";
  for (it=first.begin(); it!=first.end(); ++it)
    std::cout << " " << *it;

  std::cout << std::endl;
  return 0;
}

//


6 See Alos #



※ 최신 내용은 아래 wiki에서 확인할 수 있습니다.
 in my wiki: http://alones.byus.net/moniwiki/wiki.php/transform?action=show

크리에이티브 커먼즈 라이센스
Creative Commons License
Trackback 1 : Comment 10
http://alones.byus.net/tt/trackback/673
From. cheap clopidogrel 2008/05/22 22:26Delete / Modify
cheap clopidogrel
Trackback
From. BlogIcon raven riley nude video 2008/03/13 06:31Delete / ModifyReply
이 위치는 유익한뿐 아니라 재미있는다!
From. BlogIcon 2006 mustang mach 1 2008/03/13 07:11Delete / ModifyReply
너는 아주 좋은 보는 위치가 있는다!
From. BlogIcon bag big glad 2008/03/13 07:59Delete / ModifyReply
너는 우수한 위치가 있는다!
From. BlogIcon fucking man woman 2008/03/13 08:43Delete / ModifyReply
너는 아주 좋은 보는 위치가 있는다!
From. BlogIcon florida community colleges 2008/03/14 03:49Delete / ModifyReply
나의 친구는 너의 위치의 현재 팬이 되었다!
From. BlogIcon ads sex woman 2008/03/14 04:36Delete / ModifyReply
좋은 위치! 너를 감사하십시요.
From. BlogIcon airport parking spokane 2008/03/14 04:37Delete / ModifyReply
너는 우수한 위치가 있는다!
From. BlogIcon milf video favourites 2008/05/23 04:16Delete / ModifyReply
위치에 그것을 중대한 일은 좋아했다!
From. BlogIcon free poker software strip 2008/05/24 00:35Delete / ModifyReply
걸출한 블로그!
From. BlogIcon diviant art naruto xxx 2008/05/24 00:40Delete / ModifyReply
너의 방문한 위치를 즐기는!

 std::list::sort()는 std::list의 element를 정렬할 때 쓰기 유용하며 STL의 template과 재정의를 잘 반영한 api라고 할 수 있을 것이다 (대부분의 STL feature들이 그렇겠지만).

아무튼 std::list::sort()에 대해서 작성해보았다.

주의할 것은 VC6.0이 표준을 잘 따르지 않아서 sort의 두 번째는 주의를 요하기도 한다.

최신은 아래 wiki에서 update해갈 것이다.

 in my wiki: http://alones.byus.net/moniwiki/wiki.php/sort?action=show

  • initial version: 2007.05.25

목차

1 Introduction
2 Signature
3 Usage 1: sort()
4 Usage 2: sort(Compare comp)
5 Usage 3: sort(greater<T> pr)
6 References

1 Introduction #

list::sort는 list 내에 있는 element 들을 소팅 해준다. 소팅의 기준은 elements의 operator< 연산자 재 정의를 따르거나 sort에 전달되는 Compare에 따른다. 그래서 아래 Signatrue와 같이 두 가지 방식이 제공된다. Template과 재정의를 막각하게 제공해주는 STL의 성격을 잘 드러내 주는 api라고 볼 수 있다.

2 Signature #


두 가지 형식이 있으며
// type1. element의 operator< 연산자에 따라 소팅
void sort ( );

// type2. 전달되는 comp에 따라 소팅       
template <class Compare>
  void sort ( Compare comp );
//

주의 할 것은 VC6.0의 경우는 두 번째 방식에 대해서 표준을 따르지 않고 typ2를 아래와 같이 정의하고 있다.

// type1. element의 operator< 연산자에 따라 소팅
void sort();

// type2. struct std::greater<T>를 구현해서 
// 넘겨줘야 한다.usage 3 참고
template<class Pred>
    void sort(greater<T> pr);
//

3 Usage 1: sort() #

MyData라는 class는 id (int)와 name (std::string)을 가지고 있다고 가정해 보자 id에 따라 오름 차순 (작은 수가 앞으로 오게) 으로 오게 소팅을 하고 출력하는 코드는 void sort()를 이용해서 다음과 같이 작성할 수 있을 것이다.

list::sort를 위해서 MyData의 opeartor<을 재 정의 했다.

#include <list>
#include <string>
#include <iostream>

class MyData
{
        // 편의상 public으로
public:
        int                     m_nId;
        std::string     m_strName;

public:

        // operator< 재 정의 sort에서 사용 됨
        bool operator<(const MyData& other)
        {
                if( m_nId < other.m_nId)
                        return true;
                else
                        return false;
        };

        // constructor
        MyData(int nId, std::string strName)
        {
                m_nId = nId;
                m_strName = strName;
        };
};

void main()
{
        std::list<MyData>               dataList;

        // elements 채우기
        dataList.push_back( MyData(100, "alones1"));
        dataList.push_back( MyData(50, "alones2"));
        dataList.push_back( MyData(16, "alones3"));
        dataList.push_back( MyData(58, "alones4"));

        // 소팅: MyData::operator< 을 이용
        dataList.sort();


        std::list<MyData>::iterator it = dataList.begin();

        // 결과 출력 id에 따라 오름 차순으로 정렬
        while( it != dataList.end())
        {
                std::cout<<"id: "<<(*it).m_nId
                        <<" name: "<<(*it).m_strName<<std::endl;

                ++it;
        }
}
//



4
Usage 2: sort(Compare comp) #

위의 MyData를 두 번째 sort()을 이용해서 정렬 해보자. 즉, 정렬 시 MyData의 operator<을 사용하지 않고 comp를 별도로 만들어서 정렬하는 것이다. comp는 두 개의 파라미터를 받으며 (물론 list의 element와 같은 type이어야 할 것이다) 소팅 시 첫 번째 파라미터가 두 번째 파라미터에 오면 true를 그렇지 않으면 false를 반환하게 작성하면 된다.

아래 Comp()는 Usage 1과 같은 결과를 가져오기 위해 작성되었다.


#include <list>
#include <string>
#include <iostream>

class MyData
{
        // 편의상 public으로
public:
        int                     m_nId;
        std::string     m_strName;

public:

        // operator< 재 정의 sort에서 사용 됨
        bool operator<(const MyData& other)
        {
                if( m_nId < other.m_nId)
                        return true;
                else
                        return false;
        };

        // constructor
        MyData(int nId, std::string strName)
        {
                m_nId = nId;
                m_strName = strName;
        };

        MyData(){};
};

bool Comp(MyData first, MyData second)
{
        if( first.m_nId < second.m_nId)
                return true;
        else
                return false;
}

void main()
{
        std::list<MyData>               dataList;

        // elements 채우기
        dataList.push_back( MyData(100,