Coordinate left-right-up-down in C++ - c++

I'm making a pan-tilt tracking camera like this, before control servos, I have to know where object is ( up-left, up-right, down-left, down-right), I've tried
if ( x > 350) {
move_right();
}
else if (x < 290) {
move_right();
}
if ( y > 206) {
move_up();
}
else if ( y < 126) {
move_down();
}
But I think it's looked weird. Is there any method simple like switch statement?? My code is written in C++ and OpeCV libraries

The switch statement uses exact values and not inequalities. It won't be of any use for you.
I don't know if you really need the "else-if". Also, what happens when x is between 290 and 350?
If you can keep the comparison operator the same, you could create a lookup table of .

Related

How to generate a boolean condition during runtime in C++?

I want to be able to generate a boolean condition during the runtime based on the states of some variables. My task looks simple at first. I have a large if () else if () statement what needs to determine if the number is in a certain range. It then does something depending on whether that number is inside that range.
Here's pseudocode to demonstrate what I want:
void fun(int num, int offset = 0) {
if (0...60) {
// do something
} else if (60...180) {
// do something else
} else if (180...240) {
} else if (240...360) {
}
}
The first if statement should work like this:
if (0 >= num && num <= 20) {
// do something
}
The caveat here is that in addition to int num, there is another parameter passed in, which I call the offset. The structure of the code here, including the do something inside the { } is the same. The only things that need to change are are ranges, based on the value of the offset. By the way, this is not a default parameter here, it is just pseudocode demonstrating what the value of int offset was passed in.
void fun(int num, int offset = 120) {
if (120...180) {
// do something
} else if (180...300) {
// do something else
} else if (300...360) {
} else if (360...120) {
}
}
That last else if () statement has been giving me some trouble.
} else if (360...120) {
}
What I'm actually trying to write here is:
} else if (num >= 360 || num <= 120) {
}
The reason for this is that my int num may have a value > 360. However, in that case for the purpose of my application it has to "wrap around" and be treated as a value 0...120.
This is for a mathematical application here. Whenever you have int num > 360, you go around the full circle and you end back at 0 where you started. So that is the effect which I want to achieve.
I don't want to write extra functions. I want my code to be generic because many different values for int num and int offset may be passed into my function. I want to generate the necessary conditions during the runtime based on the value of int offset.
The main problem here is that in the first situations, when int offset = 0 my condition is
} else if (240 >= num && num <= 360) {
}
However, for a different offset we wrap around and so I have to change the format of the entire condition! For example, when int offset = 120, as shown above:
} else if (num >= 360 || num <= 120) {
}
The problem is that in the first situation I had the && in the last else if (), but now I have the || to convey the same meaning. What I'm looking for is a way to be able to manipulate the operators inside the conditional statements as mere chars in a string, then "paste" the completed condition into the if () statements during the runtime!
What's even worse is that this "wrapping around" can occur inside any one of the if () statements, not just the last one. It is based on the value of the offset.
I can't use preprocessor tricks, because I want this to work during the runtime. Maybe it is possible to use function pointers or something for this, but I don't know how to do that. Please note that the ... above is not real C++ code, it is pseudocode! I'm aware that there is a "range-based" switch statement in C++, but I can't use that because of the "wrapping around" property mentioned above.

branching depending on which of 3 numbers is smallest

