I just want to create a simple C++ struct that has an int index and an int grayValue .The function is given the vector with the gray values. When I try to compile it I get a segmentation fault, does anyone know why? (didn't sort the vector) Thank you.
vector<gray> createStruct( vector<int> grayValues)
{
vector <gray> grayStruct;
for (int i = 0; i<grayValues.size();i++)
{
grayStruct[i].originalIndex= i;
grayStruct[i].grayValue= grayValues[i];
}
return grayStruct;
}
int main() {
vector <int> grayVals={411,21,78,23};
vector <gray> grayStruct=createStruct(grayVals);
// sort(grayStruct);
for (int i = 0; i < grayStruct.size(); i++)
{cout << grayStruct[i].originalIndex<<' '<<grayStruct[i].grayValue;
cout<<endl;
}
return 0;
}
It is because you are using elements of grayStruct, which actually doesn't exist, in the function createStruct.
You have to create elements before use or use push_back() to create elements.
Create elements via the constructor:
vector<gray> createStruct( vector<int> grayValues)
{
vector <gray> grayStruct(grayValues.size()); // add number of elements to create
for (int i = 0; i<grayValues.size();i++)
{
grayStruct[i].originalIndex= i;
grayStruct[i].grayValue= grayValues[i];
}
return grayStruct;
}
Create elements via resize():
vector<gray> createStruct( vector<int> grayValues)
{
vector <gray> grayStruct;
grayStruct.resize(grayValues.size()); // create elements
for (int i = 0; i<grayValues.size();i++)
{
grayStruct[i].originalIndex= i;
grayStruct[i].grayValue= grayValues[i];
}
return grayStruct;
}
Add elements one-by-one via push_back():
vector<gray> createStruct( vector<int> grayValues)
{
vector <gray> grayStruct;
for (int i = 0; i<grayValues.size();i++)
{
gray value;
value.originalIndex= i;
value.grayValue= grayValues[i];
grayStruct.push_back(value); // add an element
}
return grayStruct;
}
I am writing a function in c++ which takes a vector array as a parameter and then finds the number of occurrences of the largest value in it.
I have written function birthdaycakecandles and main function as below.
#include <iostream>
using namespace std;
int birthdaycakecandles(vector<int> a)
{
int largest=a[0];
int pos;
for(int i=1;i<a.size();++i)
{
if(largest<a[i])
{
largest=a[i];
pos=i;
}
}
int count=1;
for(int i=0;i<a.size();++i)
{
if(a[i]==largest&&i!=pos)
count++;
}
return count;
}
int main()
{
double n;
cin>>n;
vector<int> a;
for(double i=0;i<n;++i)
cin>>a[i];
int val=birthdaycakecandles(a);
cout<<val;
return 0;
}
Please review the code and suggest me the reason(s) for the error.
The compiler is giving me segmentation error.
Thanks.
Given the code
vector<int> a;
for(double i=0;i<n;++i)
cin>>a[i];
a is empty; access to nonexistent elements as a[i] leads to UB, anything is possible.
You can initialize a containing n elements from the beginning.
size_t n;
cin>>n;
vector<int> a(n);
for(size_t i=0;i<n;++i)
cin>>a[i];
Or use push_back to insert elements into a.
size_t n;
cin>>n;
vector<int> a;
for(size_t i=0;i<n;++i) {
int x;
cin>>x;
a.push_back(x);
}
PS: Using double as the index of vector seems meaningless.
When using vector, we have to add elements using push_back or emplace_back. In order to traverse the vector, make use of vector iterators for exception safety due to out of bound access.
for (vector<int>::iterator it = a.begin() ; it != a.end(); ++it)
{
//your implementation goes here.
cout << *it << endl; //access each element like this
}
Also note that a.end() is in fact the last_element + 1
vector<int> a;
for(double i=0;i<n;++i)
cin>>a[i];
This is not the way to input in vector use a.push_back(i); instead;
and use auto to traverse till a.begin() till a.end()
I am writing a code to find number of pairs in a given array.But i am getting segmentation fault.
I am sorting the given array and then comparing the elements to get pairs.
#include <bits/stdc++.h>
using namespace std;
int sockMerchant(int n, vector<int> ar) {
sort(&ar[0], &ar[n]);
int k=1;
int m=0;
for(int i=0;i<n;i++){
for(int j=1;j<n;j++){
if (ar[i]=ar[j])
k++;
if(ar[i]!=ar[j])
i=j;
m+=k/2;
break;
}
}
return m;
}
int main()
{
int n;
cin>>n;
vector<int> ar;
for(int i=0;i<n;i++){
cin>>ar[i];
}
int k = sockMerchant(n,ar);
cout<<k<<endl;
return 0;
}
When you say
vector<int> ar;
It just creates an empty vector.
So your for loop is basically trying to write to the elements of an empty vector.
for(int i=0;i<n;i++){
cin>>ar[i];
}
You can either:
Call ar.resize(n); before the for loop
or
You can use vector::push_back function to let the vector resize dynamically as you enter your values.
for(int i=0;i<n;i++){
int tmp;
cin>>tmp;
ar.push_back(tmp);
}
P.S: You don't have to pass n to your function. you can use ar.size() to get the size of your vector
I am trying to implement a code from a standard quotient and remainder algorithm namely:
function divide(x,y)
if x=0: return (q,r)=(0,0)
(q,r)=divide(floor(x/2),y)
q=2*q, r=2*r
if x is odd: r=r+1
if r>=y: r=r-y, q=q+1
return (q,r)
with a c++ code here is the relavent part of my function
bool compareVector(const vector<int> &A, const vector<int> &B){
if(A.size()<B.size())
return(1==0);
if(A.size()>B.size())
return(1==1);
for(int i=A.size()-1;i>=0;i--){
if (A[i]>B[i])
return(1==1);
if(A[i]<B[i])
return(1==0);
}
return(1==1);
}
struct QandR{
vector<int> r;
vector<int> q;
};
QandR Division(vector<int> BinaryA, const vector<int> & BinaryB, QandR &x){
vector<int> one, zero;
one.clear();
one.push_back(1);
zero.clear();
zero.push_back(0);
if(BinaryA==zero){
return x;
}
else if(BinaryA==one){
BinaryA[0]=0;
}
else if(BinaryA.size()>1)
pop_front(BinaryA);
x=Division(BinaryA,BinaryB,x);
x.q=addBinary(x.q,x.q);
x.r=addBinary(x.r,x.r);
if(BinaryA[0]==1)
x.r=addBinary(x.r,one);
if(compareVector(x.r,BinaryB))
{
x.r=Subtract(x.r,BinaryB);
x.q=addBinary(x.q,one);
}
return x;
}
However this simply does not work for example with BinaryA={1,0,1,1} and BinaryB={0,1}. This is 13/2 so q should be {0,1,1}, and r should be {1}. But my code out puts r={1} and q={0,1}. I don't understand what is going on. All functions that are used above that are not defined work. Also, is there a easier way to return two values in c++ if there is I would be grateful to know. Thank you.
Add is the whole code
#include <iostream>
#include <string> //this is only used for the user to insert a number
#include <stdlib.h> //this is used to convert the user iputed string to a vector
#include <vector>
#include <algorithm>
using namespace std;
void CleanArray(vector<int> & Array){ //CleanArray() is mainly for the Multiply function where we need to keep removing the enteries
for(int i=0;i<Array.size();i++){
Array[i]=0; //of a vector<int> Array. And then I clean some of the other struct vector<int>'s for saft
}
}
vector<int> addBinary(vector<int> A,vector<int> B){ //addBinary() adds two struct vector<int>'s and returns a new struct vector<int>
vector<int> C; // C is our carry array but we take advantage of the fact that after we carry to a new column we nolonger need the old one so we
// can also use C to store our answere.
C.assign(A.size()+1,0);
CleanArray(C);
for(int i=0; i<B.size();i++){ //Case 1 we are adding the first part where we are adding columns and we still have vector<int> A and vector<int> B
if(C[i]+B[i]+A[i]==3){
C[i]=1;
C[i+1]=1;
}
else if(B[i]+A[i]+C[i]==2){
C[i]=0;
C[i+1]=1;
}
else if(B[i]+ A[i]+C[i] ==1){
C[i]=1;
}
}
for(int i=B.size();i<A.size();i++){ //Case 2 we adding where vector<int> B has been exasted and we only have vector<int> A and vector<int> C.
if(C[i]+A[i]==2){
C[i]=0;
C[i+1]=1;
}
else if(A[i]==1){
C[i]=1;
}
} // this is fine but not necessary.
if(C[C.size()-1]==0) // We want to change C's member length_a if the aswere is one bigger then the size of A.size().
C.pop_back();
return C;
}
vector<int> Subtract(vector<int> A, vector<int> B){ // this function is almost exactly the same as Multiply() using a vector<int> C to hold the value of A-B
vector<int> C;
C.assign(A.size(),0);
CleanArray(C);
// reverse(B.begin(), B.end());
for(int i=A.size()-B.size();i>0;i--)
B.push_back(0);
// reverse(B.begin(), B.end());
for(int i=A.size()-1;i>=0;i--){
if((A[i]+B[i])==2)
C[i]=0;
else if(A[i]==1 && B[i]==0)
C[i]=1;
else if(B[i]==1 && A[i]==0){
C[i]=1;
int j=0;
int k=i+1;
while(j==0){ //we need this while loop bc when we have 0-1 this changes all values of
if(C[k]==1){ //C[i+1] to the next C[]==1, changing all of those to 1 so ex 1000-1=0111
C[k]=0;
j++;
}
else if(C[k]==0){
C[k]=1;
k++;
}
// if(i==C.size()-1 && C.size()>1) // this removes the zero's in front of the numberso the answer is not like 001 but 1.
// C.pop_back();
}
}
// else this was the problem with subtraciton
// C[i]=0; "" " " " " "
}
int i=C.size()-1;
while(C[i]==0 && i!=0){
C.pop_back();
i--;
}
return C;
}
vector<int> Multiply(const vector<int> & A, const vector<int> &B){ // This also uses the concept of having a vector<int> C to store the values of the succesive additions of the rows
vector<int> C;
C.assign(A.size(),0);
for(int j=0;j<B.size();j++){
vector<int> D;
D.assign(A.size(),0);
for(int i=0;i<A.size();i++){
if(B[j]==1)
D[i]=A[i];
// this makes a new row if B[j]==1 so if 1110101*1=1110101(0...0) there are j zero's in
}
D.insert(D.begin(),j,0);
C=addBinary(D,C); //this adds the pervious value of C with the next row.
}
return C;
}
void pop_front(vector<int> & A){
reverse(A.begin(),A.end());
A.pop_back();
reverse(A.begin(),A.end());
}
bool compareVector(const vector<int> &A, const vector<int> &B){
if(A.size()<B.size())
return(1==0);
if(A.size()>B.size())
return(1==1);
for(int i=A.size()-1;i>=0;i--){
if (A[i]>B[i])
return(1==1);
if(A[i]<B[i])
return(1==0);
}
return(1==1);
}
struct QandR{
vector<int> r;
vector<int> q;
};
QandR Division(vector<int> BinaryA, const vector<int> & BinaryB, QandR &x){
vector<int> one, zero;
one.clear();
one.push_back(1);
zero.clear();
zero.push_back(0);
if(BinaryA==zero){
return x;
}
else if(BinaryA==one){
BinaryA[0]=0;
}
else if(BinaryA.size()>1)
pop_front(BinaryA);
x=Division(BinaryA,BinaryB,x);
x.q=addBinary(x.q,x.q);
x.r=addBinary(x.r,x.r);
if(BinaryA[0]==1)
x.r=addBinary(x.r,one);
if(compareVector(x.r,BinaryB))
{
x.r=Subtract(x.r,BinaryB);
x.q=addBinary(x.q,one);
}
return x;
}
/*
vector<int> modexp(vector<int> x,vector<int> y, vector<int> N){
vector<int> one;
vector<int> r;
vector<int> q;
one.push_back(0);
if(y.size()==1 && y[1]==0)
return one;
y.pop_back();
vector<int> z=modexp(x,y,N);
if(y[0]==1){
vector<int> D=Multiply(z,z);
Division(D,N,q,r);
z=q;
return z;
}
else{
vector<int> C =Multiply(Multiply(z,z),x);
Division(C,N,q,r);
z=q;
return z;
}
}
*/
int main(){
int arraya[4]={1,1,0,1};
int arrayb[2]={1,1};
vector<int> a(arraya,arraya+4);
vector<int> b(arrayb,arrayb+2);
for(int i=0;i<a.size();i++){
cout<<a[i]<<" ";
}
cout<<endl;
pop_front(a);
for(int i=0;i<a.size();i++)
cout<<a[i]<<" ";
cout<<endl;
QandR x;
x.r.clear();
x.q.clear();
x.r.push_back(0);
x.q.push_back(0);
x=Division(a,b,x);
for(int i=0;i<x.r.size();i++){
cout<<x.r[i]<<" ";
}
cout<<endl;
for(int i=0;i<x.q.size();i++)
cout<<x.q[i]<<" ";
cout<<endl;
return 0;
}
When you divide BinaryA by 2, and try to call Division again, you have to return BinaryA to its original state so that you can verify if it was odd or not.
So, in these two cases:
else if(BinaryA==one){
BinaryA[0]=0;
}
else if(BinaryA.size()>1)
pop_front(BinaryA);'
you have to keep the bit that is lost and restore it after the recursive Division has returned.
** To print repeated elements from an user defined array
//print repeated elements from an array
#include<iostream>
using namespace std;
int main()
{
int p,n;
cout<<"enter no. of elements in array: "<<endl;
cin>>n;
int a[n],b[n];
int z=0;
cout<<"enter elements of array:"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int j=0;j<n;j++)
{
for(int k=j;k<=n;k++)
{
if(j==k)
{
continue;
}
else if(a[j]==a[k])
{
b[z]=a[j];
++z;
a[k]=a[k+1]; //deleting the array element which repeats
a[n-1]=0; //settng last element as 0
--n; //reducing the size of array
break;
}
int d=z;
if(b[j]==b[k])
{
b[j]=b[j+1];
b[n-1]=0;
n--;
}
}
}
if(z==0)
{
cout<<"No Elemnts in the array is repeated"<<endl;
}
else
{
cout<<"repeated elements are: "<<endl;
for(p=0;p<z;p++)
{
cout<<b[p]<<" ";
}
}
return 0;
}
How to fine tune this program so as it displays correct output? When we enter 3 similar elements it repeats itself twice and also has problem reading the last element.
Thanks
You should rewrite your algorithm. Something like that should work:
std::vector<int> a;
/* fill a */
std::sort(a.begin(), a.end());
std::vector<int> unique_elements;
std::unique_copy(a.begin(), a.end(), std::back_inserter(unique_elements));
std::vector<int> b;
std::copy_if(unique_elements.begin(), unique_elements.end(), std::back_inserter(b), [&](int n)
{
return std::count(a.begin(), a.end(), n) >= 2;
});