首页 > 解决方案 > 打印 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}}

标签: c++11for-loopiterationclang2d-vector

解决方案


这是我可以做到的:

#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 << "}";
}

推荐阅读