首页主机资讯如何使用C++处理网格数据的输入输出

如何使用C++处理网格数据的输入输出

时间2024-09-14 18:14:05发布访客分类主机资讯浏览1395
导读:在C++中处理网格数据的输入输出,通常需要使用二维数组或者std::vector 读取网格数据: #include<iostream> #include <fstream> #include<vector&...

在C++中处理网格数据的输入输出,通常需要使用二维数组或者std::vector

  1. 读取网格数据:
#include<
    iostream>
    
#include <
    fstream>
    
#include<
    vector>


int main() {
    
    std::ifstream input_file("grid_data.txt");
    
    int rows, cols;
    
    input_file >
    >
     rows >
    >
     cols;
    

    std::vector<
    std::vector<
    int>
    >
     grid(rows, std::vector<
    int>
    (cols));
    

    for (int i = 0;
     i<
     rows;
 ++i) {
    
        for (int j = 0;
     j<
     cols;
 ++j) {
    
            input_file >
    >
     grid[i][j];

        }

    }
    

    input_file.close();
    

    // 处理网格数据...

    return 0;

}
    
  1. 写入网格数据:
#include<
    iostream>
    
#include <
    fstream>
    
#include<
    vector>


int main() {
    
    int rows = 3, cols = 4;
    
    std::vector<
    std::vector<
    int>
    >
 grid = {

        {
1, 2, 3, 4}
,
        {
5, 6, 7, 8}
,
        {
9, 10, 11, 12}

    }
    ;
    

    std::ofstream output_file("grid_data_output.txt");
    
    output_file<
    <
     rows <
    <
     " "<
    <
     cols <
    <
     "\n";
    

    for (int i = 0;
     i<
     rows;
 ++i) {
    
        for (int j = 0;
     j<
     cols;
 ++j) {
    
            output_file<
    <
     grid[i][j] <
    <
     " ";

        }
    
        output_file <
    <
     "\n";

    }
    

    output_file.close();
    

    return 0;

}
    

这两个示例分别展示了如何从文件中读取网格数据以及将网格数据写入文件。你可以根据实际需求对这些代码进行修改和扩展。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 如何使用C++处理网格数据的输入输出
本文地址: https://pptw.com/jishu/699303.html
C++中网格的搜索和遍历技巧 C++中网格的可视化展示方法

游客 回复需填写必要信息