Here's an example of how to parse some complex numbers then sort them using the C++ Standard Library. If you want to as a learning exercise, you can replace one part at a time - e.g. introduce your own type instead of std::complex
, read some other input format (rather than parenthesised comma-separated numbers sans a trailing "i"), and/or use your own sort.
#include <iostream>
#include <complex>
#include <vector>
#include <sstream>
#include <algorithm>
int main()
{
std::istringstream iss("(1.0,-2.3)
"
"(1.0,1.2)
"
"(-2, 0)
"
"(0, 2)
");
typedef std::complex<double> Complex;
std::vector<Complex> nums;
Complex c;
while (iss >> c)
nums.push_back(c);
std::sort(std::begin(nums), std::end(nums),
[](Complex x, Complex y)
{
return x.real() < y.real() ||
x.real() == y.real() && x.imag() < y.imag();
});
for (auto& c : nums)
std::cout << c << '
';
}
Output:
(-2,0)
(0,2)
(1,-2.3)
(1,1.2)
Note: I've just used a std::istringstream
so the input can be hard-coded in the program for easy testing: just change to while (std::cin >> c)
if you want to read from standard input (keyboard by default).
You can see the code running here
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…