Vector sorting using BUbble sort C++ - c++

I need a simple program to accept string vector and sort using bubble sort and display the result. While executing the program automatically terminates.
#include<bits/stdc++.h>
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
vector<string> v2;
void Bsortchar(vector <string> &ch)
{
int i, j;
string temp[1][200];
int charLength = ch.size();
cout<<ch.size();
for(i = 0; i <= charLength; i++)
{
for (j=0; j < (charLength -1); j++)
{
if (ch[j+1] < ch[j])
{
temp[1][200] = ch[j];
ch[j] = ch[j+1];
ch[j+1]= temp[1][200];
}
}
}
return;
}
int main()
{
int charSize;
//**********************************************************
cout<<"Enter the Size of the char Vector"<<endl;
cin>>charSize;
cout<<"Enter the char Vector"<<endl;
string c;
for(int i=0;i<=charSize;i++)
{
cout<<i<<":";
getline(cin,c);
v2.push_back(c);
}
//************************************************************
Bsortchar(v2);
//***********************************************************
cout<<endl<<"The sorted character vector array is : "<<endl;
for(int i=0;i<=charSize;i++)
{
cout<<v2[i]<<" ";
}
//***********************************************************
return 0;
}
Need to accept string from the user and display the results after performing a bubble sort.

You have undefined behaviour temp[1][200] is off the ends of both parts of this (gratuitous) 2d array.
You don't need an array here, just a single temporary.
auto temp = ch[j];
ch[j] = ch[j+1];
ch[j+1]= temp;
Or, preferably, you can use an existing function
std::swap(ch[j], ch[j+i]);

Related

I want to store input in array. and print the array elements but cout line isn't working

I am new in programming,
basically in this program, it takes input from user and storing in array, 5 elements. After loop ends it should give the elements back but it seems that the last line is not working.
include<iostream>
using namespace std;
int main(){
int size=5;
string guess[size];
for (int i=0; i<size;i++){
cin>>guess[size];
}
cout<<guess[size];
return 0;
}
guess[size] is out of bounds. The last valid index in an array with size elements is size-1. Further, string guess[size]; is not valid C++ when size is not a constant expression. At the very least it should be const int size = 5;. You wrote a loop to take input and you also need a loop to print all elements.
This is the correct loop to read the input:
const int size=5;
std::string guess[size];
for (int i=0; i < size; i++){
std::cin >> guess[i];
}
You can modify it so that both input and output should use i as the loop subscript.
//cover #
#include<iostream>
using namespace std;
int main(){
int size=5;
string guess[size];
for (int i=0; i<size;i++){
cin>>guess[i];
}
for (int i = 0; i < size; ++i) {
cout<<guess[i];
}
return 0;
}
Use Range based Loops when You want to Print whole array, so you won't get an "Out-Of-Bounds" error. Because the Index in array are Zero Based Always remember the last index is (length_of_array - 1)
using namespace std;
int main()
{
int size = 5;
string guess[size];
for (int i=0; i<size;i++)
{
cin >> guess[i];
}
// range based loop
for (int i : guess)
{
cout << i << endl;
}
return 0;
}

C++ - Passing 2D array to function [duplicate]

This question already has answers here:
Passing a 2D array to a C++ function
(17 answers)
Variable length arrays (VLA) in C and C++
(5 answers)
Closed 3 months ago.
I am trying to pass a 2D array to a function but I am failing to do so. There is no problem with passing 1D array. How can I do this?
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
for (int j = 0; j < n; j++)
{
cout << matrix[j];
}
}
int main()
{
int n,m;
cin>>n;
//int matrix[n]={};
DisplayBoard(matrix,n);
return 0;
}
i think you want to input index number (n) from user and then input array object from user too
i complete your code like this :
#include <iostream>
using namespace std;
void DisplayBoard(int matrix[],int n) // Prints out the given array.
{
cout<<endl ;
for (int j = 0; j < n; j++)
{
cout << matrix[j]<<" ";
}
}
int main() {
int n,m;
cin>>n ;
int matrix[n];
for(int i=0;i<n;i++) {
cin>>matrix[i];
}
DisplayBoard(matrix,n);
return 0;
}
remember to declare array in main function too ,
that was one of your code error !
and this is incorrect to declare array :
int matrix[n]={} // incorrect !
Well. int matrix[n]={}; fills it with zeros and that's what I wanted to do. And my code with 1D array works fine but if I do it like so it does not.
#include <iostream>
using namespace std;
void DisplayMatrix(int matrix[][],int n,int m)
{
for(int i=0;i<n;i++)
{
for (int j = 0; j < m; j++)
{
cout << matrix[j];
}
}
}
int main()
{
int n,m;
cin>>n>>m;
int matrix[n][m]={};
DisplayMatrix(matrix,n,m);
return 0;
}

