怎么遍历自嵌套的vector输出它的元素?
本帖最后由 微光拼图 于 2022-11-28 00:34 编辑vector<vector<int>> generate(int numRows)
{
if(numRows<=0)
{
return {};
}
if(numRows==1)
{
return{{1}};
}
if(numRows==2)
{
return{{1},{1,1}};
}
vector<vector<int>> res={{1},{1,1}};
vector<int> arr;
int row=1;
while(row < numRows - 1)
{
arr.push_back(1);
for(int i=0;i<res.size()-1;i++)
{
int temp=0;
temp=res+res;
arr.push_back(temp);
}
arr.push_back(1);
res.push_back(arr);
arr.clear();
row++;
}
return res;
} 已解决
for (int i = 0; i < res.size(); i++)
{
for(int j = 0; j < res.size(); j++)
cout << res << " ";
cout << endl;
} sh-5.1$ cat main.cpp
#include <iostream>
#include <vector>
using std::cout, std::endl;
using std::ostream;
using std::vector;
ostream &operator<<(ostream &os, const vector<int> &v) {
for(const auto &i: v) os << i << " ";
return os;
}
ostream &operator<<(ostream &os, const vector<vector<int>> &v) {
bool flag = false;
for(const auto &i: v) {
if(flag) os << endl;
flag = true;
os << i;
}
return os;
}
int main() {
vector<vector<int>> v = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {2, 5, 8}};
cout << v << endl;
return 0;
}
sh-5.1$ g++ -g -Wall -o main main.cpp
sh-5.1$ ./main
1 2 3
4 5 6
7 8 9
2 5 8
sh-5.1$
微光拼图 发表于 2022-11-28 01:08
已解决
#include <iostream>
#include <vector>
using std::vector;
using std::cout, std::endl;
int main(void) {
vector <vector <int>> arr{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
for (auto ver : arr) {
for (int num : ver) {
cout << num << " ";
}
cout << endl;
}
return 0;
}
页:
[1]