簡體   English   中英

使用Gecode打印到文件

[英]Printing to file using Gecode

我正在做一個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,則可以直接從中調用其方法S-> print()您的main()方法,並在那里提供正確的文件流,即:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM