I was doing a problem on LeetCode where I had to sort an input array and return output array such that sorted even numbers precede the sorted odd numbers. I wrote the following code:-
#include <iostream>
#include <vector>
#include <string.h>
#include "easy.h"
using namespace std;
int main()
{
vector<int> evenArray;
vector<int> oddArray;
string tempStr;
getline(cin, tempStr);
for (int i = 0; i < tempStr.length(); ++i){
// cout << tempStr[i] << endl;
if (isdigit(tempStr[i]) && (tempStr[i])%2==0){
//cout << "is even : " << tempStr[i] << endl;
evenArray.push_back((int)(tempStr[i]));
//printVector(evenArray);
//cout << "\n";
} else if (isdigit(tempStr[i]) && (tempStr[i])%2!=0){
//cout << "is odd : " << tempStr[i] << endl;
oddArray.push_back((int)(tempStr[i]));
//printVector(oddArray);
//cout << "\n";
}
}
for (int k = 0; k < oddArray.size(); ++k){
evenArray.push_back(oddArray[k]);
}
printVector(evenArray);
return 0;
}
I inputted the following 2 4 5 3 4
, expected {2 ,4, 4, 3, 5}
, instead got {50, 52, 52, 53, 51}
. Please note that the easy.h header file does no harm and I am only calling one function printVector()
from the header file. If in any case, you want the code for printVector():-
template <typename t> void printVector(vector<t> vec){
cout << "{";
for (int l = 0; l < vec.size(); ++l){
cout << vec[l] << ", ";
}
cout << "\b\b}";
}
Also, the comments made were used by me by the time of debugging the program. Any help or reference will be useful.