I'm writing a program that has a user input integers into an array, calls a function that removes duplicates from that array, and then prints out the modified array. When I run it, it lets me input values into the array, but then gives me a "Segmentation fault" error message when I'm done inputing values. What am I doing wrong?
Here is my code:
#include <iostream>
using namespace std;
void rmDup(int array[], int& size)
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i];
size--;
}
}
}
}
int main()
{
const int CAPACITY = 100;
int values[CAPACITY], currentSize = 0, input;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
while (cin >> input)
{
if (currentSize < CAPACITY)
{
values[currentSize] = input;
currentSize++;
}
}
rmDup(values, currentSize);
for (int k = 0; k < currentSize; k++)
{
cout << values[k];
}
return 0;
}
Thank you.
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i]; /* WRONG! array[-1] = something */
size--;
}
}
}
If array[0] and array[1] are equal, array[0-1] = array[0], meaning that array[-1] = array[0]. You are not supposed to access array[-1].
I wouldn't make it even possible to create duplicates:
int main()
{
const int CAPACITY = 100;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
std::set<int> myInts;
int input;
while (std::cin >> input && input != 'q' && myInts.size() <= CAPACITY) //note: 113 stops the loop, too!
myInts.insert(input);
std::cout << "Count: " << myInts.size();
}
And do yourself a favour and don't use raw arrays. Check out the STL.
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
vector<int> vec = {1,1,2,3,3,4,4,5,6,6};
auto it = vec.begin();
while(it != vec.end())
{
it = adjacent_find(vec.begin(),vec.end());
if(it != vec.end())
vec.erase(it);
continue;
}
for_each(vec.begin(),vec.end(),[](const int elem){cout << elem;});
return 0;
}
This code compiles with C++11.
#include<iostream>
#include<stdio.h>
using namespace std;
int arr[10];
int n;
void RemoveDuplicates(int arr[]);
void Print(int arr[]);
int main()
{
cout<<"enter size of an array"<<endl;
cin>>n;
cout<<"enter array elements:-"<<endl;
for(int i=0;i<n ;i++)
{
cin>>arr[i];
}
RemoveDuplicates(arr);
Print(arr);
}
void RemoveDuplicates(int arr[])
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;)
{
if(arr[i]==arr[j])
{
for(int k=j;k<n;k++)
{
arr[k]=arr[k+1];
}
n--;
}
else
j++;
}
}
}
void Print(int arr[])
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}
Related
As you see in my code, I have to return an array through return function. What necessary thing do I have to change in my code to disable the warning of return type? When I run this code, it gives me a warning. I have to remove this warning:
warning: no return statement in function returning non-void [-Wreturn-type]
#include <bits/stdc++.h>
using namespace std;
int sort(int a[], int n)
{
int zeros = 0;
for (int i = 0; i < n; i++)
{
if (a[i] == 0)
{
zeros++;
}
}
int k = 0;
while (zeros--)
{
a[k++] = 0;
}
while (k < n)
{
a[k++] = 1;
}
}
int main()
{
int n;
cout << "Enter the n value : ";
cin >> n;
int a[n];
cout << "Enter the array elements : ";
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a, n);
for (int i = 0; i < n; i++)
{
cout << a[i];
}
return 0;
}
int sort(int a[], int n)
Your sort function is declared to return an int, but you didn't return anything. If you don't want to return anything, declare it using void.
Also, VLA is not valid C++. You should use std::vector instead.
So, your code should look like this.
#include <iostream>
#include <vector>
void sort(std::vector<int> &a) // no need for n
{
int zeros = 0;
for (int i = 0; i < a.size(); i++) // use member function size() instead for n
{
if (a[i] == 0)
{
zeros++;
}
}
int k = 0;
while (zeros--)
{
a[k++] = 0;
}
while (k < n)
{
a[k++] = 1;
}
}
int main()
{
int n;
std::cout << "Enter the n value : ";
std::cin >> n;
std::vector<int> a(n);
std::cout << "Enter the array elements : ";
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a);
for (cons auto &i : a) // range-base for loop, recommend
{
std::cout << a[i];
}
return 0;
}
Note: using namespace std; and #include <bits/stdc++.h> are both bad practice, so avoid using it.
I've been stuck on this problem for a pretty Long while. I always get "Time limit exceeded" when I submit the code.
My solution is to input the items of the array then determine the largest number in the array and diplay it along with the elements following it and so on.
How can I make my algorithm more efficient?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int T, n;
cin >> T;
while (T--) {
//inputting p[n]
scanf_s("%d", &n);
int* p = new int[n];
for (int i = 0; i < n; i++) {
scanf_s("%d", &p[i]);
}
while (n != 0) {
//*itr = largest element in the array
auto itr = find(p, p + n, *max_element(p, p + n));
int index = distance(p, itr);
for (int i = index; i < n; i++) {
printf("%d\n", p[i]);
}
//deleting element by decreasing n:
n = index;
}
delete[] p;
}
return 0;
}
You solution is O(n^2), too slow.
A O(n) solution is obtained by iteratively calculating the position of the max element until a given index i.
#include <iostream>
#include <vector>
#include <algorithm>
//using namespace std;
int main() {
int T;
std::cin >> T;
while (T--) {
//inputting p[n]
int n;
std::cin >> n;
std::vector<int> p(n);
for (int i = 0; i < n; i++) {
std::cin >> p[i];
}
std::vector<int> max_before(n);
max_before[0] = 0;
for (int i = 1; i < n; ++i) {
if (p[i] > p[max_before[i-1]]) {
max_before[i] = i;
} else {
max_before[i] = max_before[i-1];
}
}
while (n != 0) {
int index = max_before[n-1];
for (int i = index; i < n; i++) {
std::cout << p[i] << " ";
}
//deleting element by decreasing n:
n = index;
}
std::cout << '\n';
}
return 0;
}
In an array of N elements (N is given), find the smallest element from the first zero element to the end of the array. If there are no zero elements in the array, display a message about it.
Can someone fix this for me please?
#include<iostream>
using namespace std;
int main() {
int i, n;
cout << "N= "; cin >> n;
if (n > 0) {
int *a = new int[n];
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < n; i++) {
if (a[0] > a[i])
a[0] = a[i];
}
cout << "\nMin:" << a[0];
delete[] a;
}
return 0;
}
I couldn't find the problem with your code so I am showing how I approached finding a minimum element from a given array:
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int minNo=INT16_MAX; // to assign max. possible value to minNo
for(int i=0;i<n;i++){
minNo=min(arr[i],minNo);
}
cout<<minNo<<endl;
return 0;
}
You can simply check it in the same loop in which you looking for smallest element.
#include <iostream>
#include <climits>
using namespace std;
int main() {
int i, n;
bool isZeroElement = false;
cout << "N= "; cin >> n;
if (n > 0) {
int *a = new int[n];
for (i = 0; i < n; i++) {
cin >> a[i];
}
int minElement = INT_MAX;
for (i = 0; i < n; i++) {
if (!isZeroElement && a[i] == 0)
{
isZeroElement = true;
continue;
}
if (isZeroElement && minElement > a[i])
minElement = a[i];
}
if (!isZeroElement)
cout << "There is no zero element in the array\n";
else
cout << "\nMin:" << minElement;
delete[] a;
}
return 0;
}
The assignment was to write a program that receives numbers as an inputs (each one on a new line) and then sorts them from smallest to largest. The way to end the input is to enter a blank newline after the numbers are entered. My program works fine except for when I enter only a blank line. Then the program times out.
Here is my code:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
void sort(vector<int>& v)
{
for(int i = 0; i < v.size() - 1; ++i)
{
int min = i;
for(int j = i; j < v.size(); ++j)
{
if(v[j] < v[min])
{
min = j;
}
}
if(min != i){
int temp = v[min];
v[min] = v[i];
v[i] = temp;
}
}
}
void print(vector<int> v)
{
for(int i = 0; i < v.size(); ++i)
{
cout << v[i];
if(i != v.size() - 1)
{
cout << ", ";
}
}
cout << endl;
}
int main()
{
cout << "Enter integers (one on each line, entering an empty line quits):" << endl;
vector<int> v;
string str;
while(getline(cin, str))
{
if(str == "")
{
cout << "Sorted: ";
break;
}
else
{
v.push_back(atoi(str.c_str()));
}
}
sort(v);
print(v);
return 0;
}
Any help is appreciated.
You don't check for empty vector in sort() and v.size() - 1 causes integer underflow. Add check for empty vector:
void sort(vector<int>& v)
{
if (!v.empty()) {
for(int i = 0; i < v.size() - 1; ++i)
{
int min = i;
for(int j = i; j < v.size(); ++j)
{
if(v[j] < v[min])
{
min = j;
}
}
if(min != i){
int temp = v[min];
v[min] = v[i];
v[i] = temp;
}
}
}
}
I have it so that the user defines the size of the vector and then a vector is filled. Then that vector is sorted using bubble sort (homework assignment). However, when the "sorted" vector is displayed, there are different numbers in it than what were in the original creation. How do I first create the vector, display it, then sort it and display it??
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
int main()
{
int n;
double average=0.0;
int median = 0;
double size = 0.0;
int i=0;
cout<<"Vector Length?: "<<endl;
cin>>n;
vector<int> data;
srand(time(NULL));
//Filling vector
for (int i=0; i<n; i++)
{
data.push_back(rand()%10+1);
}
for (int i=0; i<data.size(); i++)
{
cout<<"Vector: "<< data[i]<<endl;
}
size = data.size();
//Sorting
void bubbleSort(vector<int> & data);
{
for (int k = 1; k < size; k++)
{
for (int i = 0; i<size -1 - k; i++)
{
if (data[i] > data[i +1])
{
int temp = data[i];
data[i] = data[i + 1];
data[i + 1] = temp;
}
cout<<"Sorted vector: "<< data[i]<<endl;
}
}
}
First off:
make sure to include all necessary header files, e.g. stdlib.h for your used rand() function.
get rid of all unused variables, like average, median and size.
declare your bubbleSort function outside of main function, and add additional checkup code to prevent sort if list has not more than one element.
The sort problem is related to this code snippet of yours:
for (int i = 0; i<size -1 - k; i++) { ... }
Simply remove -1
To fix your sort problem, and for better output, use following code:
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <cmath>
using namespace std;
void bubbleSort(vector<int>& data)
{
if(data.size() <= 1)
return;
for(int i=1; i<data.size(); i++)
{
for(int j=0; j<data.size()-i; j++)
{
if(data.at(j) > data.at(j+1))
{
int temp = data.at(j+1);
data.at(j+1) = data.at(j);
data.at(j) = temp;
}
}
}
}
int main()
{
int n;
vector<int> data;
cout << "Vector Length?: ";
cin >> n;
// Filling vector
for(int i=0; i<n; i++)
data.push_back(rand()%10+1);
cout << "Vector: ";
for(int i=0; i<data.size(); i++)
cout << data.at(i) << ", ";
// Sorting
bubbleSort(data);
cout << endl << "Sorted Vector: ";
for(int i=0; i<data.size(); i++)
cout << data.at(i) << ", ";
return 0;
}
Hope this helps ;)
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
void printVector(vector<int> & data)
{
for (int i=0; i<data.size(); i++)
{
cout<<"Vector: "<< data[i]<<endl;
}
}
//Sorting
void bubbleSort(vector<int> & data);
{
size = data.size();
for (int k = 1; k < size; k++)
{
for (int i = 0; i<size -1 - k; i++)
{
if (data[i] > data[i +1])
{
int temp = data[i];
data[i] = data[i + 1];
data[i + 1] = temp;
}
}
}
}
int main()
{
int n;
double average=0.0;
int median = 0;
double size = 0.0;
int i=0;
cout<<"Vector Length?: "<<endl;
cin>>n;
vector<int> data;
srand(time(NULL));
//Filling vector
for (int i=0; i<n; i++)
{
data.push_back(rand()%10+1);
}
printVector(data);
bubbleSort(data);
printVector(data);
}
If you are planning to define function void bubbleSort(vector & data) later you need to declare it before calling it.\
void bubbleSort(vector<int> & data);
int main()
{
// Here your code
bubbleSort(data);
//Here your code
}
You need to define variables only just before you need it. And if you declare and never use it, you will get unused variable warnings. So better you can comment all these variables. You can un-comment whenever you need.
//double average=0.0;
//int median = 0;
You should call your function bubbleSort() from main() as follows:
bubbleSort(data);
You are not using the iterator indexes properly to sort the elements of vector. If you change your function bubbleSort as follows it will work
//Sorting
void bubbleSort(vector<int> & data)
{
int size = data.size();
for (int k = 1; k < size; k++)
{
for (int i = 0; i<size -1 ; i++)
{
if (data[i] > data[k])
{
int temp = data[i];
data[i] = data[k];
data[k] = temp;
}
//cout<<"Sorted vector: "<< data[i]<<endl;
}
}
}
complete program for your reference:
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
//Sorting
void bubbleSort(vector<int> & data)
{
int size = data.size();
for (int k = 1; k < size; k++)
{
for (int i = 0; i<size -1 ; i++)
{
if (data[i] > data[k])
{
int temp = data[i];
data[i] = data[k];
data[k] = temp;
}
//cout<<"Sorted vector: "<< data[i]<<endl;
}
}
}
int main()
{
int n;
//double average=0.0;
//int median = 0;
//double size = 0.0;
//int i=0;
cout<<"Vector Length?: "<<endl;
cin>>n;
// int n =10;
vector<int> data;
srand(time(NULL));
//Filling vector
for (int i=0; i<n; i++)
{
data.push_back(rand()%10+1);
}
for (unsigned int i=0; i<data.size(); i++)
{
cout<<"Vector: "<< data[i]<<endl;
}
bubbleSort(data);
std::cout<<"sorted vector"<<"\n";
for (unsigned int i=0; i<data.size(); i++)
{
cout<<"Vector: "<< data[i]<<endl;
}
}