How to copy char array of a structure into another char array of a structure?

#include <iostream>
using namespace std;
struct stud
{
char name[10];
int id;
};
int input(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = ";
cin>>a[i].name;
cout<<"id = ";
cin>>a[i].id;
}
cout<<endl;
return 0;
}
int output(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = "<<a[i].name<<" ";
cout<<"id = "<<a[i].id<<" ";
}
cout<<endl;
return 0;
}
int copy(stud a[], stud x[], int size)
{
for(int i=1; i<=size; i++)
{
x[i].name=a[i].name;
x[i].id=a[i].id;
}
output(x,size);
cout<<endl;
return 0;
}
int main()
{
struct stud s[3], x[3];
input(s,3);
output(s,3);
copy(s,x,3);
return 0;
}
In this program the statement in function copy x[i].name =a[i].name; is not copying contents from 1 structure object to another. I have tried to put this statement in for loop for(int j=1;j<=10;j++) x[i].name[j] =a[i].name[j]; but still not working.
please suggest what should be changed or some alternatives for this.
i'll be very thankful to you for this.
regards,
umar
Either using a loop to copy each character in the name field or using thestrcpy function from <cstring> header works.
int copy(stud a[], stud x[], int size) {
for(int i = 1; i <= size; i++) {
// for(unsigned j = 0; j < 10; j++) {
// x[i].name[j] = a[i].name[j];
// }
strcpy(x[i].name, a[i].name);
x[i].id = a[i].id;
}
output(x, size);
cout << endl;
return 0;
}
But since you tagged this as c++, consider using std::string instead of a char array, unless you have a particular reason for using a char array. In that case x[i].name = a[i].name would have worked just fine and you could also use the standard algorithm library for copy. Also, using std::array instead of a raw C array for you "array of structures" might be a better option (does not degenerate into a pointer like a regular C array does).
Evrey single one of your loops is wrong, because in C++ arrays start at zero. So not
for(int i=1; i<=size; i++)
instead
for(int i=0; i<size; i++)
You cannot copy arrays by writing a = b;. Since your arrays are really strings there's a built in function strcpy to copy strings.
strcpy(x[i].name, a[i].name);
If you use = to copy struct, the char array inside that struct will be copied. You don't need to do anything more.
#include <iostream>
using namespace std;
typedef struct{
char name[10];
} type_t;
int main() {
type_t a = {"hihi"};
type_t b;
b = a;
a.name[0] = 'a';
cout<<a.name<<endl;
cout<<b.name<<endl;
return 0;
}
output:
aihi
hihi
ideone: https://ideone.com/Zk5YFd

allocation error in c++

