Comparing unsorted elements in two vectors - c++

I'm new to C++ and I'm trying to compare two unsorted vectors elements against each other and determining if they match or not.
for example:
1 4 9 16 9 7 4 9 11 and 11 11 7 9 16 4 1
these would be considered a match.
I've tried using firstVector == secondVector, but that does not work when they vectors are not sorted, I'm specifically trying to compared them while they are unsorted but am struggling.
int main() {
int incorrectMatches = 0;
int totalMatches = 0;
int input = 0;
vector <int> firstVector;
vector <int> secondVector;
do {
cout << "Please enter a number for first vector: ";
cin >> input;
firstVector.push_back(input);
cout << endl;
}
while (input > 0);
input = 0;
firstVector.pop_back();
do {
cout << "Please enter a number for second vector: ";
cin >> input;
secondVector.push_back(input);
cout << endl;
}
while (input > 0);
secondVector.pop_back();
for (int loop = 0; loop < firstVector.size(); loop++) {
cout << firstVector[loop] << " ";
}
cout << endl;
for (int loop = 0; loop < secondVector.size(); loop++) {
cout << secondVector[loop] << " ";
}
cout << endl;
int vectorSize = firstVector.size();
for (int i = 0; i < vectorSize; i++) {
if (firstVector[i] == secondVector[i]) {
totalMatches = totalMatches++;
}
else {
incorrectMatches = incorrectMatches++;
}
}
cout << "There were " << totalMatches << " matches." << endl;
cout << "There were " << incorrectMatches << " incorrect matches";
/*
if (firstVector == secondVector) {
cout << "Your vectors match!";
}
else{
cout << "Your vectors don't match!";
}
*/
/*
for (int i = 0; i < input; i++) {
cout << "Please enter a number (1-9): ";
myVector.push_back(input);
cout << endl;
myVector[i] = i;
cout << "Vector entry: " << myVector[i] << endl;
}
*/
system("pause");
return 0;}

