구조체란?

서로 다른 데이터형을 집합시켜 단일변수로 처리하게 해주는 복합 데이터형이다. 우리가 흔히 아는 int,double,char형 등의 변수와 동일하게 0차원으로써 하나의 데이터 타입을 만족한다.

선언된 순서대로 메모리에 할당되며 이의 특성을 고려하여 파일 입추력시 유용하다.

사용방법은

struct 구조체명{

맴버1 선언
맴버2 선언
...
}<전역 구조체명>;

참고로 구조체는 파스칼 네이밍 방식을 사용한다.(appleFruitKiwi 대분자로 띄어쓰기 표시)

구조체와 메모리

구조체의 틀자체는 공간을 차지않는다.

일반 데이터타입과 마찬가지로 구조체로 변수를 찍어내면 그때 메모리가 할당되게 된다.

구조체가 받을 수 있는 맴버

int char double등 뿐 아니라 배열, 또 다른 구조체까지 구조체의 맴버로 사용 가능하다.

구조체 만들어보기

struct끼리른 대입연산이 가능하며 입력한 변수 순서 그대로 입력된다.

struct도 배열이 가능하므로 초기화시 {{},{},{}..} 로 해준다.

구조체 배열생성및 대입

이런식으로 할경우 형식이 다르다는 오류가 발생.

직접 고치려면 이렇게 일일 히 바꾸어 주어야한다.

구조체 포인터

해당 포인터의 맴버변수 접근시 * 가아닌 ->를 이용한다.

sort algorithm

1)selection sort 뽑을 때 작은수나 큰수부터 차례대로 뽑음

2)insertion sort 넣을 때 작은수나 큰수부터 차례대로 넣음

ex)원하는 숫자를 넣으면 알아서 순서를 배열해주는 알고리즘

{.cpp}
// ConsoleApplication27.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

const int declared_size = 20;

void fillarray(int a[], int size, int& numberused);

int indexofsmallest(int a[], int startindex, int numberused);

void sort(int a[], int numberused);

void swapvalues(int& v1, int& v2);

int search(int a[], int numberused, int target);

int main()
{
    cout << "this program sort\n";
    int samplearray[10], numberused;
    fillarray(samplearray, 10, numberused);
    sort(samplearray, numberused);
    cout << "it is \n";
    for (int index = 0; index < numberused; index++)
    {
        cout << samplearray[index] << "";
        cout << endl;
    }


    return 0;


}

void fillarray(int a[], int size, int& numberused)
{
    cout << "enter" << size << " no negative nube\n mark the endof lis is negative ";
    int next, index = 0;
    cin >> next;
    while ((next > 0) && (index < size))
    {
        a[index] = next;
        index++;
        cin >> next;
    }
    numberused = index;
    cout << "index is"<<index << endl;
}

void sort(int a[], int numberused)
{
    int indexofnextsmallest;
    //맨마지막에 두개가 남을때 이것을 한번만 돌리면된다. 이유는 둘중작은거 하나만 찾으면 되기 때문이다.
    for (int index = 0; index < numberused - 1; index++)
    {
        indexofnextsmallest = indexofsmallest(a, index, numberused);
        swapvalues(a[index], a[indexofnextsmallest]);
    }
}

void swapvalues(int&v1, int& v2)
{
    int temp;
    temp = v1;
    v1 = v2;
    v2 = temp;
}

int indexofsmallest(int a[], int startindex,int numberused)
{
    //min값에 a의 시작값을 넣어준다.
    int min = a[startindex];
    //indexofmin에는 index의 시작값을 넣어준다.
    int indexofmin = startindex;
    //a의 index는 startindex+1부터 시작된다.
    //만약 a[index]가 a의 맨시작점인 min값보다 작다면 min값에 작은값a을 넣어준다.
    //indexofmin에는 작은값을 갖는 index값을 넣어준다.
    for (int index=startindex+1;index < numberused; index++)
        if (a[index] < min)
        {
            min = a[index];
            indexofmin = index;
        }
    return indexofmin;
}

//a배열과 그것에대한 크기와 taget값을 받아준다.
//target과 동일한 a[]배열의 index값을 찾아준다.
int search(int a[], int numberused, int target)
{
    int index = 0;
    bool found = false;
    //a[index]값=target과 동일한 값이되면 루프를 멈춘다.
    while ((!found) && (index < numberused))
    {
        if (target == a[index])
            found = true;
        else
            index++;
    }
    if (found)
        return index;
    //else가 나오는 경우는 a[]의 배열이 끝나도록 target과 동일한 값이 없을때 이다.
    else
        return -1;
}

structure part

구조체이다.

C/C++ 언어는 기본 데이터형을 최소화하기 위해서 많이 사용하는 형식의 데이터형만을 기본 데이터형 으로 정의하고 나머지는 프로그래머가 데이터형을 정의해서 사용할수 있도록 만들어졌는데 이를 구조체를 통해 정의한다.

structure안에 정의된 변수를 membervaluable이라 한다.

membervaluable 의 순서는 중요하지 않다.

선언방법 struct <구조체명> { membervaluable 선언; };

예제)

{.cpp}
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

struct Theater
{
    string strName;
    int nTripTime;
    int pShowTime[10];
};

int main()
{
    Theater aTheater;
    aTheater = { "Lotte Cinema in Gunkuk Univ station",10,{9,10,11,13,14,15,16,18,20,23} };
    cout<<aTheater.strName<<endl<<"The time from home to the cinema : "<< aTheater.nTripTime << "minutes"<<endl<<"Movie : kings man2";
    for (int i=0; i < 10; i++)
    {
        cout << endl << i+1 << "- showing time : " << aTheater.pShowTime[i]<<":00";
    }


    return 0;
}

'언어 > CPP(cpp)' 카테고리의 다른 글

static,vector(벡터)  (0) 2017.12.25
클래스 생성자  (0) 2017.12.25
array(배열)  (0) 2017.12.25
영화 별점 표본 검사 코드  (0) 2017.12.25
assert,debug,driver,stub,중단점,디버그,조사식  (0) 2017.12.25

+ Recent posts