2011-06-20 121 views
15

我有一個大的矢量。如何將矢量值寫入文件

我使用的方法使程序的運行時間大大增加。首先是將所有值寫入字符串,因爲它們使用stringstreams進行計算,稍後將字符串寫入文件。另一種方法是在事實之後創建一個長字符串並將其寫入文件。但是,這兩者都非常緩慢。

有沒有辦法只是用換行符將矢量的值立即寫入文本文件?

+2

「有隻寫向量的值到文本文件的方式立即沒有換行符?「 - 你需要有或沒有換行符? – Ajay

+1

它讓我很高興看到我的程序完成了之前在5分鐘內完成了3小時的任務XD – TimeCoder

回答

33

使用std::ofstreamstd::ostream_iteratorstd::copy()是通常的做法。下面是使用C++語法98 std::string個例子(這個問題是問前C++ 11):

#include <fstream> 
#include <iterator> 
#include <string> 
#include <vector> 

int main() 
{ 
    std::vector<std::string> example; 
    example.push_back("this"); 
    example.push_back("is"); 
    example.push_back("a"); 
    example.push_back("test"); 

    std::ofstream output_file("./example.txt"); 
    std::ostream_iterator<std::string> output_iterator(output_file, "\n"); 
    std::copy(example.begin(), example.end(), output_iterator); 
} 
+2

你應該小心使用一個字符串作爲例子。由於加載字符串矢量的反面是不同的(它是輸出/輸入不同的唯一標準類型)。 –

+11

你寫了「問題被問到C++ 11以前的版本」 - 有沒有其他方式用C++ 11來做到這一點? – Default

4

也許我錯過了一些東西,但什麼是錯的:

std::ofstream f("somefile.txt"); 
for(vector<X>::const_iterator i = v.begin(); i != v.end(); ++i) { 
    f << *i << '\n'; 
} 
這避免了不得不做的潛在二次字符串連接,這一點我認爲是什麼殺死你的運行時

+0

對不起,v和X代表什麼? – TimeCoder

+0

'v'是你的載體。 「X」是其中包含的類型。 – Johnsyweb

6
#include <fstream> 
#include <vector> 
#include <string> 

int main() 
{ 
    std::vector<std::string> v{ "one", "two", "three" }; 
    std::ofstream outFile("my_file.txt"); 
    // the important part 
    for (const auto &e : v) outFile << e << "\n"; 
}