As duplicates shall not matter, you could simply insert the elements of the vectors in a separate std::set, respectively, and then compare the sets using operator ==. I think the use of sets expresses the intent of your program best:
int main() {
vector<int> v1 = { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
vector<int> v2 = { 11, 11, 7, 9, 16, 4, 1 };
set<int> s1;
s1.insert(v1.begin(), v1.end());
set<int> s2;
s2.insert(v2.begin(), v2.end());
bool isEqual = (s1 == s2);
cout << "v1 and v2 are " << (isEqual ? "" : "not ") << "equal." << endl;
return 0;
}

Related

Even and odd sorting arrays

I can't get the following program to sort 'orig', 'even', and 'odd' arrays in ascending order.
The code seems fine to me, but it doesn't sort correctly at all, it will separate the array into the original even and odd lists, but the order is random and not in ascending order at all.
The output should look something like this:
Input up to 50 integers. Use a negative number to stop.
The list will be sorted into odd and even values.
Input an integer: 15
Input an integer: 8
Input an integer: 22
Input an integer: 4
Input an integer: 77
Input an integer: 19
Input an integer: 2
Input an integer: -1
Orig Even Odd
2 2 15
4 4 19
8 8 77
15 22
19
22
77
#include<iostream>
#include<iomanip>
using namespace std;
void DataIn(int Max[], int List[][50]);
void Separate(int Max[], int List[][50]);
int Lowest(int start, int N, int Vector[]);
void Sort(int Max[], int List[][50]);
void DataOut(int Max[], int List[][50]);
int main()
{
//Index: 0 = input, 1 = even, 2 = odd
int Max[3] = { 0, 0, 0 };
int List[3][50];
cout << "Input up to 50 integers. Use a negative number to stop.\n";
cout << "The list will be sorted into odd and even values.\n\n";
DataIn(Max, List);
Separate(Max, List);
Sort(Max, List);
DataOut(Max, List);
}
void DataIn(int Max[], int List[][50])
{
cout << "Input an integer: ";
cin >> List[0][Max[0]];
while (List[0][Max[0]] > 0)
{
cout << "Input an integer: ";
cin >> List[0][++Max[0]];
}
return;
}
void Separate(int Max[], int List[][50])
{
int n, type;
for (n = 0; n < Max[0]; ++n)
{
if ((List[0][n] % 2) == 0)
type = 1;
else
type = 2;
List[type][Max[type]++] = List[0][n];
}
return;
}
int Lowest(int start, int N, int Vector[])
{
int i, low = start;
for (i = start + 1; i < N; i++)
if (Vector[i] < Vector[low])
low = i;
return (low);
}
void Sort(int Max[], int List[][50])
{
int i, j, k, l;
double origSort,evenSort,oddSort;
for (i = 0; i < Max[0] - 1; ++i)
{
j = Lowest(i, Max[0], List[50]);
origSort = List[0][i];
List[0][i] = List[0][j];
List[0][j] = origSort;
k = Lowest(i, Max[1], List[50]);
evenSort = List[1][i];
List[1][i] = List[1][k];
List[1][k] = evenSort;
l = Lowest(i, Max[2], List[50]);
oddSort = List[2][i];
List[2][i] = List[2][l];
List[2][l] = oddSort;
}
}
void DataOut(int Max[], int List[][50])
{
int i;
int orig = 0, even = 1, odd = 2;
cout << "\n\n";
cout << setw(10) << "Orig" << setw(10) << "Even" << setw(10) << "Odd" << "\n\n";
for (i = 0;i < Max[0];i++)
{
if(List[0][i]>0)
cout << setw(10) << List[orig][i];
else
cout << setw(10) << " ";
if (List[1][i] > 0)
cout << setw(10) << List[even][i];
else
cout << setw(10) << " ";
if (List[2][i] > 0)
cout << setw(10) << List[odd][i] << "\n";
else
cout << "\n";
}
}
You have overcomplicated yourself too much with a two dimensional array and whatever int Max[3] is.
Things are simple: sort the original vector, then filter the odds and evens. Since you filter after you sort, the two resulting vectors will already be sorted.
Here's the C++20 solution:
int main()
{
using namespace std::ranges::views;
std::vector<int> v{15, 8, 22, 4, 77, 19, 2};
std::ranges::sort(v);
auto evens = v | filter([] (int a) { return a % 2 == 0; });
auto odds = v | filter([] (int a) { return a % 2 != 0; });
for (auto e : v)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : evens)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : odds)
std::cout << e << " ";
std::cout << std::endl;
}
You don't even need the variables to store the ranges. You can do the filter in the output loop if you want:
for (auto e : v | filter([] (int a) { return a % 2 == 0; }))
std::cout << e << " ";
std::cout << std::endl
And here's the non-ranges solution:
int main()
{
std::vector<int> v{15, 8, 22, 4, 77, 19, 2};
std::vector<int> evens;
std::vector<int> odds;
std::sort(v.begin(), v.end());
std::copy_if(v.begin(), v.end(), std::back_inserter(evens),
[] (int a) { return a % 2 == 0; });
std::copy_if(v.begin(), v.end(), std::back_inserter(odds),
[] (int a) { return a % 2 != 0; });
for (auto e : v)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : evens)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : odds)
std::cout << e << " ";
std::cout << std::endl;
}
If you for whatever reason don't want to use the standard library algorithms you must at least use the standard containers. Ditch the C arrays. And implement the solution following the same logic: sort then filter.

How to make an output file of n*n matrix,by taking n from the user, with the numbers generated in pairs?

Currently I have a pre-made 6X6 matrix in a text file like this:
2 6 3 1 0 4
4 2 7 7 2 8
4 7 3 2 5 1
7 6 5 1 1 0
8 4 6 0 0 6
1 3 1 8 3 8
and I made a code that is reading from a file i have made. However I want to have user make a grid for themselves (i.e. 3X3 or 10X10). Which then writes to a text file automatically like in similar fashion and then have that read-in instead. It is a basic memory match card game, so I need to have rand() which generates equal pair so the game can be over when every pair in the grid has been found. Thank you so much for your time!
/*Here are the snippets of my code*/
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <fstream>
#include <string>
#include <numeric>
#include <limits>
using namespace std;
//global 2d vectors that are associated with the game
vector<vector<int> > game_grid;
vector<vector<int> > hidden_grid;
vector <vector<int> > guessed;
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
for (int i = 0; i < 6; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < 6; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
return;
}
void print_grid() {
cout << "Game grid" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
cout << game_grid[i][j] << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
}
void print_hidden_grid(int r1 = -1, int r2 = -1, int c1 = -1, int c2 = -1) {
cout << "Attempt:" << endl;
if (r1 != -1) {
hidden_grid[r1][c1] = game_grid[r1][c1];
}
if (r2 != -1) {
hidden_grid[r2][c2] = game_grid[r2][c2];
}
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
if (r1 != -1) {
if (game_grid[r1][c1] == game_grid[r2][c2]) {
guessed[r1][c1] = 1;
guessed[r2][c2] = 1;
cout << "You have a match!" << endl << endl;
}
else {
hidden_grid[r1][c1] = -1;
hidden_grid[r2][c2] = -1;
}
}
cout << endl << endl;
}
void print_current_grid() {
cout << "Current Grid:" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl << endl;
}
.......
If I well understand you want to auto detect the size of the matrix when you read it ? If yes you can do something like that in initialize_grid :
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
// detect size
int size = 0;
string line;
if (!getline(input_file, line))
return;
istringstream iss(line);
while (iss >> num)
size += 1;
input_file.clear();
input_file.seekg(0);
for (int i = 0; i < size; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < size; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
}
and else where you replace 6 by game_grid.size() (using size_t rather than int to type the indexes)

