我制作了这个程序,用于输入两个向量的输入(long long int考虑到数字可能非常大而普通的int无法容纳的事实)然后我希望对它们进行排序。
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
bool myfunct1( A first, A second );
bool myfunct2( A first, A second );
class A
{
public:
long long int foo;
};
int main (void)
{
vector<A> values1(1000);
vector<A> values2(1000);
int temp1 = 0;
int temp2 = 0;
int faltu;
while (temp1<n)
{
cin>>faltu;
values1[temp1].foo = faltu;
temp1++;
}
while (temp2<n)
{
cin>>faltu;
values2[temp2].foo = faltu;
temp2++;
}
sort(values1.begin(), values1.end(),&myfunct1); // Sorting the elements in ascending order
sort(values2.begin(), values2.end(),&myfunct2); // Sorting in descending order
for ( i = 0; i < n; i++ )
printf("%lld",values1[i].foo);
printf("\n");
for ( i = 0; i < n; i++ )
printf("%lld",values2[i].foo);
printf("\n");
}
bool myfunct1( A first, A second )
{
if ( first.foo < second.foo )
return true;
else
return false;
}
bool myfunct2( A first, A second )
{
if ( first.foo > second.foo )
return true;
else
return false;
}
当我在排序后看到向量的输出时,它是不正确的。例如输入为:
2 1 3
7 8 9
(对于两个向量),它将输出显示为000
987
。为什么会这样?
我认为sort函数运行不正常。但我在
答案 0 :(得分:3)
第一个向量打印000的原因可能是因为你初始化了1000个初始值的向量,这可能默认为0.我不是100%肯定这个,但第二个排序的工作原因是因为最大的数字放在第一位。在第一种情况下,在1,2,3之前有997 0。我建议的是(如果你的n是3),只用3初始化向量并进行测试。
另外,IDK为什么要初始化你的向量以立即拥有1000个A类元素,但你也可以尝试通过不用任何元素初始化向量并在其上使用push_back方法来测试你的程序和排序函数插入变量。
你的语法完全没问题,排序应该没有问题。