I have very recently started using vectors in C++.The purpose of the program I am trying to write is to determine the first missing positive number. Given an input array A : [ -9, 12, -1, 0, 1 ]
the expected output is 2
. I coded it -
int Solution::firstMissingPositive(vector<int> &A)
{
std::sort(A.begin(),A.end()); //sorting vector
bool Negative=false;
int flag;
int i=0;
for(i=0;i<A.size();++i)
{
if(A[i]<=0)
{
Negative=true;
std::cout<<"\nwe found a -ve number or 0";
}
else if( (A[i]>0) && (A[i+1]!=A[i]+1) )
{
Negative=false;
std::cout<<"\ncomparing @ ="<<i<<" which = "<<A[i];
std::cout<<"\ncomparing @ ="<<i+1<<" which = "<<A[i+1];
flag=A[i]+1; //The faulty statement
std::cout<<"\n\n missing number(A[i]+1) @ ="<<A[i]+1;
std::cout<<"\n\n missing number(flag) @ ="<<flag;
break;
}
}
//do something more
}
With this output -
-9 -1 0 1 12
we found a -ve number or 0
we found a -ve number or 0
we found a -ve number or 0
comparing @ =3 which = 1
comparing @ =4 which = 12
missing number(A[i]+1) @ =2
missing number(flag) @ =20
I found this interesting because, to me, it looks like I cannot use an integer to store the value of a vector.
- Trying to debug it I found changing the flag assignment to
flag = A[i]+2
makes the resultant print30
. - I've read other questions on SO where it suggests using
vector.at(i)
instead of the[]
operator as a better practice. Changing this does not reflect any change for my code. - Changing
flag
tovector<int>
gives me a dirty error which I'm not sure about.
Isn't A[i]+1
syntactically equivalent to an integer value? And if it is, why can I not store it?
Aucun commentaire:
Enregistrer un commentaire