-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的結構)對初始化的向量
從我可以告訴,它把在一個單獨的陣列中的每個對,但我從來沒見過這樣的聲明。
有人可以幫我理解這段代碼的工作原理嗎? 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);
有使用此構造。 a
和a + 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;
}
它的輸出是相同的,如上所示。
什麼是配對?你不明白什麼?你熟悉'vector'嗎?你檢查過「vector」的文檔嗎? –