2013-06-06 23 views
1

我想使用ostream_iterator將對的向量寫入file.ostream_iterator需要在聲明時應用模板參數。 將載體原樣ostream_iterator的模板參數 - 每個元素都是對

vector<pair<string,long>> test; 

定義。當我通過對作爲模板的ostream_iterator它顯示了一個錯誤 -

錯誤1錯誤C2679:二進制「< <」:沒有操作員發現它需要一個'const std :: pair < _Ty1,_Ty2>'的右手操作數(或者沒有可接受的轉換)C:\ Program Files(x86)\ Microsoft Visual Studio 10.0 \ VC \ include \ iterator 531 1 wordsegmentation

在這種情況下,什麼可能是正確的論點?

編輯 - 代碼段

vector<pair<string,long>> t; 
...... 
//t is filled up with elements 
ostream_iterator<pair<string,long>> output_iterator(out, "\n"); 
std::copy(t.begin(), t.end(), output_iterator); 
+0

顯示您正在調用'ostream_iterator'的實際代碼。 – Yuushi

+0

[std :: copy to std :: cout for std :: pair]可能重複(http://stackoverflow.com/questions/634087/stdcopy-to-stdcout-for-stdpair) –

+0

可能的[Pretty-打印C + + STL容器](http://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers) – juanchopanza

回答

2

沒有operator <<std::pair。您不能簡單地使用ostream_iteratorstd::pair

您可以使用派生自pair或存儲pair的其他東西或書寫類並使用它。您不能在std名稱空間中編寫重載,因爲它會導致未定義的行爲,並且您不能在全局名稱空間中重載此運算符,因爲ADL找不到正確的重載(如果使用stl算法,如copy,ostream_iterator)。

簡單地說,像這樣將工作做好

#include <iostream> 
#include <utility> 
#include <algorithm> 
#include <iterator> 

int main() 
{ 
    std::vector<std::pair<int, int>> vec = 
    { 
     {1,1}, 
     {2,2} 
    }; 
    for (const auto& p : vec) 
    { 
     std::cout << p.first << " " << p.second << std::endl; 
    } 
} 
+0

如果我的每個元素都是矢量,我會得到相同的錯誤。你可以給這個文件寫一個這樣的變量的替代方案。我原本想把hashmap寫到一個文件中,但是這看起來更容易。謝謝 – code4fun

+0

@ code4fun向量沒有'operator <<'來。 – ForEveR

+0

謝謝。因此,我實際使用的是pair >。您認爲我應該如何存儲它,以便在讀取文件時能夠正確識別矢量。 – code4fun

1

你可以簡單地重載std::ostream& operator<<

std::ostream& operator<<(std::ostream& o, const pair<string,long>& p) 
{ 
    return o << p.first << " " << p.second; 
} 

或者看看pretty print C++ containers

相關問題