I made this program for taking in input in two vectors ( long long int considering the fact that the numbers can be really large that a normal int cannot accomodate ) and then I wish to sort them.
#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; } When I see the output of the vectors after sorting, it is not correct. For eg for the input as : 2 1 3 7 8 9 ( for the two vectors ), it shows the output as, 000 987. Why is this happening? I think that the sort function is not functioning properly. But I did sorting after
ifstatement in the functions? You can just as well writereturn first.foo < second.foo;vector<A> values1(1000)- what does this do?n? How is it declared`How is it initialized?2 1 37 8 9". Really? You created two vectors of1000elements each, all elements initialized to0. Then you set some of these elements (3 in each vector apparently) to some non-zero values, leaving remaining 997 elements as zeros. And then you sorted the vectors. Why do you find it surprising that those 997 zeros drifted to the beginning of the vector after sorting in ascending order?nis not declared.