使用 Gecode 打印到文件

Printing to file using Gecode

本文关键字:文件 打印 Gecode 使用      更新时间:2023-10-16

我正在做一个 Gecode 项目,代码应该输出一个如下所示的文件:

n: 17
x: {0, 0, 16, 18, 17, 31, 32, 0, 34, 10, 30, 37, 38, 30, 30, 10}
y: {0, 27, 28, 14, 0, 31, 20, 17, 11, 17, 0, 0, 6, 7, 11, 25}
s: 43
runtime: 0.137
failure: 127

以上是代码应输出的示例。我尝试执行以下代码:

virtual void
print(std::ostream& os) const {
    string filename = "project1-t15-n" + n + ".txt";
    ofstream myfile;
    myfile.open (filename);
    myfile << "n: " << n << std::endl;
    myfile << "x: {";
    for (int i = 0; i < x.size(); i++) {
        if (i != 0) {
            myfile << ", ";
        }
        myfile << x[i];
    }
    myfile << "}" << std::endl;
    myfile << "y: {";
    for (int i = 0; i < y.size(); i++) {
        if (i != 0) {
            myfile << ", ";
        }
        myfile << y[i];
    }
    myfile << "}" << std::endl;
    myfile << "s: " << s << std::endl;
    //???????????????????????????????? print runtime and failures
    myfile.close();
}

我知道 n、s、x 和 y 是正确的,但我有两个问题:

1:打印到文件时print(std::ostream& os) const正确的用法吗?

2:如何从 Gecode 输出中获取运行时和故障?他们的内置打印功能就是这样做的。

myfile << "s: " << s << std::endl;

在你的代码中没有看到任何s,它是什么?此外,打印方法的签名表明它已经获取了输出流。这是真的吗?谁叫它,从哪里来,用什么论点?如果其他方法确实调用 print 并为其提供输出流,那么您可能应该使用它,而不是创建自己的方法。

更新:查看了 Gecode 的文档,找到了定义 print() 的地方:

http://www.gecode.org/doc-latest/reference/driver_8hh_source.html#l00666

因此,您可以在自己的类中重新定义此方法,该方法源自 ScriptBase(我想这就是您应该为 Gecode 编写内容的方式),但您应该使用提供的参数,即:

    virtual void
    print(std::ostream& os) const {
        os << "n: " << n << std::endl;
        os << "x: {";
// etc

实际打印到特定文件 I/O 控制台的一个选项是简单地使用重新路由的输出运行程序。 例如,如果您的程序称为myprogram,而您的文件称为myfile.txt,请按以下方式运行它:

myprogram >> myfile.txt

它会将所有内容打印到文件而不是控制台。

另外,就文档(http://www.gecode.org/doc-latest/MPG.pdf)而言,如果您有 ScriptBase 派生的类 S,您可以直接从 main() 方法调用其方法 S->print(),并在那里提供正确的文件流,即:

S* s= new S; // something like that
ofstream f("myfile.txt");
s->print(f);
...