2017-12-02 9 views
-3

누군가이 코드가 어떻게 작동하는지 이해할 수 있도록 도와 줄 수 있습니까? Pair a[] = {{5, 29}, {39, 40}, {15, 28}, {27, 40}, {50, 90}}; int n = sizeof(a)/sizeof(a[0]); vector<Pair> arr(a, a + n); 내가 말할 수있는 건쌍 초기화 벡터

, 그것은 별도의 배열의 각 쌍을 배치 (쌍 두 정수 a를 가지고와 b 구조이다)하지만 내가 전에 선언의이 종류를 본 적이 없어요.

+0

'쌍'이란 무엇입니까? 정확하게 당신은 이해하지 못합니까? 당신은'벡터'에 익숙합니까? 'vector'에 대한 문서를 확인 했습니까? –

답변

0

클래스 템플릿 std::vector이 생성자가 사용이 선언

vector<Pair> arr(a, a + n); 

에 따라서 생성자에게

template <class InputIterator> 
vector(InputIterator first, InputIterator last, const Allocator& = Allocator()); 

있다. aa + n[a, a + n) 범위를 지정합니다. 이 범위의 요소는 벡터를 초기화하는 데 사용됩니다. 이 선언

Pair a[] = {{5, 29}, {39, 40}, {15, 28}, {27, 40}, {50, 90}}; 

로서는

는 그것의 각 요소는 브레이스 목록을 사용하여 초기화 배열 선언한다. 사용자 정의 유형 Pair은 집계이거나 두 개의 인수를 허용하는 생성자가있는 것으로 보입니다. 여기

은 시범 프로그램을이다

#include <iostream> 
#include <vector> 

struct Pair 
{ 
    int x; 
    int y; 
}; 

int main() 
{ 
    Pair a[] = 
    { 
     {5, 29}, {39, 40}, {15, 28}, {27, 40}, {50, 90} 
    }; 

    size_t n = sizeof(a)/sizeof(a[0]); 

    std::vector<Pair> arr(a, a + n); 

    for (const Pair &p : arr) 
    { 
     std::cout << "{ " << p.x 
        << ", " << p.y 
        << " }" << ' '; 
    } 

    std::cout << std::endl; 

    return 0; 
} 

그것의 출력은 그냥 쓸 수있는 대신이 문

size_t n = sizeof(a)/sizeof(a[0]); 

    std::vector<Pair> arr(a, a + n); 

{ 5, 29 } { 39, 40 } { 15, 28 } { 27, 40 } { 50, 90 } 

입니다

std::vector<Pair> arr(std::begin(a), std::end(a)); 
,536 91,363,210

여기서 상기 도시 된 바와 같이, 그 출력이 동일한

#include <iostream> 
#include <vector> 
#include <iterator> 

struct Pair 
{ 
    int x; 
    int y; 
}; 

int main() 
{ 
    Pair a[] = 
    { 
     {5, 29}, {39, 40}, {15, 28}, {27, 40}, {50, 90} 
    }; 

    std::vector<Pair> arr(std::begin(a), std::end(a)); 

    for (const Pair &p : arr) 
    { 
     std::cout << "{ " << p.x 
        << ", " << p.y 
        << " }" << ' '; 
    } 

    std::cout << std::endl; 

    return 0; 
} 

다른 프로그램을 실증한다.