c++数组写文件

作用, 用于代码自测

#include <iostream>
#include <utility>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>

#include <fstream>

using namespace std;

// 直接调试去掉下面的注释, 然后把 dir改成绝对路径
#define TEST

#ifdef TEST
// 修改这里可以改成绝对路径用 ide 直接调试
string dir = "/Users/nichao/Code/c++/untitled1/";
string inputFile = dir + "input.txt";
string outputFile = dir + "output.txt";
string expectFile = dir + "expect.txt";

ifstream in(inputFile);
ofstream out(outputFile);

ifstream output(outputFile);
ifstream expect(expectFile);

string emptyStr = "nullptr";

template<typename T, typename ...Args>
auto has_begin(int) -> decltype(declval<T>().begin(declval<Args>...), true_type{});

template<typename T, typename ...Args>
false_type has_begin(...);

template<typename T, typename ...Args>
using beginable = typename std::is_same<decltype(has_begin<T>(0)), true_type>::type;


// 用于实现了 operator<<的对象
template<typename Obj, typename = typename enable_if<
        !is_same<
                true_type,
                beginable<
                        typename decay<Obj>::type
                >
        >::value
>::type
>
auto writeToFile(Obj &&r, bool end = true, bool last = true) -> decltype(void(out.operator<<(r))) {
    out << r;
    if (!last) {
        out << ",";
    }
    if (end) {
        out << endl;
    }
}

// 容器都有 begin 方法
template<typename Container>
auto writeToFile(Container &&c, bool end = true, bool last = true) -> decltype(void(c.begin())) {
    out << "[";
    for (int i = 0; i < c.size() - 1; i++) {
        writeToFile(c[i], false, false);
    }
    writeToFile(c.back(), false);
    out << "]";
    if (!last) {
        out << ",";
    }
    if (end) {
        out << endl;
    }
}

// 用于数值退化成指针的情况
template<typename Arr, size_t N>
void writeToFile(Arr &&r, int n) {
    for (int i = 0; i < n; ++i) {
        out << r[n] << ",";
    }
    out << endl;
}

#else
istream &in = cin;
ostream &out = cout;
#endif


#ifdef TEST

///  ===============测试代码=============================

void oneTest() {
    vector<int> data = {1, 2, 3};
    writeToFile(data);
}

void twoTest() {
    vector<vector<int>> data= {{1,2,3},{4,5,6},{7,8,9}};
    writeToFile(data);
}

void threeTest() {
    vector<vector<vector<int>>> data= {{{1,2,3},{4,5,6},{7,8,9}}};
    writeToFile(data);
}

int main() {
    oneTest();
    twoTest();
    threeTest();
}
#endi

输出

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值