2013-05-05 107 views
0

我希望有人可以提供一些有關特定問題的見解。我正在編寫一個程序,它採用整數,將它們存儲在一個向量中,並用逗號分隔符將它們打印出來,數字大於999 - > 1,000。重載<<並定義一個流操作器C++

我的問題是..好吧,其實兩個,我怎樣才能傳遞一個矢量到一個函數,第二,如果我想超載的所有這些在幕後將是可能的嗎?

從類逗號

全局函數:

template <class T> 
string formatWithComma(T value){ 
    stringstream ss; 
    locale commaLoc(locale(), new CommaNumPunc()); 
    ss.imbue(commaLoc); 
    ss << value; 
    return ss.str(); 

環在main()顯示矢量:

for (vector<unsigned int>::iterator i = integers.begin(); i != integers.end(); ++i){ 
    cout << formatWithComma(*i) << " "; 
} 
+0

你不需要編寫自定義'locale'有逗號分隔的數字,' num_punct'應該用','作爲分隔符,'3'作爲數字分組 – 2013-05-05 23:28:21

回答

1

第一個問題:

如何傳遞載體的功能

只需直接通過。例如(假定函數模板):

template <typename T> 
void processVector(const vector<T>& vec); 

內部主,您可以按以下稱之爲:

processVector<unsigned int> (integers); //an example instantiation 

第二個問題:

,如果我想超載< <到在幕後做這一切會是可能的嗎?

是的,當然可以。看看如何從這些資源超負荷<<操作: MSDN Overload << operatorOverload the << operator WISC

和SO一堆資源:How to properly overload << operator

2

傳遞一個矢量到一個函數可以這樣來完成:

void foo(std::vector<T> &vector); 
void foo(const std::vector<T> &vector); 

您通常需要傳遞(const)引用以避免複製向量。