Change the output format of a complex number

A template exists in the C ++ standard library complex<>, and it has an overloaded <<so that it displays complex numbers in the format (real_part, im_part). I need to change the behavior of this operator for complex numbers so that the output format is changed to something completely different. In particular, I need a conclusion in the form real_part\tim_part. How to do it?

+5
source share
4 answers

There is no direct way to replace operator <<, but you have several options. First, you can simply write your own function to print complex numbers:

template <typename T> void PrintComplex(const complex<T>& c) {
    /* ... */
}

nice stream, , , - , complex, operator <<, . :

template <typename T> class ComplexPrinter {
public:
    /* Conversion constructor allows for implicit conversions from
     * complex<T> to ComplexPrinter<T>.
     */
    ComplexPrinter(const complex<T>& value) : c(value) {
        // Handled in initializer list
    }

    /* Output the complex in your own format. */
    friend ostream& operator<< (ostream& out, const ComplexPrinter& cp) {
        /* ... print in your own format ... */
    }

private:
    complex<T> c;
};

-

cout << ComplexPrinter<double>(myComplex) << endl;

, , , :

template <typename T>
ComplexPrinter<T> wrap(const complex<T>& c) {
    return ComplexPrinter<T>(c);
}

cout << wrap(myComplex) << endl;

, .

, , complex<T> ComplexPrinter<T> s. , vector< complex<T> >, , ,

vector< complex<double> > v = /* ... */
copy (v.begin(), v.end(), ostream_iterator< ComplexPrinter<double> >(cout, " "));

complex<double> , .

, , complex, :

template <typename T> class ComplexPrinter {
public:
    /* Conversion constructor allows for implicit conversions from
     * complex<T> to ComplexPrinter<T>.
     */
    ComplexPrinter(const complex<T>& value) : c(value) {
        // Handled in initializer list
    }

    /* Output the complex in your own format. */
    friend ostream& operator<< (ostream& out, const ComplexPrinter& cp) {
        /* ... print in your own format ... */
    }

private:
    const complex<T>& c;
};

complex. ( ). , , , , , , .

, !

+7
template<class T>
struct my_complex_format_type {
  std::complex<T> const &x;
  my_complex_format_type(std::complex<T> const &x) : x (x) {}
  friend std::ostream& operator<<(std::ostream &out,
                                  my_complex_format_type const &value)
  {
    out << "format value.x however you like";
    return out;
  }
};
template<class T>
my_complex_format_type<T> my_complex_format(std::complex<T> const &x) {
  return x;
}

void example() {
  std::cout << my_complex_format(some_complex);
}
+3

complex<T>, typedef (boost ) < < . < .

< < complex<T> .

+1

. , iostreams - , C-like. , , , .

-1

All Articles