Question

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) << "  ";
}
Was it helpful?

Solution 2

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

OTHER TIPS

Passing a vector to a function can be done like this:

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

You typically want to pass by (const) reference to avoid copying the vector.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top