对复数 C++ 进行排序
Sorting Complex Numbers c++
我试图获取用户输入的复数(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)
即可。
您可以在此处看到运行的代码
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 如何在C++中对数组进行冒泡排序