Algorithm for arranging values in ascending order - c++

I am currently making a piece of code that reads in up to 20 integers, assigns them to a vector, then arranges them in ascending order. I have everything, but I can not figure out how to arrange them in ascending order.
#include <iostream.h>
#include "apvector.h"
void DisplayVector(int intOutputLoop, int intInputLoop, apvector<int> numbers);
void BuildVector(int &intInputLoop, apvector<int> &numbers);
void BuildVector(int &intInputLoop, apvector<int> &numbers)
{
int intInput;
do
{
if (!(cin >> intInput))
{
cout << "Please Enter A Numeric Value" << endl;
cin.clear();
cin.ignore(1000000, '\n');
}
else
{
if (intInput == 666)
break;
else
{
numbers[intInputLoop] = intInput;
intInputLoop = intInputLoop + 1;
}
}
}
while (intInputLoop < 20);
}
void DisplayVector(int intOutputLoop, int intInputLoop, apvector<int> numbers)
{
}
int main()
{
apvector<int> numbers(20);
int intInputLoop = 0;
int intOutputLoop = 0;
BuildVector(intInputLoop, numbers);
DisplayVector(intOutputLoop, intInputLoop, numbers);
}

I solved the issue with the following:
std::sort (numbers.begin(), numbers.end());
for (std::vector<int>::iterator order = numbers.begin(); order != numbers.end(); ++order)
{
if (*order != 0)
std::cout << ' ' << *order;
}

Related

Struct doesn't print with cout

I'm trying to print the structure in an array whose int prejetih member is highest.
#include <iostream>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(Tekma tekme[]) {
int maksi = 0, index = 0;
for (int i = 0;i < 2;i++) {
if (maksi < tekme[i].prejetih) {
index = i;
maksi = tekme[i].prejetih;
}
}
return tekme[index];
}
void vpis(Tekma tekme[]) {
for (int i = 0;i < 2;i++)
cin >> tekme[i].prejetih;
}
int main() {
Tekma tekme[2];
vpis(tekme);
cout << najvec_kosev(tekme);
}
The compiler reports
C++ no operator matches these operands
operand types are: std::ostream << Tekma
over cout << najvec_kosev(tekme);
Here using a solution with std::vector and fixing your cout problem:
#include <iostream>
#include <vector>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(vector<Tekma>& tekme) {
Tekma lowest = tekme[0]
for(auto& t : tekme) {
if(lowest.prejetih < t.prejetih) {
lowest = t;
}
}
return lowest ;
}
void vpis(vector<Tekma>& tekme) {
int input;
while(true) {
cin >> input;
// Check if the input is valid else quit the loop.
if(input == valid) {
Tekma newStruct = {input};
tekme.push(newStruct);
}
else {
// Stop the loop
break;
}
}
}
int main() {
vector<Tekma> tekme;
vpis(tekme);
cout << najvec_kosev(tekme).prejetih; // This fixes your error.
}

Part of the char array?

