如何将数组存入list<vector<int>>并通过迭代器输出指定数据?
解决list<vector>存储数组元素并输出指定序列的问题
我明白你想要把给定的int数组拆分后存入list<vector<int>>容器,然后输出特定的序列。咱们一步步来实现:
步骤说明
首先得明确你需要输出的序列对应的是原数组的哪些子片段:
- 子片段1:原数组前3个元素
3,5,4 - 子片段2:原数组最后1个元素
4 - 子片段3:原数组第4、5个元素
0,7 - 子片段4:原数组第4到第7个元素
0,7,9,1 - 子片段5:原数组第5到第9个元素
7,9,1,3,6 - 子片段6:原数组第6到最后一个元素
9,1,3,6,8,4
接下来我们把这些子片段分别存入vector<int>,再将每个vector添加到list<vector<int>>中,最后通过迭代器遍历输出所有元素。
完整代码实现
#include <iostream> #include <list> #include <vector> using namespace std; int main() { // 原数组 int t[] = { 3 , 5 , 4 , 0 , 7 , 9 , 1 , 3 , 6 , 8 , 4 }; // 创建目标容器 list<vector<int>> bar; // 将各个子数组存入vector并添加到list中 // 子片段1: 3,5,4 bar.push_back(vector<int>(t, t + 3)); // 子片段2: 4 bar.push_back(vector<int>(t + 10, t + 11)); // 子片段3: 0,7 bar.push_back(vector<int>(t + 3, t + 5)); // 子片段4: 0,7,9,1 bar.push_back(vector<int>(t + 3, t + 7)); // 子片段5:7,9,1,3,6 bar.push_back(vector<int>(t + 4, t + 9)); // 子片段6:9,1,3,6,8,4 bar.push_back(vector<int>(t + 5, t + 11)); // 通过迭代器遍历list和vector,输出元素 for (auto list_it = bar.begin(); list_it != bar.end(); ++list_it) { for (auto vec_it = list_it->begin(); vec_it != list_it->end(); ++vec_it) { cout << *vec_it << " "; } } cout << endl; return 0; }
代码解释
- 数组转vector:利用
vector的构造函数vector<int>(起始指针, 结束指针),可以快速从数组的指定区间生成对应的vector,比如vector<int>(t, t+3)就会把数组t中从索引0到2的元素(共3个)存入vector。 - 存入list:使用
list的push_back方法,把每个生成的vector添加到list容器中。 - 迭代器遍历输出:外层迭代器遍历list中的每个vector,内层迭代器遍历当前vector中的每个元素,逐个输出并添加空格分隔。
运行这段代码后,就能得到你想要的输出:3 5 4 4 0 7 0 7 9 1 7 9 1 3 6 9 1 3 6 8 4。
内容的提问来源于stack exchange,提问作者grace1997
相关产品推荐
相关产品推荐

