cin.tie(NULL), sync_with_stdio(false)

c4fiber·2022년 3월 10일
0

code-interview

목록 보기
2/12

백준 알고리즘 문제를 풀이하면서 새로운 부분을 봤다.

이분 탐색을 헷갈리지 않게 구현하기에서 예시문제로 나무 자르기 를 제시한다.

solution 코드중에

#define fastio cin.tie(0)->sync_with_stdio(0);
cin.tie(NULL); sync_with_stdio(false);

이렇게 분리하여 작성하는건 봤지만 클래스 참조로 더 간결하게 표현하는걸 봤다.

레퍼런스를 찾아보니 cin 클래스는 ios를 상속한 istream을 상속하며, tie 함수는 연결되어있던 stream 포인터를 반환한다.

즉 cin.tie(0) 호출로 반환된 'ios'객체를 참조하여 sync_with_stdio(0)를 호출하는 것.

자세하게 보기위해 간단하게 코드를 작성해보았다.


알아두기

  1. tie() 는 tie되어있던 ostream을 반환
  2. tie 함수에 ostream을 넣으면 해당 ostream과 tie를 수행함
  3. ostream은 ios_base를 상속한 ios를 상속
#include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;

int main() {
    cout << "pointer of cout: " << cin.tie() << endl;
    cout << "cout is not tied to any other output stream: " << cin.tie()->tie() << endl;

    cout << endl;

    cout << "before untie cin to cout: " << cin.tie(0) << endl;
    cout << "after untie cin to cout: " << cin.tie() << endl;
    cout << " - tie to 0 == is not tied(?)" << endl;

    return 0;
}

결과:


간단하지만 이해하는데는 정말 오래걸렸다.
세계는 넓구나

출처:
https://www.cplusplus.com/reference/ios/
https://www.cplusplus.com/reference/ios/ios/tie/

profile
amazing idiot

0개의 댓글