对复数 C++ 进行排序

Sorting Complex Numbers c++

本文关键字:排序 C++      更新时间:2023-10-16

我试图获取用户输入的复数(3-8i 或 -1+5i),然后按与上述相同的格式按升序按实数排序,如果相同,则为虚数。

我首先要求用户输入一个复数或 ctr-d 来终止程序,然后排序。然后我想将字符串转换为浮点数。 一旦浮点,我想快速排序。 这是正确的方法吗?我知道我有很多错误。

void QuickSort(vector <float> &vec)
{
  quick_sort(vec, 0, vec.size() - 1);
}
void quick_sort (vector<float> &vec, float left, float right){
  float pivot, ltemp, rtemp;
  ltemp = left;
  rtemp = right;
  pivot = vec;
  while (left < right){
    while ((vec >= pivot) && (left < right)){
      right--;
    }
    if (left != right){
      vec = vec;
      left++;
    }
    while ((vec <=pivot) && (left < right)) {
      left++;
    }
    if (left != right){
      vec = vec;
      right--;
    }
    vec = pivot;
    pivot = left;
    left = ltemp;
    right = rtemp;
    if (left < pivot){
      quick_sort(vec, left, pivot -1);
    }
    if (left != right){
      vec = vec;
      left++;
    }
    while ((vec <=pivot) && (left < right)) {
      left++;
    }
    if (left != right){
      vec = vec;
      right--;
    }
    vec = pivot;
    pivot = left;
    left = ltemp;
    right = rtemp;
    if (left < pivot){
      quick_sort(vec, left, pivot -1);
    }
    if (right > pivot){
      quick_sort(vec, pivot +1, right);
    }
}
int main(){
  string user;
  vector <float> V;
  for (int y = 0; y < 5; y++)
  {
      cout << "Enter a complex number:" << endl;
      cin >> user >> test1;
      float usr = atof(user.c_str());
      V.push_back(usr);
  }
  QuickSort(V);
  for (int z = 0; z < V.size(); z++)
    cout << V[z] << endl;
  return 0;
}

下面是一个示例,说明如何解析一些复数,然后使用 C++ 标准库对它们进行排序。 如果你想作为一个学习练习,你可以一次替换一个部分 - 例如引入你自己的类型而不是std::complex,阅读一些其他输入格式(而不是括号中的逗号分隔的数字没有尾随的"i"),和/或使用你自己的排序。

#include <iostream>
#include <complex>
#include <vector>
#include <sstream>
#include <algorithm>
int main()
{
    std::istringstream iss("(1.0,-2.3)n"
                           "(1.0,1.2)n"
                           "(-2, 0)n"
                           "(0, 2)n");
    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 << 'n';
}

输出:

(-2,0)
(0,2)
(1,-2.3)
(1,1.2)

注意:我刚刚使用了一个std::istringstream,因此可以在程序中对输入进行硬编码以便于测试:如果您想从标准输入(默认为键盘)读取,只需更改为while (std::cin >> c)即可。

您可以在此处看到运行的代码