Search code examples
c++vectoroperator-overloadingmanipulators

overloading the << and defining a stream manipulator c++


I am hoping someone could offer some insight on a particular problem im having. I am writing a program that takes in integers, stores them in a vector, and prints them out with comma separators for numbers larger than 999 -> 1,000.

My question is.. well, two actually, how can i pass a vector to a function, and second, if i wanted to overload the << to do all this behind the scenes would that be possible?

global function from a class Comma:

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

loop in main() to display the vector:

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

Solution

  • First question:

    how can i pass a vector to a function

    Just pass it directly. For example(assume function template):

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

    Inside main, you can call it as follows:

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

    Second question:

    if i wanted to overload the << to do all this behind the scenes would that be possible?

    Yes, of course possible. see how to overload << operator from those resources: MSDN Overload << operator and Overload the << operator WISC

    and a bunch of resource from SO: How to properly overload << operator