Converting String to vector of Integers

FizzBuzz program. The user enters numbers separated by a comma. The program reads input and lets the computer know if divisible by 3, 5 or both. When the user enters 15,5,30, the program will only output the first number, 15 and stops there. What am I doing wrong?
void processVector(vector<int> intVector)
{
bool loop;
for (int i = 0; i < intVector.size(); i++)
{
loop = true;
}
}
int main()
{
cout << "Welcome to the FizzBuzz program!" << endl;
cout << "This program will check if the number you enter is divisable by
3, 5, or both." << endl;
cout << "Please enter an array of numbers separated by a comma like so,
5,10,15" << endl;
cin >> userArray;
vector<int> loadVector(string inputString);
istringstream iss(userArray);
vector <int> v;
int i;
while (iss >> i);
{
v.push_back(i);
if (iss.peek() == ',')
iss.ignore();
if (i % 15 == 0)
{
cout << "Number " << i << " - FizzBuzz!" << endl;
}
else if (i % 3 == 0)
{
cout << "Number " << i << " Fizz!" << endl;
}
else if (i % 5 == 0)
{
cout << "Number " << i << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
system("pause");
}
Here is how I would approach the problem:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "!!!Hello World!!!" << std::endl; // prints !!!Hello World!!!
std::cout << "Please enter your numbers seperated by a comma (5, 3, 5, 98, 278, 42): ";
std::string userString;
std::getline(std::cin, userString);
std::vector<int> numberV;
size_t j = 0; // beginning of number
for(size_t i = 0; i < userString.size(); i++){
if((userString[i] == ',') || (i == userString.size() -1)){ // could also use strncmp
numberV.push_back(std::stoi(userString.substr(j, i))); // stoi stands for string to int, and .substr(start, end) creates a new string at the start location and ending at the end location
j = i + 1;
}
}
for(size_t n = 0; n < numberV.size(); n++){
std::cout << numberV[n] << std::endl;
}
return(0);
}
This should give you a method to solve the problem (without handling the fizzbuzz part of your program) that I personally find simpler.
The basic form for using functions is:
<return type> <function_name(<inputs)>{
stuff
};
So, a basic function that takes a string and returns a vector (what you are wanting) would be:
std::vector myStringToVector(std::string inputString){
std::vector V;
// your code (see the prior example for one method of doing this)
return(V);
};
It also looks like they want a separate function for outputting your vector values, this could look something like:
void myVectorPrint(std::vector inputVector){
// your code (see prior example for a method of printing out a vector)
};
Thank you #Aaron for the help. Here is the finished code and it works great!
I had to take a little more time researching a few things and trying to understand which order and what to put where in terms of the functions and how to call them. I appreciate all the help as I said I am a noob.
#include "stdafx.h"
#include <iostream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;
vector<int> loadVector(string inputString)
{
stringstream ss(inputString);
vector <int> numberV;
int n;
size_t j = 0; // beginning of number
for (size_t n = 0; n < inputString.size(); n++)
{
if ((inputString[n] == ',') || (n == inputString.size() - 1))
{
numberV.push_back(std::stoi(inputString.substr(j, n)));
j = n + 1;
}
}
return numberV;
}
void processVector(vector<int> intVector)
{
for (int i = 0; i < intVector.size(); i++)
{
int n = intVector.at(i);
if (n % 15 == 0)
{
cout << "Number " << n << " - FizzBuzz!" << endl;
}
else if (n % 3 == 0)
{
cout << "Number " << n << " Fizz!" << endl;
}
else if (n % 5 == 0)
{
cout << "Number " << n << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
}
int main()
{
cout << "Welcome to the FizzBuzz program." << endl
<< "Please enter an array of numbers separated by comma's (5, 10, 15)"
<< endl;
string inputString;
getline(cin, inputString);
try
{
vector<int> intVector = loadVector(inputString);
processVector(intVector);
}
catch (const exception& e)
{
cout << "Exception caught: '" << e.what() << "'!;" << endl;
}
system("pause");
return 0;
}

Need help on getting the smallest three numbers on an array

For this program a user must enter 10 contestants and the amount of second it took for them to complete a swimming race. My problem is that I must output the 1st, 2nd and 3rd placers, so I need to get the three smallest arrays (as they would be the quickest times) but I'm unsure on how to do it. Here is my code so far.
string names[10] = {};
int times[10] = { 0 };
int num[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int min1 = 0, min2 = 0, min3 = 0;
cout << "\n\n\tCrawl";
for (int i = 0; i < 10; i++)
{
cout << "\n\n\tPlease enter the name of contestant number " << num[i] << ": ";
cin >> names[i];
cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
cin >> times[i];
while (!cin)
{
cout << "\n\tError! Please enter a valid time: ";
cin.clear();
cin.ignore();
cin >> times[i];
}
if (times[i] < times[min1])
min1 = i;
cout << "\n\n\t----------------------------------------------------------------------";
}
system("cls");
cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
cout << "\n\n\t1st Place - " << names[min1];
cout << "\n\n\t2nd Place - " << names[min2];
cout << "\n\n\t3rd Place - " << names[min3];
}
_getch();
return 0;
}
As you can see, it is incomplete. I know how to get the smallest number, but its the second and third smallest that is giving me trouble.
your code is full of errors:
what do you do with min2 and min3 as long as you don't assign them?? they are always 0
try checking: cout << min2 << " " << min3;
also you don't initialize an array of strings like that.
why you use an array of integers for just printing number of input:
num? instead you can use i inside loop adding to it 1 each time
to solve your problem use a good way so consider using structs/clusses:
struct Athlete
{
std::string name;
int time;
};
int main()
{
Athlete theAthletes[10];
for(int i(0); i < 10; i++)
{
std::cout << "name: ";
std::getline(std::cin, theAthletes[i].name);
std::cin.sync(); // flushing the input buffer
std::cout << "time: ";
std::cin >> theAthletes[i].time;
std::cin.sync(); // flushing the input buffer
}
// sorting athletes by smaller time
for(i = 0; i < 10; i++)
for(int j(i + 1); j < 10; j++)
if(theAthletes[i].time > theAthletes[j].time)
{
Athlete tmp = theAthletes[i];
theAthletes[i] = theAthletes[j];
theAthletes[j] = tmp;
}
// printing the first three athletes
std::cout << "the first three athelets:\n\n";
std::cout << theAthletes[0].name << " : " << theAthletes[0].time << std::endl;
std::cout << theAthletes[1].name << " : " << theAthletes[1].time << std::endl;
std::cout << theAthletes[2].name << " : " << theAthletes[2].time << std::endl;
return 0;
}
I hope this will give u the expected output. But i suggest u to use some sorting alogirthms like bubble sort,quick sort etc.
#include <iostream>
#include<string>
using namespace std;
int main() {
int times[10] = { 0 };
int num[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int min1 = 0, min2 = 0, min3 = 0,m;
string names[10] ;
cout << "\n\n\tCrawl";
for (int i = 0; i < 10; i++)
{
cout << "\n\n\tPlease enter the name of contestant number " << num[i] << ": ";
cin >> names[i];
cout << names[i];
cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
cin >> times[i];
cout<<times[i];
while (!cin)
{
cout << "\n\tError! Please enter a valid time: ";
cin.clear();
cin.ignore();
cin >> times[i];
}
if(times[i]==times[min1]){
if(times[min1]==times[min2]){
min3=i;
}else{min2 =i;}
}else if(times[i]==times[min2]){
min3=i;
}
if (times[i] < times[min1]){
min1 = i;
cout <<i;
}
int j=0;
while(j<i){
if((times[j]>times[min1])&&(times[j]<times[min2])){
min2 =j;
j++;
}
j++;
}
m=0;
while(m<i){
if((times[m]>times[min2])&&(times[m]<times[min3])){
min3 =m;
m++;
}
m++;
}
cout << "\n\n\t----------------------------------------------------------------------";
}
cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
cout << "\n\n\t1st Place - " << names[min1];
cout << "\n\n\t2nd Place - " << names[min2];
cout << "\n\n\t3rd Place - " << names[min3];
return 0;
}
There is actually an algorithm in the standard library that does exactly what you need: std::partial_sort. Like others have pointed out before, to use it you need to put all the participant data into a single struct, though.
So start by defining a struct that contains all relevant data. Since it seems to me that you only use the number of the contestants in order to be able to later find the name to the swimmer with the fastest time, I'd get rid of it. Of course you could also add it back in if you like.
struct Swimmer {
int time;
std::string name;
};
Since you know that there always will be exactly 10 participants in a race, you can also go ahead and replace the C-style array by a std::array.
The code to read in the users then could look like this:
std::array<Swimmer, 10> participants;
for (auto& participant : participants) {
std::cout << "\n\n\tPlease enter the name of the next contestant: ";
std::cin >> participant.name;
std::cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
while(true) {
if (std::cin >> participant.time) {
break;
}
std::cout << "\n\tError! Please enter a valid time: ";
std::cin.clear();
std::cin.ignore();
}
std::cout << "\n\n\t----------------------------------------------------------------------";
}
Partial sorting is now essentially a one-liner:
std::partial_sort(std::begin(participants),
std::begin(participants) + 3,
std::end(participants),
[] (auto const& p1, auto const& p2) { return p1.time < p2.time; });
Finally you can simply output the names of the first three participants in the array:
std::cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
std::cout << "\n\n\t1st Place - " << participants[0].name;
std::cout << "\n\n\t2nd Place - " << participants[1].name;
std::cout << "\n\n\t3rd Place - " << participants[2].name << std::endl;
The full working code can be found on coliru.
This is not a full solution to your problem, but just meant to point you into the right direction...
#include <iostream>
#include <limits>
#include <algorithm>
using namespace std;
template <int N>
struct RememberNsmallest {
int a[N];
RememberNsmallest() { std::fill_n(a,N,std::numeric_limits<int>::max()); }
void operator()(int x){
int smallerThan = -1;
for (int i=0;i<N;i++){
if (x < a[i]) { smallerThan = i; break;}
}
if (smallerThan == -1) return;
for (int i=N-1;i>smallerThan;i--){ a[i] = a[i-1]; }
a[smallerThan] = x;
}
};
int main() {
int a[] = { 3, 5, 123, 0 ,-123, 1000};
RememberNsmallest<3> rns;
rns = std::for_each(a,a+6,rns);
std::cout << rns.a[0] << " " << rns.a[1] << " " << rns.a[2] << std::endl;
// your code goes here
return 0;
}
This will print
-123 0 3
As you need to know also the names for the best times, you should use a
struct TimeAndName {
int time;
std::string name;
}
And change the above functor to take a TimeAndName instead of the int and make it also remember the names... or come up with a different solution ;), but in any case you should use a struct similar to TimeAndName.
As your array is rather small, you could even consider to use a std::vector<TimeAndName> and sort it via std::sort by using your custom TimeAndName::operator<.

Why is my function not working properly

My function that checks if numbers in the vector are even or odd doesn't work properly.
This function prints the numbers that i have typed in the vector and puts them in 2 categories EVENS/ODDS. But if i have a negative number there is a problem with the odds not printing it but evens work.
problematic code is here:
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1) // Here is the problem.
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
Or more exactly this line: if (new_v1.at(i) % 2 == 1)
It prints the numbers that are odd but only the positive ones not the negative ones.
But if i change it to if (new_v1.at(i) % 2 != 0) then it works correctly.
Why does that happen and is there a problem with the equal operator?
If yes then why are the evens getting printed even if they are negatives while still using the equal operator?
Code here for reference.
clude <iostream>
#include <vector>
using namespace std;
void fillVector(vector <int>&);
void printVector(const vector <int>&);
void printEvensAndOddsVector(const vector <int>&); // Prints Evens and Odds.
int main()
{
vector <int> v1;
fillVector(v1);
printVector(v1);
printEvensAndOddsVector(v1);
cout << "\n\n\n";
system( "pause");
return 0;
}
// Function Definitions
void fillVector(vector <int>& new_v1)
{
int number;
cout << "Type in numbers and type -100 to stop: ";
cin >> number;
while (number != -100)
{
new_v1.push_back(number);
cin >> number;
}
}
void printVector(const vector <int>& new_v1)
{
cout << "\nVector: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
cout << new_v1.at(i) << " ";
}
cout << " \n";
}
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
This line: if (new_v1.at(i) % 2 == 1). It prints the numbers that are odd but only the positive ones not the negative ones.
For negative n, n % 2 returns either 0 or -1 in C++. It never returns 1, so the condition cannot be true for negative inputs.
As you've discovered, comparing to zero would work.
See Modulo operator with negative values