对初始化的向量

有人可以帮我理解这段代码的工作原理吗? 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的结构)对初始化的向量

从我可以告诉,它把在一个单独的阵列中的每个对,但我从来没见过这样的声明。

回答:

类模板std::vector具有构造

template <class InputIterator> 

vector(InputIterator first, InputIterator last, const Allocator& = Allocator());

因此,在此声明

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

有使用此构造。 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;

}

它的输出是

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

,你可以只写

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

这里是另一个示范性程序

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

}

它的输出是相同的,如上所示。

以上是 对初始化的向量 的全部内容, 来源链接: utcz.com/qa/258909.html

回到顶部