-3

Can someone please help me understand how this piece of code works?

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);

(Pair is a structure that has two integers a and b)

From what I could tell, it places each pair in a separate array, but I've never seen this kind of declaration before.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • What is `Pair`? What exactly do you not understand? Are you familiar with `vector`? Did you check the documentation for `vector`? – Vittorio Romeo Dec 03 '17 at 00:00

1 Answers1

0

The class template std::vector has constructor

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

Thus in this declaration

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

there is used this constructor. a and a + n specify the range [a, a + n ). Elements in this range are used to initialize the vector.

As for this declaration

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

then it is a declaration of an array each element of which is initialized by using a brace list. It seems that that the user-defined type Pair is either an aggregate or has a constructor that accepts two arguments.

Here is a demonstrative program

#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;
}

Its output is

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

Instead of these statements

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

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

you could just write

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

Here is another demonstrative program

#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;
}

Its output is the same as shown above.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335