c++11 - 打印 2d Vector 结果的内容而不将每个标记索引为一个
问题描述
我试图以与初始化相同的方式打印出二维向量的内容。
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<vector<int > > frontier = {{-1,0}, {1,0}, {0,-1}, {0,1}};
for (int i = 0; i < frontier.size(); i++) {
for (int j = 0; j < frontier[i].size(); j++) {
std::cout << frontier[i][j] << ", ";
}
}
cout << "End of frontier. " << endl;
/* This below is an implementation that I found online but found
no
* way to be able to implement the column reference.
*/
for (int i = 0; i < frontier.size(); ++i) {
for (int j = 0; j < col; ++j) {
cout << frontier[i + j * col] << ' ';
}
cout << endl;
}
}
这是为了确定二维向量的内容。到目前为止,这段代码可以打印出用逗号分隔的每个索引。另一方面,我需要编写代码来表示新向量的开始位置。
输出:
-1, 0, 1, 0, 0, -1, 0, 1,
预期输出:
{{-1,0}, {1,0}, {0,-1}, {0,1}}
解决方案
这是我可以做到的:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::vector<int>> frontier = { {-1,0}, {1,0}, {0,-1}, {0,1} };
std::string outerPrefix = "";
std::cout << "{";
for(const auto& outer : frontier)
{
std::cout << outerPrefix << "{";
std::string innerPrefix = "";
for(auto inner : outer)
{
std::cout << innerPrefix << inner;
innerPrefix = ",";
}
std::cout << "}";
outerPrefix = ", ";
}
std::cout << "}";
}
输出:{{-1,0}, {1,0}, {0,-1}, {0,1}}
在第一个示例中,我使用了基于范围的 for 循环。如果您熟悉foreach
许多语言中的概念,则基本上是相同的。如果您不需要实际的索引变量,它会更安全,因为您不必担心被 1 关闭并在容器外部进行索引。它在容器上的工作方式也相同,map
或者set
您需要使用迭代器而不是索引的地方。
如果你对嵌套索引循环做同样的事情,就像你原来的那样,它可能看起来像这样:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::vector<int>> frontier = { {-1,0}, {1,0}, {0,-1}, {0,1} };
std::cout << "{";
for(size_t outer = 0; outer < frontier.size(); ++outer)
{
if (outer != 0)
{
std::cout << ", ";
}
std::cout << "{";
for(size_t inner = 0; inner < frontier[outer].size(); ++inner)
{
if (inner != 0)
{
std::cout << ",";
}
std::cout << inner;
}
std::cout << "}";
}
std::cout << "}";
}
推荐阅读
- django - Heroku - 设置 Procfile 以运行 Django 命令来创建数据库
- c - 是否有将 Racket 编译为 C 的编译器?
- android - ProGuard 错误:文件 'C:\...\proguard.txt' 第 16 行中的未知选项 '-if'
- php - 如何创建时间范围列表?
- java - Intellij IDEA 无法识别 java 文件:目录中有蓝色方块
- php - 在 URL 中插入引号
- python - 如何从 Excel 工作表中的单元格中删除或忽略控制字符 \r 或“”?
- mql5 - 编写止损处理程序
- sql-server - 如何在 SQL 连接字符串中使用 Azure KeyVault 机密?
- docker - Docker 错误:服务“应用程序”构建失败