I got a task in which I receive babies' firstname and weight in kilogram in a character array (for example: Johnny, 2 kg). I must store them in an array that can hold maximum 1000 elements and must be a struct type, storing the baby's firstname and weight.
Every actions must be done in functions - however, when I tried to get the name until the comma, str.copy() didn't work for me. Its specific problem was something with the last parameter, the position. Could someone help me out with that? Also, I'm kinda new to C++ and imagining how to separately, in two functions ask in the char arrays until empty line and do the copying in the other... if someone could help me out, I'd be grateful for that ^^'
Thanks for the help in advance!
#include<iostream>
#include<string>
#define M 1000
struct baby{
std::string baby_name;
float weight;
};
int readIn(baby* baby_datapair, int max);
// int maxWeight(baby* baby_datapair);
// int minWeight(baby* baby_datapair);
// void descendingOrder(baby* baby_datapair, int num);
int main(){
baby baby_array[M];
int n = readIn(baby_array, M);
return 0;
}
int readIn(baby* baby_datapair, int max){
int n = 0;
char name[12];
while (n < max){
std::cout << "Baby" << n+1 << "'s datas (Nickname, weight in kg): ";
std::getline(std::cin, name);
//~ std::cin.ignore(1);
if (neve == ""){
std::cout << "Wrong input!\n";
break;
}else{
std::size_t pos = name.find(',');
std::size_t until = name.copy(baby_datapair[n].baby_name, 0, pos);
}
n++;
}
return n;
}
// int maxWeight(baby* baby_datapair){
// }
// int minWeight(baby* baby_datapair){
// }
// void descendingOrder(baby* baby_datapair, int num){
// }
You must use std::string name; instead of char name[12]; as std::getline 's parameter. BTW, It make better for memory management. After input data, check pos value for valid value.
#include<iostream>
#include<string>
#define M 1000
struct baby {
std::string baby_name;
float weight;
};
int readIn(baby* baby_datapair, int max);
// int maxWeight(baby* baby_datapair);
// int minWeight(baby* baby_datapair);
// void descendingOrder(baby* baby_datapair, int num);
int main() {
baby baby_array[M];
int n = readIn(baby_array, M);
return 0;
}
int readIn(baby* baby_datapair, int max) {
int n = 0;
//char name[12];
std::string name;
while (n < max) {
std::cout << "Baby" << n + 1 << "'s datas (Nickname, weight in kg): ";
std::getline(std::cin, name);
//~ std::cin.ignore(1);
if (name == "") {
std::cout << "Wrong input!\n";
break;
}
else {
std::size_t pos = name.find(',');
if (pos <= 0) {
std::cout << "Invalid input structure!\n";
continue;
}
//std::size_t until = name.copy(baby_datapair[n].baby_name, 0, pos);
baby_datapair[n].baby_name = name.substr(0, pos);
baby_datapair[n].weight =(float)atof(name.substr(pos+1).c_str());
//std::cout << std::endl;
//std::cout << baby_datapair[n].baby_name;
//std::cout << ", " << baby_datapair[n].weight;
}
n++;
}
return n;
}
// int maxWeight(baby* baby_datapair){
// }
// int minWeight(baby* baby_datapair){
// }
// void descendingOrder(baby* baby_datapair, int num){
// }
You are taking it the wrong size. You should not try to copy to, but just copy from. BTW, name must be a std::string for you program to compile, and you should check for possible end of file. So a minally fixed version could be:
std::string name;
while (n < max) {
std::cout << "Baby" << n + 1 << "'s datas (Nickname, weight in kg): ";
std::getline(std::cin, name);
//~ std::cin.ignore(1);
if ((! std::cin) || name == "") {
std::cout << "Wrong input!\n";
break;
}
else {
std::size_t pos = name.find(',');
baby_datapair[n].baby_name = std::string(name.c_str(), pos);
baby_datapair[n].weight = strtof(name.c_str() + pos + 1, nullptr);
}
But using a std::stringstream would be more idiomatic in C++. Above code is rather C-ish...

Tried making a hash table, can't map all keys, also program crashes

I have to make a program with a hash table that maps single random characters into the table. The program kind of works but sometimes it crashes, also it doesn't map every element. Some of them just won't get inside the table and there are always spare spaces in the table. I don't know what to do to solve these 2 problems. I used 3 versions of open adressing and each of them causes the same 2 problems. Sorry for my bad English. Thank you in advance.
Edited. Of course, I forgot about dynamic allocation. But the problem isn't solved.
#include <time.h>
#include <string>
#include <cstdlib>
using namespace std;
int Liniowo(int i, int proby, int rozmiar) // (open adressing, Linear probing)
{
if(i+proby<rozmiar)
return i+proby;
else
{
return -1;
}
}
int Kwadratowo(int i, int proby, int rozmiar) // (open adressing, Quadratic probing)
{
if (i+proby*proby<rozmiar)
return i+proby*proby;
else
{
return -1;
}
}
int Podwojnie(int i, int proby, int rozmiar, char klucz) // (open adressing, Double hashing)
{
if (i*(klucz*(701%klucz)-klucz%13)<rozmiar&&i*(klucz*(701%klucz)-klucz%13)>0)
return i*(klucz*(701%klucz)-klucz%13);
else
{
return -1;
}
}
int modularnie(char c,int rozmiar) // modular
{
return c%rozmiar;
}
void dodaj(char *tab,int max, char c) // add an element
{
int i=modularnie(c, max);
if (tab[i]== '\0')
tab[i]=c;
else
{
int u=0;
int h;
while (tab[i]!= '\0'&&h!=-1)
{
u++;
// h=Kwadratowo(i, u, max);
h=Podwojnie(i,u,max,c);
}
if (h!=-1)
tab[h]=c;
else
cout << "no niestety, nie udalo sie wstawic " <<endl; //"I couldn't map the element"
}
}
int wyszukaj(char *tab,int max, char c) // search an element
{
int i=modularnie(c, max);
int j=i;
if (tab[i]== '\0')
return -1;
while (tab[i]==c)
{
i=(i+1)%max;
if((i==j)||(tab[i]== '\0'))
return -1;
}
return i;
}
int usun(char *tab,int max, char c) // remove an element
{
int r,j,i=wyszukaj(tab,max,c);
j=i;
if (i==-1)
return -1;
tab[i]= '\0';
while (tab[(++i)%max]!= '\0')
{
i%=max;
r=modularnie(tab[i],max);
if (((i<r)&&(r<=j)) || ((r<=j)&&(j<i)) || ((j<i)&&(i<r)))
{
tab[j]=tab[i];
tab[i]= '\0';
j=i;
continue;
}
}
return 0;
}
int main()
{
srand( time( NULL ) );
int ile;
cout << "podaj wielkosc tablicy: "; //"Type the size of the table"
cin >> ile;
char* tab; // EDITED
tab=new char(ile);
for (int n=0; n<ile; n++)
{
tab[n]= '\0';
}
char e;
for (int i=0; i<ile; i++)
{
e='!'+rand()%127;
dodaj(tab, ile, e);
}
for(int j=0; j<ile; j++)
{
cout << j << ", " << tab[j] << endl;
}
return 0;
}

Why do I get stuck in an infinite loop after calling a function?

I'm supposed to make a function that receives two arguments: a sentence(std::string) and bunch of phrases(std::vector<std::string>>). Now for all words in a sentence that are contained in the vector, I need to make their palindrome, and stick them together, e.g. compile -> compileelipmoc.
I also need to make sure that input is available up until two ENTER's are pressed.
The problem occurs after calling the function, where I seem to get stuck in an infinite loop.
Why am I getting this infinite loop?
#include <iostream>
#include <vector>
#include <string>
typedef std::vector<std::string> Vektor;
typedef std::string String;
void ReverseString(String &s1)
{
char temp(0);
for(int i(0); i < s1.size()/2; i++) {
temp = s1.at(i);
s1.at(i) = s1.at(s1.length()-1-i);
s1.at(s1.length()-1-i) = temp;
}
}
void CreatePalindrome(String s, Vektor v)
{
bool white_space(true);
bool go_on(false);
String compare;
for(int i(0); i < s.size(); i++) {
for(;;) {
if(s.at(i) == '\n' || i == s.size()-1) {
go_on == true;
break;
}
compare+=s.at(i);
}
if(go_on) {
for(int j(0); j < v.size(); j++) {
if(compare == v.at(j)) {
ReverseString(v.at(j));
if(i != s.size()-1) v.at(j)+=' ';
s.insert(i, v.at(j));
}
}
}
compare.clear();
}
}
int main ()
{
String sentence, phrase;
Vektor v1;
char character(0);
std::cout << "Enter your sentence: ";
std::getline(std::cin, sentence);
std::cout << "Enter phrases: ";
for(;;) {
character = std::cin.get();
if(character == '\n') break;
for(;;) {
phrase.push_back(character);
character = std::cin.get();
if(character == '\n') break;
}
v1.push_back(phrase);
phrase.clear();
}
CreatePalindrome(sentence, v1);
std::cout << "After the transformation, the sentence is: " << sentence;
return 0;
}
for(;;) {
if(s.at(i) == '\n' || i == s.size()-1) {
go_on == true;
break;
}
compare+=s.at(i);
}
Your only way out is via that if, but you modify neither s nor i in the loop, so you'll never break!

Error with strcoll (C++)

I want to sort a vector of strings into order alphabetically. I have coded thus far and I can not resolve the error for strcoll. Also, I am not allowed to use algorithm library. The error can be seen in the bubbub function where I am trying to bubble sort.
I have a few functions that should explain themselves with their names
#include <iostream>
#include <string.h>
#include <vector>
#include <stdio.h>
using namespace std;
inline void swap(string & a, string & b)
{
string c = b;
b = a;
a = c;
return;
}
void input_name(string&);
void sort_names(string&);
void repeat_pro(int&);
void sortArray(string, int);
void print_names(vector<string>& b_list);
void bubbub(vector<string> & b_list);
int main() {
vector<string> b_list;
string name;
int choice;
int count=0;
cout << "Welcome to the Business Sorting Program!" << endl;
do{
input_name(name);
b_list.push_back(name);
count++;
repeat_pro(choice);
bubbub(b_list);
cout<<"\n \n Your Businesses are:"<<endl;
for(int i=0; i < b_list.size() ; i++){
cout<<b_list[i]<<"\n";
}
cout << "\n\n";
}while(choice == 0);
cout << "Thanks for using this program"<<endl;
return 0;
}
void input_name(string &name){
cout << "Enter in the name of the business: ";
getline(cin, name);
}
void sort_names(string &name){
}
void repeat_pro(int &choice){
cout << "Do you want to enter in more names: ";
string answ;
cin>>answ;
cin.ignore(1000,'\n');
for (int x=0; x<answ.size(); x++){
answ[x] = tolower(answ[x]);
}
if (answ == "yes" || answ == "y"){
choice = 0;
}
else {
choice = 1;
}
}
void bubbub(vector<string> & b_list)
{
vector<string>::size_type loop = 0;
bool done = false;
while ((loop+1 < b_list.size()) && ! done)
{
done = true;
for (vector<string>::size_type count = 0;
count+1 != b_list.size(); count++)
{
string x;
string z;
x = b_list[count];
z= b_list[count+1];
if ( strcoll (x,z) < 0 )
{
swap( b_list[count], b_list[count+1] ); // swap
done = false;
}
}
loop++;
}
return;
}
I fixed it by converting my string into a list of chars. then compared them and swapped the vector based on the results. Thanks for the help guys
void bubbub(vector<string> & b_list)
{
vector<string>::size_type loop = 0;
bool done = false;
while ((loop+1 < b_list.size()) && ! done)
{
done = true;
for (vector<string>::size_type count = 0;
count+1 != b_list.size(); count++)
{
string x;
string z;
char array[50];
char array2[50];
x = b_list[count];
z= b_list[count+1];
strncpy(array, x.c_str(), sizeof(x));
strncpy(array2, z.c_str(), sizeof(z));
if ( strcoll (array,array2) > 0 )
{
swap(b_list[count+1], b_list[count] ); // swap
done = false;
}
}
loop++;
}
return;
}
You can use std::string::compare instead of strcoll
#include <iostream>
#include <vector>
#include <stdio.h>
#include <cstring>
using namespace std;
inline void swap(string & a, string & b)
{
string c = b;
b = a;
a = c;
return;
}
void input_name(string&);
void sort_names(string&);
void repeat_pro(int&);
void sortArray(string, int);
void print_names(vector<string>& b_list);
void bubbub(vector<string> & b_list);
int main() {
vector<string> b_list;
string name;
int choice;
int count=0;
cout << "Welcome to the Business Sorting Program!" << endl;
do{
input_name(name);
b_list.push_back(name);
count++;
repeat_pro(choice);
bubbub(b_list);
cout<<"\n \n Your Businesses are:"<<endl;
for(int i=0; i < b_list.size() ; i++){
cout<<b_list[i]<<"\n";
}
cout << "\n\n";
}while(choice == 0);
cout << "Thanks for using this program"<<endl;
return 0;
}
void input_name(string &name){
cout << "Enter in the name of the business: ";
getline(cin, name);
}
void sort_names(string &name){
}
void repeat_pro(int &choice){
cout << "Do you want to enter in more names: ";
string answ;
cin>>answ;
cin.ignore(1000,'\n');
for (int x=0; x<answ.size(); x++){
answ[x] = tolower(answ[x]);
}
if (answ == "yes" || answ == "y"){
choice = 0;
}
else {
choice = 1;
}
}
void bubbub(vector<string> & b_list)
{
vector<string>::size_type loop = 0;
bool done = false;
while ((loop+1 < b_list.size()) && ! done)
{
done = true;
for (vector<string>::size_type count = 0;
count+1 != b_list.size(); count++)
{
string x;
string z;
x = b_list[count];
z = b_list[count+1];
if (z.compare(x) != 0 )
{
swap( b_list[count], b_list[count+1] ); // swap
done = false;
}
}
loop++;
}
return;
}
Output
Welcome to the Business Sorting Program!
Enter in the name of the business: hello
Do you want to enter in more names: yes
Your Businesses are:
hello
Enter in the name of the business: apple
Do you want to enter in more names: no
Your Businesses are:
apple
hello
Thanks for using this program
Program ended with exit code: 0