I have this following code to sort number which I read from text file. My text file elements must be like this:
3 6
6
5
1
The first number (3) in the first column represents the number of elements that should I sort, the first number in second column represent the max number which I have to send via array which is 6 here.
And the number must be sorted is 6 5 1.
So this is my code but there is error says "invalid allocation size" and how to send max via array.
I need help please.
Here is my code:
// Read and Sort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std ;
#include<time.h>
#include <string>
int Max ;
int number_of_items;
const int s= 22;
int arr[s];
int n=sizeof(arr)/sizeof(*arr);
class sort{
public:
int read_file()
{
int num = 0;
int x ;
char filename[50];
ifstream numbersfile ;
cout<<"Please enter the file name below"<<endl<<"_______________________________________________"<<endl;
cin.getline(filename,50);
cout<<"_______________________________________________"<<endl;
numbersfile.open(filename);
if(numbersfile.is_open())
{
for(int i =0;i<n;i++){
numbersfile>>arr[i];
Max=arr[0];
number_of_items=arr[1];
}
}
else{
cout<<"Failed To load requierd file"<<endl;
}
int arr2[s];
cout<<"The elements supposed to be sorted are:"<<endl<<endl;
for(int i =2;i<n;i++){
numbersfile>>arr[i];
cout<<arr[i]<<" "<<endl;
}
counting_sort(arr2,n);
return 0 ;}
int counting_sort(int arr[],int size)
{
int n=size;
int max=arr[0];
for (int i=1;i<n;i++) {
if (arr[i]>max) {
max=arr[i];
}
}
int *output_array=new int[n];
for (int i=0;i<n;i++) {
output_array[i]=0;
}
int *count=new int[max+1];
for (int i=0;i<=max+1;i++) {
count[i]=0;
}
for (int i=0;i<n;i++){
count[arr[i]]=count[arr[i]]+1;
}
for (int i=1;i<max+1;i++) {
count[i]=count[i]+count[i-1];
}
for (int i=n-1;i>=1;i--) {
output_array[count[arr[i]]-1]=arr[i];
count[arr[i]]=count[arr[i]]-1;
}
cout<<"The sorted elements are:"<<endl<<endl;
for (int i=0;i<n;i++) {
cout<<output_array[i]<<" ";
}
cout<<"\n-----------------------------------------------"<<endl;
return 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
clock_t t1,t2;
t1=clock();
sort s1;
s1.read_file();
t2 = clock();
float diff = ((float)t2 - (float)t1)/1000 ;
cout <<"The time taken to execute this process is:\n"<< diff<<" Milliseconds." << endl;
return 0;
}
int *count=new int[max+1];
for (int i = 0; i <= max+1;i++) {
count[i]=0;
}
Note that here you goes out of range, because you try to access the last element as count[max+1], because the <= in the conditional test, and this position is not allocated. It should be like this:
int *count=new int[max+1];
for (int i = 0; i < max+1;i++) {
count[i]=0;
}
I suggest to you to carefully check each for, looking if you aren't accessing some position not bounded/allocated. Use printf's or cout's to debug, this is really useful.

Filling 2-D arrays from user input

I have a bit of a problem, I am writing a program to ask the user to enter numbers for a Sudoku grid, and then store them in a 2-d array. I know how to print out the array to show the Sudoku grid, But I am having trouble getting the array elements set to the numbers that the user enters, can anyone help?
This is all that I have, which I know is not much but I have only ever done this with 1-d arrays before.
Code:
#include <iostream>
using namespace std;
void fillGrid1(int grid1, int sizeOfArray) {
for(int x = 0; x < sizeOfArray; x++) {
grid1[x][9] = x;
}
}
int main()
{
int grid1[9][9];
fillGrid1(grid1, 9);
for(int row = 0; row < 9; row++) {
for(int column = 0; column < 9; column++) {
cout << grid1[row][column] << " ";
}
cout << endl;
}
}
Here you have two functions, one to interactively fill the hole sudoku by getting the user input. The other for printing the sudoku. With the little information you gave it's what I think you seek:
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
void interactiveSudokuFill(int grid1[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
string theString;
cout<<"Write the value to prace in Sudoku["<<y<<"]["<<x<<"] :"<<endl;
std::getline(cin,theString);
int nr=atoi(theString.c_str());
grid1[y][x]=nr;
}
}
}
void printSudoku(int grid[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
cout<<"["<<grid[y][x]<<"]";
}
cout<<endl;
}
}
int main()
{
int grid1[9][9];
interactiveSudokuFill(grid1);
printSudoku(grid1);
}
There are other more safe/elegant ways of doing this(for example user input should have been checked before delievering it to atoi()), but this way is the simpler I can think of.
Firstly, you're taking in an int where you expect an array:
void fillGrid1(int grid1, int sizeOfArray)
// ^^^^^^^^^
This should be something of the form,
void fillGrid1(int grid1[9][9], int sizeOfArray)
Next is that you should use a nested loop to access the elements of the multidimensional array:
void fillGrid1(int grid1[9][9], int sizeOfArray)
{
for (int i = 0; i < sizeOfArray; ++i)
{
for (int k = 0; k < sizeOfArray; ++k)
{
grid1[i][k] = x; // shouldn't x be the number the user entered?
}
}
}
You should also zero-fill your array:
int grid1[9][9] = {0};