어떻게 하면 코드 작성자가 사용자에게 더 편의를 제공할 것인가?

C에서는 structure의 멤버들에 대한 정보/사용법을 사용자가 모두 알아야만 한다.

#include <stdio.h>

//code writer
typedef struct USERDATA
{
	int nAge;
	char szName[32];
	void(*Print)(struct USERDATA *);	//step 3 improvement
} USERDATA;
 
void PrintData(USERDATA *pUser)			//step 2 improvement
{
	printf("%d, %s\n", pUser->nAge, pUser->szName);
}

// code user
int main(void)
{
	USERDATA user = { 20, "Peter", PrintData };
	//printf("%d, %s\n", user.nAge, user.szName);		//step 1 C style
	//PrintData(&user);					//step 2 improvement
	user.Print(&user);					//step 3 improvement
    
	return 0;
}

From step 3, it seems the function is working as structure's member in code user point of view.

But it looks redundant which is using 'user' stucture's address agin from Print member function.

// code user
int main(void)
{
	USERDATA user = { 20, "Peter", PrintData };
    //printf("%d, %s\n", user.nAge, user.szName);	//step 1 C style
    //PrintData(&user);					//step 2 improvement
    //user.Print(&user);				//step 3 improvement
    user.Print();					//step 4 improvement
    
	return 0;
}

In C++, it's decided to hide &user parameter. it's related with 'this' pointer.

 

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

// code writer
class CTest
{
public :
	CTest() {}
    
	int m_nData1 = 10;
	int m_nData2 = 20;
    
	void PrintData(void)
	{
		cout << m_nData1 << endl;
		cout << m_nData2 << endl;
	}
};

// user code
int _tmain(int argc, _TCHAR* argv[])
{
	CTest t;
	t.PrintData();

	return 0;
}
반응형

'Prog&Algol' 카테고리의 다른 글

Algo | C++ | DFS and BFS  (0) 2022.03.30
BJ | 2178 | BFS shorted path  (0) 2022.03.30
C++ | Namespace  (0) 2022.03.29
BJ | 9996 | connect server when missing Korea  (0) 2022.03.29
BJ | 2309 | 일곱 난쟁이 | Combination  (0) 2022.03.22

2.4.1 Namespace

C++가 지원하는 각종 요소들(변수, 함수, 클래스 등)을 한 범주로 묶어주기 위한 문법

소속이나 구역이라는 개념

 

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

namespace TEST
{
	int g_nData = 100;
    
	void TestFunc(void)
	{
		std::cout << "TEST::TestFunc()" << std::endl;
	}
}
 
// _tmain은 Global namespace 소속
int _tmain(int argc, _TCHAR* argv[])
{
	TEST::TestFunc();
	// cout은 std 네임스페이스 소속
	std::cout << TEST::g_nData << std::endl;
    
	return 0;
}

 

2.4.2 Using

네임스페이스를 임의로 생략

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

// declare std namespace with 'using' keyword
using namespace std;

namespace TEST
{
	int g_nData = 100;
    
	void TestFunc(void)
	{
		cout << "TEST::TestFunc()" << endl;
	}
}

// declare TEST namespace with 'using' keyword
using namespace TEST;

int _tmain(int argc, _TCHAR* argv[])
{
	TestFunc();
	cout << g_nData << endl;
    
	return 0;
}

 

2.4.3 nested Namespace

네임스페이스 안에 또 다른 네임스페이스가 속할 수 있음

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

using namespace std;

namespace TEST
{
	int g_nData = 100;
    namespace DEV
    {
    	int g_nData = 200;
        namespace WIN
		{
        	int g_nData = 300;
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << TEST::g_nData << endl;
    cout << TEST::DEV::g_nData << endl;
    cout << TEST::DEV:WIN::g_nData << endl;
    
