【问题标题】:overloading the << and defining a stream manipulator c++重载 << 并定义流操纵器 C++
【发布时间】:2013-05-05 23:15:16
【问题描述】:

我希望有人可以就我遇到的特定问题提供一些见解。我正在编写一个程序,它接收整数,将它们存储在一个向量中,并用逗号分隔符将它们打印出来,用于大于 999 -> 1,000 的数字。

我的问题是.. 嗯,实际上有两个,我如何将向量传递给函数,第二,如果我想重载

来自逗号类的全局函数:

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) << "  ";
}

【问题讨论】:

  • 你不需要写一个自定义的locale来用逗号分隔数字,num_punct应该用,作为分隔符,3作为数字分组

标签: c++ vector operator-overloading manipulators


【解决方案1】:

将向量传递给函数可以这样完成:

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

您通常希望通过 (const) 引用来避免复制向量。

【讨论】:

    【解决方案2】:

    第一个问题:

    如何将向量传递给函数

    直接传就行了。例如(假设函数模板):

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

    在main里面,可以这样调用:

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

    第二个问题:

    如果我想重载

    是的,当然可以。查看如何从这些资源中重载 &lt;&lt; 运算符: MSDN Overload << operatorOverload the << operator WISC

    还有来自 SO 的一堆资源:How to properly overload << operator

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 2022-01-05
      • 2010-10-06
      • 1970-01-01
      相关资源
      最近更新 更多