The solution is obvious, but this is question about nice solution.
(EDIT: by nice I mean e.g. 1) without code redudancy 2) without comprimising performance 3) without forcing programmer to make some unnecessary function or temporary variables )
Consider situation when I would like to execute 3 different blocks of code depending on which of numbers a,b,c is smallest.
The code would look like this:
if( a < b ){
if( a < c ){
// code block for "a is minimum" case
}else{
// code block for "c is minimum" case
}
}else{
if( b < c ){
// code block for "b is minimum" case
}else{
// code block for "c is minimum" case
}
}
What I don't like is that I have to copy the // code block for "c is minimum" case twice.
There are several solutions to that. E.g. I can put the block of code for "c is minimum" into an inline function or macro. But I don't like it (seems less clear to read).
Old school solution would be use goto like:
if( a < b ){
if( a < c ){
// code for "a is minimum" case
goto BRANCHE_END;
}
}else{
if( b < c ){
// code for "b is minimum" case
goto BRANCHE_END;
}
}
// code for "c is minimum" case
BRANCHE_END:
but people don't like to see goto (for good reason). On the other hand in this particular case it is even very well readable.
If the block of code would be independent function it can be written like
void myBranching( double a, double b, double c ){
if( a < b ){
if( a < c ){
// code for "a is minimum" case
return;
}
}else{
if( b < c ){
// code for "b is minimum" case
return;
}
}
// code for "c is minimum" case
return;
}
(which is actually almost the same as that goto) But in many cases similar block of code have to be part of more complex algorithm and it is inconvenient to put it inside function. Encapsulation in function would require passing many variables which are used both inside and outside ( e.g. see the use case below) .
Is there any control structure in C/C++ which would solve this in elegant way.
NOTE: Consider performance critical code. (e.g. ray-tracer, GLSL shader, physical simulation ). Anything which would add some unnecessary computational overhead is out of question.
Additional questions / comments
This is one of a few examples when I feel like Structured programming tie my hands, and that it is just subset of what is possible to do with jump instruction. Do you know other examples where algorithm would be more simple and clear using goto rather than standard control structures ?
can you imagine more complex branching where it would be necessary to copy some blocks of code even more times ?
EDIT : Use case
I think some confusion resulted from the fact that I did not specified context in which I want to use this. This is part of algorithm which raytrace regular triclinic 3D grid ( something like Bresenham's line algorithm in 3D, but the starting point is float (not aligned to center of any box) )
but please, do not focus on algorithm itself, it may be also wrong, I'm currently debugging it.
double pa,pb,pc,invPa,invPb,invPc,mda,mdb,mdc,tmax,t;
int ia,ib,ic;
// for shortness I don't show initialization of these variables
while( t<tmax ){
double tma = mda * invPa;
double tmb = mdb * invPb;
double tmc = mdc * invPc;
if( tma < tmb ){
if( tma < tmc ){ // a min
t += tma;
mda = 1;
mdb -= pb*tma;
mdc -= pc*tma;
ia++;
}else{ // c min
t += tmc;
mda -= pa*tmc;
mdb -= pb*tmc;
mdc = 1;
ic++;
}
}else{
if( tmb < tmc ){ // b min
t += tmb;
mda -= pa*tmb;
mdb = 1;
mdc -= pc*tmb;
ib++;
}else{ // c min
t += tmc;
mda -= pa*tmc;
mdb -= pb*tmc;
mdc = 1;
ic++;
}
}
// do something with ia,ib,ic,mda,mdb,mdc
}
You can solve this pretty easily with std::min and using the version that takes a std::initializer_list. You call min on the three variables to get the minimum and then you have three if statements to check the return against each of the variables.
void foo(int a, int b, int c)
{
int min = std::min({a, b, c});
if (min == a)
{
// a case
}
else if (min == b)
{
// b case
}
else
{
// c case
}
}
You don't have to nest conditionals by the way:
if(a <= b && a <= c) { /* a is the lowest */ }
else if(b <= c) { /* b is the lowest */ }
else { /* c is the lowest */ }
Note that the semantics of C++'s operator && is such that
if(a <= b && a <= c)
works roughly like
if(a <= b) if(a <= c)
(The difference is that the succeeding else clause, if any, covers both ifs simultaneously.) In the expression cond1 && cond2, if cond1 proves to be false then cond2 is never evaluated, at least, it does not have observable side-effects.
Sure we can make something more monstrous, with non-local exits, for example:
do {
if(a <= b) {
if(a <= c) {
// a is the lowest
break;
}
}
else if(b <= c) {
// b is the lowest
break;
}
// c is the lowest
}
while(0);
But in fact this construct, despite being incredibly taller, is logically equivalent to those three lines above (with Dieter's proposed edit).

Is it possible to embed "for loop" inside an "if statement" to compare multiple condition before continuing using c++

In this program, the user must type in an 3 letter departing airport code (userFlight) and I will give them back the possible destinations. To check that what they typed in is one of the valid airport codes (departureAirport) I want to compare userFlight and make sure it is one of the possible departureAirports which I have stored in a vector called flights[]. This code obviously isn't working, but is there a similar way to accomplish this?
if
(for (j = 0, j < flights.size, j++)
{
(userFlight != flights[j].departAirport)
})
{return errorCode};
else
{//doSomething()};
If it has a operator< inside which does compare like your condition, how about
if(std::find(flights.begin(), flights.end(), userFlight) != flights.end())
{
/* found */
}
else
{
/* not found */
}
Else, if you don't like that, just check if the loop runs through all indices:
size_t i;
for (i = 0, i < flights.size, i++)
{
if(userFlight == flights[i].departAirport)
break;
}
if(i < flights.size)
{
/* found */
}
else
{
/* not found */
}
But no, a syntax like you want doesn't exist.
The code structure you were aiming for is:
for (j = 0; j < flights.size(); j++)
if (userFlight == flights[j].departAirport)
break;
if ( j == flights.size() ) // we got to the end
return errorCode;
doSomething(j);
However, this is a C-like code style. Not that there is anything wrong with that, but C++ allows for algorithms to be expressed more abstractly (and therefore, easier to read and maintain). IMHO it would be better to use one of the other suggestions such as std::set or std::find_if.
It sounds like you actually want to have a std::set of departing airports.
std::set<std::string> departing_airports = {"DTW", "MKE", "MSP", };
assert(departing_airports.count("DTW") == 1);
Yet another option is std::any_of. Assuming flights contains objects of type Flight:
if (std::any_of(std::begin(flights), std::end(flights),
[&](const Flight& f) { return userFlight == f.departAirport; }))
return errorCode;
doSomething();

C++ translated to objective-C

I'm looking into translating some code from C++ to Objective C and I ran into an instance that contains a function with a const notation at the end. I'm quite rusty on C++ and I don't remember what this would represent (I have been googling though). I'd like to know how to force this over to Objective-C. Currently, here's what I have:
C++ code:
float RenderingEngine1::RotationDirection() const
{
float delta = m_desiredAngle - m_currentAngle;
if (delta == 0)
return 0;
bool counterclockwise = ((delta > 0 && delta <= 180) || (delta < -180));
return counterclockwise ? +1 : -1;
}
Objective-C:
-(float)getRotationDirection{
float delta = desiredAngle - currentAngle;
if (delta == 0) {
return 0;
}
bool counterclockwise = ((delta > 0 && delta <= 180) || (delta < -180));
float test = counterclockwise ? +1 : -1;
NSLog(#"%f",test );
return counterclockwise ? +1 : -1; //problem
}
Edit: found the error of my ways and it was just an addition problem somewhere else in the program ('I love the easy ones'). That being said, I do want to ensure that the const declaration will not interfere with any further issues and want to check to ensure whether or not there should be any declarations I need to make (such as singleton methods and such). Thank you guys for the answers!
const in c++ means that this method doesn't alter the state of the object, thus it may use just const methods, and it can't alter class variables unless they're declared mutable.
If your class is immutable, you can safely assume that every method you've declared is the equivalent of a const method.
However, since you aren't altering any ivar, you're "translating" the code properly (logically speaking), as you aren't mutating any ivar.
I don't see any particular problem with your code, there shouldn't be a syntax (neither semantic) error.
PS: That's not how you should compare floating point numbers, look here.

C++ Can someone explain what these for loops are saying?

So this code is the base outline for a boggle game from online that I copied over.
SOURCE: http://www.codingfriends.com/index.php/2010/06/10/boggle/
bool findUsersWord(string findThis, Grid<char> &theBoard, Vector<cell> &theRoute, string alreadyFound, int placeY, int placeX)
{
// need to find the findThis base case
if (findThis == alreadyFound)
return true;
// need to find the first letter within the board and then progress around that.
if (alreadyFound.empty())
{
for (int rows = 0; rows < theBoard.numRows(); rows++)
for (int cols = 0; cols < theBoard.numCols(); cols++)
// find the each character within the
if (theBoard[rows][cols] == findThis[0])
{
alreadyFound = findThis[0];
cell newR;
newR.row = rows;
newR.col = cols;
theRoute.add(newR);
if (findUsersWord(findThis, theBoard, theRoute, alreadyFound, rows, cols))
return true;
else
// clear out the found Board
theRoute.clear();
}
}
else
{
// try and find the next letters within the area around the base letter
// spin around the letter 3 * 3 grid
for (int y= (placeY > 0 ? placeY-1: placeY); y <=(placeY == (theBoard.numRows()-1) ? placeY : placeY+1);y++)
for (int x=(placeX > 0 ? placeX-1: placeX); x<=(placeX == (theBoard.numCols()-1) ? placeX : placeX+1); x++)
if ((theBoard[y][x] == findThis[alreadyFound.length()]) && (!(y==placeY && x ==placeX)))
// already used letter
if (!placeAlreadyUsed(y,x,theRoute))
{
alreadyFound += findThis[alreadyFound.length()];
cell newR;
newR.row = y;
newR.col = x;
theRoute.add(newR);
if (findUsersWord(findThis, theBoard,theRoute, alreadyFound, y, x))
return true;
else
{
if (alreadyFound.length() > 1)
alreadyFound = alreadyFound.substr(0, alreadyFound.length()-1);
theRoute.removeAt(theRoute.size()-1);
}
}
return false;
}
return false;
}
The code below is the code in question which is part of the code above.
for (int y= (placeY > 0 ? placeY-1: placeY); y <=(placeY == (theBoard.numRows()-1) ? placeY : placeY+1);y++)
for (int x=(placeX > 0 ? placeX-1: placeX); x<=(placeX == (theBoard.numCols()-1) ? placeX : placeX+1)
I am wondering if someone could turn this code into more simple code that doesn't involve the using of ? and that. I do know the simple parts of it such as the "?" means return and ":" means next line, but I am lost in the fact that it is being used in a for loop and the fact that it would just look like
if(placeY > 0)
return playceY-1
placeY;
Where have I gone wrong?
The ? : block is just a strange looking if statement. It's an inline if, if you will.
Here's the format
argument ? result evaluated to if true : result evaluated to if false
Here's an example
1<2 ? "Hurray" : "boo"
Will evaluate to "Hurray" because 1<2 is true. However, if we switch it to 1>2 it will evaluate to "boo".
I do know the simple parts of it such as the "?" means return and ":" means next line
Um, no. That's not what it means at all. ?: is one operator with three operand expressions, one of which appears between the ? and the :.
placeY > 0 ? placeY-1 : placeY
is an expression that means: "If placeY > 0 then evaluate placeY-1; otherwise evaluate placeY".
The idea of the code is that we want, for some reason, to iterate over all positions of the board that are next to (placeX,placeY). Those positions form a rectangle, and the ?: operators are used to compute the left, right, top and bottom limits of that rectangle. For example the expression quoted above is for the top coordinate. It is usually placeY-1, except that if placeY is already 0, there is no row on the board above it, and in that case placeY itself is the top row.