    return 0;
}

2.4.4 Namespace의 다중정의

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

using namespace std;

//global
void TestFunc(void) { cout << "::TestFunc()" << endl;

namespace TEST
{
	void TestFunc(void){
    	cout << "TEST:TestFunc()" << endl;
	}
}

namespace MYDATA
{
	void TestFunc(void){
    	cout << "MYDATA::TestFunc()" << endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{

	TestFunc();	//implicitly global
    ::TestFunc();	//explicitly global
    TEST::TestFunc();
    MYDATA::TestFunc();
    
    return 0;
}

첫번째 TestFunc()은 별도의 Namespace를 지정하지 않았는데, _tmain()함수의 namespace가 전역이기 때문이다.

 

int TestFunc(int);
int Data::TestFunc(int);
int CMyData::TestFunc(int);
int CMyData::TestFunc(int) const;

1번은 소속이 없음, 2~3번은 속해 있는 namespace나 class가 존재함, 4번은 CMyData라는 클래스의 상수형 Method임

 

2.5.4 using 선언과 전역 변수

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

using namespace std;

namespace TEST
{
	int nData = 200;
}

using namespace TEST;

int _tmain(int argc, _TCHAR* argv[])
{
	cout << nData << endl;
    
    return 0;
}

위의 예제에서 컴파일 에러가 발생함. nData가 전역 네임스페이스일 수도 TEST 네인스페이스일수도 있음

::nData라고 범위 식별자를 기술하거나, TEST::nData라고 정확하게 네임스페이스를 기술해야 함

반응형

'Prog&Algol' 카테고리의 다른 글

BJ | 2178 | BFS shorted path  (0) 2022.03.30
C++ | history of Class  (0) 2022.03.30
BJ | 9996 | connect server when missing Korea  (0) 2022.03.29
BJ | 2309 | 일곱 난쟁이 | Combination  (0) 2022.03.22
C++ | lower_bound & upper_bound  (0) 2022.03.22

 

의식의 흐름대로 짠 소스

개선점 : 모든 케이스를 모두 디버깅 하기 힘듬 

#include <iostream>
#include <vector>
using namespace std;

int main(){
	string inputPat;
	string inputStr;
	vector<string> result;
	
	int cntStr;
	int checked;
	
	cin >> cntStr;
	cin >> inputPat;
	 
	for (int i=0;i<cntStr;i++){
		cin >> inputStr;
		
		int fi=0;
		int pi=0;
		int si=0;
		
		//check front pattern
		for (;fi<inputPat.length() && fi<inputStr.length() && inputPat[fi]!='*';fi++){
			if ( inputPat[fi] == inputStr[fi]) {
					checked = 1;
			} else {	
			 checked = 0;
			 break;
			}
		}
		if (inputPat[fi] !='*') checked = 0;
				
		//check last pattern
		if ( checked ==1 && inputPat[fi]=='*' ){
			pi = inputPat.length()-1;
			si = inputStr.length()-1;
			
			for (; inputPat[pi]!='*' && pi>0 && si>0 && si>=fi ; pi--, si-- ){
				if ( inputPat[pi] == inputStr[si]) {
					checked = 1;
				} else {
					checked = 0;
					break;
				}
			}
			if (inputPat[pi] !='*') checked = 0;
		}
		
		if (checked == 1) result.push_back("DA");
		else result.push_back("NE");
	}
	
	for (auto a : result) cout << a << "\n";

	return 0;									
}

 

std 를 사용해서 조금더 간략화

개선점 : 가장 큰 조건을 먼저 처리하자 > 그리고 나서 세부 조건을 처리

           여러 레벨의 조건을 간략화 하

#include <iostream>
#include <vector>
using namespace std;

int main(){
	string inputPat;
	string frontPat;
	string endPat;
	
	vector<string> result;
	
	int cntStr;
	int checked;
	int stari;
	
	cin >> cntStr;
	cin >> inputPat;
	
	stari = inputPat.find("*");
	frontPat = inputPat.substr(0,stari);
	endPat = inputPat.substr(stari+1,inputPat.length()-1);
	
	for (int i=0;i<cntStr;i++){
		string inputStr;
		cin >> inputStr;
		
		string frontStr;
		string endStr;
		checked = 0;
		
		//check front pattern
		if (inputStr.length()>=frontPat.length()){
			frontStr = inputStr.substr(0,stari);
			if (frontStr == frontPat){
				inputStr.erase(0,stari);	
		
				//check last pattern
				if (inputStr.length()>=endPat.length()){
					endStr = inputStr.substr(inputStr.length()-endPat.length(), endPat.length() );
					if (endStr == endPat) {
						checked = 1;	
					}
				}
			} 
		}
		if ( checked ==1 ) result.push_back("DA");
		else result.push_back("NE");
	}	
	
	for (auto a : result) cout << a << "\n";

	return 0;									
}

 

불필요한 검사 제거

#include <iostream>
#include <vector>
using namespace std;

int main(){
	string inputPat;
	string frontPat;
	string endPat;
	
	vector<string> result;
	
	int cntStr;
	int checked;
	int stari;
	
	cin >> cntStr;
	cin >> inputPat;
	
	stari = inputPat.find("*");
	frontPat = inputPat.substr(0,stari);
	endPat = inputPat.substr(stari+1,inputPat.length()-1);
	
	for (int i=0;i<cntStr;i++){
		string inputStr;
		cin >> inputStr;

		checked = 0;
		
		//check front pattern
		if ( inputStr.length() >= frontPat.length()+endPat.length()) {
			if ( (frontPat == inputStr.substr(0, frontPat.length())) &&
				 (endPat == inputStr.substr(inputStr.length()-endPat.length())) ) 
				 	checked = 1;
		}
		
		if ( checked ==1 ) result.push_back("DA");
		else result.push_back("NE");
	}	
	
	for (auto a : result) cout << a << "\n";

	return 0;									
}
반응형

'Prog&Algol' 카테고리의 다른 글

C++ | history of Class  (0) 2022.03.30
C++ | Namespace  (0) 2022.03.29
BJ | 2309 | 일곱 난쟁이 | Combination  (0) 2022.03.22
C++ | lower_bound & upper_bound  (0) 2022.03.22
Math | Sieve of Eratosthenes  (0) 2022.03.21

#

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

using namespace std;

//초기화 하고나서, push_back하면 뒤에 들어감 
//vector<int> target(10);

vector<int> target;
vector<int> selected;

int find100sum(vector<int> dwarfHeight, int num){

	if ( num == 7 )	{
		if ( accumulate(target.begin(), target.end(), 0) == 100 ) {
			sort(target.begin(), target.end());
			for (int i=0; i<target.size();i++ ) cout << target[i] << "\n";
			return 1;
		}
		return 0;
	}
	
	for (int i=num;i<dwarfHeight.size();i++){
		
		target.push_back(dwarfHeight[i]);
		if ( find100sum(dwarfHeight, num+1) == 1 ) return 1;
		target.pop_back();
	}
	
	return 0;
}

int main(){
	
	vector<int> dwarfHeight(9);
	
	for (int i=0;i<9;i++) cin >> dwarfHeight[i];
	
	find100sum(dwarfHeight, 0);
	
	return 0;	
}
반응형

'Prog&Algol' 카테고리의 다른 글

C++ | Namespace  (0) 2022.03.29
BJ | 9996 | connect server when missing Korea  (0) 2022.03.29
C++ | lower_bound & upper_bound  (0) 2022.03.22
Math | Sieve of Eratosthenes  (0) 2022.03.21
Math | Permutation & Combination  (0) 2022.03.21
  • upper_bound - return the position of exceeding value from key
  • lower_bound - return the position of same or first larger value than key
  • Target array or vector shall be in sorted condition.
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main(){
	vector<int> v;
	int a[5] = {1,2,2,2,3};
	for (int i=0; i<5; i++){
		v.push_back(a[i]);
	}
	int x=2;
	int c=(int)(upper_bound(v.begin(), v.end(), x) - lower_bound(v.begin(), v.end(), x));
	int f=(int)(lower_bound(v.begin(), v.end(), x) - v.begin());
	int t=(int)(upper_bound(v.begin(), v.end(), x) - v.begin());
	
	int f2= *lower_bound(v.begin(), v.end(), x);
	int t2= *upper_bound(v.begin(), v.end(), x);
	printf(" %d count : %d, starting : %d, ending : %d\n", x, c, f, t);
	printf(" lower bound start : %d, upper bound start : %d\n", f2, t2);
	
	c = (int) (upper_bound(a,a+5,x) - lower_bound(a,a+5,x));
	f = (int) (lower_bound(a,a+5,x) - a);
	t = (int) (upper_bound(a,a+5,x) - a);
	f2 = *lower_bound(a,a+5,x);
	t2 = *upper_bound(a,a+5,x);

	printf(" %d count : %d, starting : %d, ending : %d\n", x, c, f, t);
	printf(" lower bound start : %d, upper bound start : %d\n", f2, t2);
	
	return 0;
}
반응형

'Prog&Algol' 카테고리의 다른 글

BJ | 9996 | connect server when missing Korea  (0) 2022.03.29
BJ | 2309 | 일곱 난쟁이 | Combination  (0) 2022.03.22
Math | Sieve of Eratosthenes  (0) 2022.03.21
Math | Permutation & Combination  (0) 2022.03.21
Algo | C++ | priority Queue  (0) 2022.03.20

+ Recent posts