vector<pair<int, int>> nums_list;
for (int i = 0; i < nums.size(); i++) {
nums_list.emplace_back(i, nums[i]);
}
這段代碼創(chuàng)建了一個名為`nums_list`的`vector`容器,其中存儲了一系列的`pair<int, int>`。代碼的邏輯如下:
1. 創(chuàng)建一個空的`vector<pair<int, int>>`容器`nums_list`,用來存儲整數對。
2. 使用`for`循環(huán)遍歷整數數組`nums`,循環(huán)變量`i`從0到`nums`的長度減1。
3. 在循環(huán)中,使用`emplace_back()`函數將一個新的`pair<int, int>`對象加入到`nums_list`中。這個對象的第一個整數(`first`成員)是`i`,表示數組索引,第二個整數(`second`成員)是`nums[i]`,表示數組中索引為`i`的元素的值。
下面是一個示例代碼,展示了如何使用上述代碼創(chuàng)建`nums_list`:
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
std::vector<std::pair<int, int>> nums_list;
for (int i = 0; i < nums.size(); i++) {
nums_list.emplace_back(i, nums[i]);
}
// 輸出 nums_list 中的元素
for (const auto& pair : nums_list) {
std::cout << "(" << pair.first << ", " << pair.second << ") ";
}
std::cout << std::endl;
return 0;
}
在上述代碼中,我們首先創(chuàng)建了一個整數數組nums
,其中包含了一些整數。然后,我們創(chuàng)建了一個空的nums_list
容器。接下來,我們使用for
循環(huán)遍歷整數數組nums
,并將每個數組元素和其對應的索引作為一個pair
對象加入到nums_list
容器中。最后,我們遍歷nums_list
容器,并輸出其中的每個整數對。
輸出結果示例:文章來源:http://www.zghlxwxcb.cn/news/detail-729163.html
(0, 1) (1, 2) (2, 3) (3, 4) (4, 5)
在上面的示例中,nums
數組中的元素為從1到5的連續(xù)整數。nums_list
容器中存儲了一系列的整數對,每個整數對表示數組的索引和對應元素的值。因此,最后的輸出結果是(0, 1) (1, 2) (2, 3) (3, 4) (4, 5)
。文章來源地址http://www.zghlxwxcb.cn/news/detail-729163.html
到了這里,關于創(chuàng)建了一個名為nums_list的vector容器,其中存儲了一系列的pair<int, int>的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!