conditional in value assignment - c++

In c++, I want to use conditionals when assigning values, for example:
int i = true && 5 || 3;
For example, using Lua you can write this:
i = true and 5 or 3
I am not sure that this is possible
Here is something that I tried:
#include "stdafx.h"
#include <iostream>
void main()
{
int test = (true && 5) || 1;
int test2 = (false && 6) || 2;
std::cout << "Test: " << test << std::endl << "Test2: " << test2 << std::endl;
for(;;);
}

C++ isn't Lua.
In Lua, true and 5 expression results in 5. That's simply how Lua works with boolean expressions.
And that's not how C++ works with boolean expressions. In C++, a boolean expression results in a boolean value. That is, either true or false.
If you want to select between two values based on a condition, we have an operator for that:
int i = true ? 5 : 3;
If the condition is true, you get the value before the :. If it's false, you get the value after the :.

I suspect you're looking for int test = true ? 5 : 1;

What you need is a conditional expression:
int i = true ? 2 : 5;
In this case i will be 2.

If we really wanted to, as of c++11 (which gives us the and and or keywords as a synonyms for && and ||), we could almost strong-arm the c++ compiler into compliance, and get it to compile this:
int x = when_true(b) and 5 or 6;
In order to do this we would need to provide some scaffolding:
#include <iostream>
struct maybe_int {
bool cond;
int x;
operator int() const { return x; }
};
int operator || (const maybe_int& l, int r) {
if (l.cond) return l.x;
return r;
}
struct when_true {
when_true(bool condition)
: _cond(condition)
{}
auto operator&&(int x) const {
return maybe_int { _cond, x };
}
bool _cond;
};
int main()
{
using namespace std;
auto b = false;
int x = when_true(b) and 5 or 6;
cout << x << endl;
return 0;
}
My suggestion would be that you don't try this kind of thing at work.

Related

How to initialize items in a range in a captureless lambda, C++

My code is below. This works, It allows me to have exactly one range in my lambda.
So I guess what my question is, is how do I achieve the same results without using
"if(LOOP > 2 && LOOP < 5){int THERANGEVALUE = 2; FUNC[THERANGEVALUE]();}"?
And instead initialize an item in my captureless lambda as being ranged instead. aka, item_2 being item_range(2,4). And then also being able to continue my lambda normally, whereas Item_3 will equate to item_5.
Thank you for any help in advance, I will gladly add more input if requested.
#include <iostream>
using namespace std;
void (*FUNC[3])(void) = { //captureless lambda.
/*ITEM_0*/[](){ cout << "x" << endl;},
/*ITEM_1*/[](){cout << "y" << endl;},
/*ITEM_2->ITEM_4*/[](){cout<<"z";}
};
/*Here the [](){code;} lambda is acting as a stand-in for void FUNC() so it shouldn't touch anything outside of its scope*/
int LOOP = 4;
int main()
{
if(LOOP > 2 && LOOP < 5){int THERANGEVALUE = 2; FUNC[THERANGEVALUE]();}
FUNC[LOOP]();
return 0;
}
Adding on to this, below is the solution I came up with after asking a friend. To my surprise it was actually a lot simpler than I expected. While I couldn't initialize each item in the lambda in a range easily, I could pass it into an array and set a range inside of the array instead. So while it's not quite what I was looking for, it's...good enough for my purposes. Thanks Jaime if you see this. Otherwise I'd use PilouPili's answer below.
#include <iostream>
using namespace std;
void (*FUNC[4])(void) = { //captureless lambda.
/*ITEM_0*/ [](){ cout << "x" << endl;},
/*ITEM_1*/ [](){cout << "y" << endl;},
/*ITEM_2->ITEM_4*/[](){cout<<"z";},
/*ITEM_5*/ [](){cout<<"z";}
};
int LOOP = 4;
int main()
{
int ARR[5]={};
for(int I = 0; I < 6;I=I+1){//handling of ranged values.
if(I>2 && I<5){ARR[I]=2;} else {ARR[I]=I;}
}
FUNC[ARR[LOOP]]();
return 0;
}
I only see to way :
either extend your function array -> That's FUNC1 in the next example
change the value given in operator [] -> That's FUNC2 in the next example
#include <iostream>
#include <vector>
using namespace std;
std::vector<void (*)(void)> init_FUNC()
{
std::vector<void (*)(void)> func(5, [](){cout<<"z";});
func[0]=[](){ cout << "x" << endl;};
func[1]=[](){ cout << "y" << endl;};
return func;
}
std::vector<void (*)(void)> FUNC1= init_FUNC();
class FUNC_MAP
{
void (*_FUNC[3])(void) = { //captureless lambda.
/*ITEM_0*/[](){ cout << "x" << endl;},
/*ITEM_1*/[](){cout << "y" << endl;},
/*ITEM_2->ITEM_4*/[](){cout<<"z";}
};
typedef void (*FUNC_MAP_OUT)(void);
public:
FUNC_MAP_OUT operator[](int i)
{
if(i>2 && i<5)
{return _FUNC[2];}
else
{return _FUNC[i];}
}
};
FUNC_MAP FUNC2;
/*Here the [](){code;} lambda is acting as a stand-in for void FUNC() so it shouldn't touch anything outside of its scope*/
int LOOP = 1;
int main()
{
FUNC1[LOOP]();
FUNC2[LOOP]();
return 0;
}

list requires class type

So I'm trying to make a bubble sort algorithm in class and I'm having this problem where it keeps giving me an error when I'm trying to find the length of the list where it says "expression must have a class type" and for the life of me I cannot figure out what to do. the tutorial I'm using isn't an help and I cannot find any other people with the same problem.
if anyone gets what it is asking I would appreciate the help, and any explanation would also be appreciated as I'm still new and would like to understand so I can try to learn
this was all done on VS 2017 (the free version)
#include "pch.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
bool found = true;
int target{ 0 };
int temp{};
bool ordered{ false };
int list[10] = { 4,6,5,1,3,2,10,8,9,7 };
cout << list.length() << endl;
bool swapped{ false };
while (ordered = false)
{
target = 0;
while (target != list.length)
{
if (list[target] > list[target + 1])
{
swapped == true;
list[target] = temp;
list[target] = list[target + 1];
list[target + 1] = temp;
target = target + 1;
}
else
{
target = target + 1;
}
}
if (swapped == false)
{
ordered = true;
}
}
cout << list << endl;
getchar();
return 0;
}
link to the photo of the error message
The error you have mentioned ("expression must have a class type") is caused by the below statement and other similar statements :
cout << list.length() << endl;
list is an integer array of size 10 as per this statement int list[10];
So you cannot use a . on it. You can use the . operator on a structure or class or union only. And even if list were a class/structure, length() method should be defined in it for the above to work.
Instead you should use sizeof operator. You can store it in a variable and use it later on.
size_t length = sizeof list/sizeof list[0];
cout << length << endl;

Return from calling function inside lambda

Lambdas are an awesome way to create reusable code inside a function/method without polluting the parent class. They're a very functional replacement for C-style macros most of the time.
However, there's one bit of syntactic sugar from macros that I can't seem to replicate with a lambda, and that's the ability to exit from the containing function. For example, if I need to return while checking the range of a series of ints, I can do that easily with a macro:
const int xmin(1), xmax(5);
#define CHECK_RANGE(x) { if((x) < xmin || (x) > xmax) return false; }
bool myFunc(int myint) {
CHECK_RANGE(myint);
int anotherint = myint + 2;
CHECK_RANGE(anotherint);
return true;
}
Obviously this is an oversimplified example, but the basic premise is that I'm performing the same check over and over on different variables, and I think it's more readable to encapsulate the check and related exits. Still, I know that macros aren't very safe, especially when they get really complex. However, as far as I can tell, trying to do the equivalent lambda requires awkward additional checks like so:
const int xmin(1), xmax(5);
auto check_range = [&](int x) -> bool { return !(x < xmin || x > xmax); };
bool myFunc(int myint) {
if(!check_range(myint)) return false;
int anotherint = myint + 2;
if(!check_range(anotherint)) return false;
return true;
}
Is there a way to do this with a lambda? Or am I missing some alternative solution?
Edit: I recognize that returning from inside a macro is generally a bad idea unless significant precautions are taken. I'm just wondering if it's possible.
You are correct--there's no way to return from the caller from inside a lambda. Since a lambda can be captured and stored to be called later, from inside an arbitrary caller, doing so would result in unpredictable behavior.
class Foo
{
Foo(std::function<void(int)> const& callMeLater) : func(callMeLater) {}
void CallIt(int* arr, int count)
{
for (index = count; index--;)
func(count);
// do other stuff here.
}
std::function<void(int)> func;
};
int main()
{
auto find3 = [](int arr)
{
if (arr == 3)
return_from_caller; // making up syntax here.
};
Foo foo(find3);
};
Is there a way to do this with a lambda?
Not exactly like the macro but your lambda, instead of returning a bool, can throw a special exception (of type bool, by example)
auto check_range
= [](int x) { if ( (x < xmin) || (x > xmax) ) throw bool{false}; };
and the function myFunc() can intercept this special type
bool myFunc (int myint)
{
try
{
check_range(myint);
int anotherint = myint + 2;
check_range(anotherint);
return true;
}
catch ( bool e )
{ return e; }
}
For a single check_range() call, this is (I suppose) a bad idea; if you have a lot of calls, I suppose can be interesting.
The following is a full working example
#include <iostream>
constexpr int xmin{1}, xmax{5};
auto check_range
= [](int x) { if ( (x < xmin) || (x > xmax) ) throw bool{false}; };
bool myFunc (int myint)
{
try
{
check_range(myint);
int anotherint = myint + 2;
check_range(anotherint);
return true;
}
catch ( bool e )
{ return e; }
}
int main ()
{
std::cout << myFunc(0) << std::endl; // print 0
std::cout << myFunc(3) << std::endl; // print 1
std::cout << myFunc(7) << std::endl; // print 0
}
No better way to do this than just to use the return value of the lambda and then return from the calling function. Macros are ew for this.
As it stands in C++, that is the idiomatic way to exit from a function that uses another condition to determine whether or not to exit.
Not C++11, but people have hacked C++2a coroutines to basically do this.
It would look a bit like:
co_await check_range(foo);
where the co_await keyword indicates that in some cases, this coroutine could return early with an incomplete result. In your cases, this incomplete result would be non-resumabable error.
The playing around I saw was with optionals, and required using a shared ptr, but things may improve before it is standardized.

Condensing a do-while loop to a #define macro

Consider the following sample code (I actually work with longer binary strings but this is enough to explain the problem):
void enumerateAllSubsets(unsigned char d) {
unsigned char n = 0;
do {
cout<<binaryPrint(n)<<",";
} while ( n = (n - d) & d );
}
The function (due to Knuth) effectively loops through all subsets of a binary string;
For example :
33 = '00100001' in binary and enumerateAllSubsets(33) would produce:
00000000, 00100000, 00000001, 00100001.
I need to write a #define which would make
macroEnumerate(n,33)
cout<<binaryPrint(n)<<",";
behave in a way equivalent to enumerateAllSubsets(33). (well, the order might be rearranged)
Basically i need the ability to perform various operations on subsets of a set.
Doing something similar with for-loops is trivial:
for(int i=0;i < a.size();i++)
foo(a[i]);
can be replaced with:
#define foreach(index,container) for(int index=0;index < container.size();index++)
...
foreach(i,a)
foo(a[i]);
The problem with enumerateAllSubsets() is that the loop body needs to be executed once unconditionally and as a result the do-while cannot be rewritten as for.
I know that the problem can be solved by STL-style templated function and a lambda passed to it (similar to STL for_each function), but some badass #define macro seems like a cleaner solution.
Assuming C++11, define a range object:
#include <iostream>
#include <iterator>
#include <cstdlib>
template <typename T>
class Subsets {
public:
Subsets(T d, T n = 0) : d_(d), n_(n) { }
Subsets begin() const { return *this; }
Subsets end() const { return {0, 0}; }
bool operator!=(Subsets const & i) const { return d_ != i.d_ || n_ != i.n_; }
Subsets & operator++() {
if (!(n_ = (n_ - d_) & d_)) d_ = 0;
return *this;
}
T operator*() const { return n_; }
private:
T d_, n_;
};
template <typename T>
inline Subsets<T> make_subsets(T t) { return Subsets<T>(t); }
int main(int /*argc*/, char * argv[]) {
int d = atoi(argv[1]);
for (auto i : make_subsets(d))
std::cout << i << "\n";
}
I've made it quite general in case you want to work with, e.g., uint64_t.
One option would be to use a for loop that always runs at least once, such as this:
for (bool once = true; once? (once = false, true) : (n = (n - d) & d); )
// loop body
On the first iteration, the once variable gets cleared and the expression evaluates to true, so the loop executes. From that point forward, the actual test-and-step logic controls the loop.
From here, rewriting this to a macro should be a lot easier.
Hope this helps!
You can do a multiline macro that uses an expression, like this:
#define macroenum(n, d, expr ) \
n = 0; \
do { \
(expr); \
} while (n = (n -d) & d) \
; \
int main(int argc, const char* argv[])
{
enumerateAllSubsets(33);
int n;
macroenum(n, 33, cout << n << ",");
}
As others have mentioned this will not be considered very clean by many - amongst other things, it relies on the variable 'n' existing in scope. You may need to wrap expr in another set of parens, but I tested it with g++ and got the same output as enumerateAllSubsets.
It seems like your goal is to be able to do something like enumerateAllSubsets but change the action performed for each iteration.
In C++ you can do this with a function in the header file:
template<typename Func>
inline void enumerateAllSubsets(unsigned char d, Func f)
{
unsigned char n = 0;
do { f(n); } while ( n = (n - d) & d );
}
Sample usage:
enumerateAllSubsets(33, [](auto n) { cout << binaryPrint(n) << ','; } );

Prefix recursion notation in c++

I was looking for recursive solution for evaluating expression in Polish prefix notation, didn't find, but i found pseudo code for that and I wanted to translate it to the C++ but it is hard. I wrote BIG LETTERS where I don't know how to do it. Please correct me I am java guy and for me C++ is big mess, but can't help it.
int preEval(stack<string> stos){
string el = "";
if(stos.empty()){
return 0;
}else if(stos.top() IS VALUE){
string el = stos.top();
stos.pop();
return atoi(el.c_str());
}else if(stos.top() IS OPERATOR){
int x = preEval(stos);
int y = preEval(stos);
return x OPERATOR y;
}
return 0;
}
EDIT
When I have expression like / 10 5 Should stack suppose to have elements(from top) / 10 5, or 5 10 / ? Just asking because if I want it in / 10 5 I have to read string somehow backwards.
I think, a better solution would be to split the work into 2 stages: lexing and parsing.
At the lexing stage, you classify each token to see whether it's an operator (+, -, etc.) or a constant, or maybe a variable. Then you pack the parsed entity into a structure containing the type and additional information.
At the parse stage, which is presented by your code, you work not with strings, but with structures. Looking at the structure, you can easily find out its type. (It can be either a field inside the structure or a structure's type if you choose to build a hierarchy of structures derived from a common base.)
Actually, the logic should be the same in both Java and C++.
If you have functions like these:
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <iostream>
#include <stack>
#include <string>
using std::stack;
using std::string;
using std::cerr;
enum Operator {
operator_none,
operator_plus,
operator_minus
};
Operator tokenOperator(const string &token)
{
if (token=="+") return operator_plus;
if (token=="-") return operator_minus;
return operator_none;
}
int applyOperator(Operator op,int x,int y)
{
switch (op) {
case operator_plus: return x+y;
case operator_minus: return x-y;
case operator_none:
break;
}
assert(false);
return 0;
}
bool isValue(const string &token,int &output_value)
{
char *end = 0;
errno=0;
output_value = strtol(token.c_str(),&end,10);
if (errno!=0) return false;
return *end=='\0';
}
bool isOperator(const string &token,Operator &output_operator)
{
output_operator = tokenOperator(token);
return output_operator!=operator_none;
}
Then preEval can be implemented like this:
int preEval(stack<string> &stos)
{
if (stos.empty()) return 0;
string el = stos.top();
stos.pop();
int value = 0;
Operator op = operator_none;
if (isValue(el,value)) return value;
if (isOperator(el,op)) {
int x = preEval(stos);
int y = preEval(stos);
return applyOperator(op,x,y);
}
return 0;
}
#include <string>
#include <map>
using namespace std;
bool is_value(string s) {
return s.find_first_not_of("0123456789") == string::npos;
}
int do_add(int x, int y) {
return x + y;
}
int do_subtract(int x, int y) {
return x - y;
}
// etc.
typedef int (*binary_op)(int, int); // Give this function pointer type a nice name
map<string, binary_op> ops;
// Somewhere before the preEval() is ever called
ops["+"] = do_add;
ops["-"] = do_subtract; // etc.
binary_op lookup_op(string s) {
map<string, binary_op>::const_iterator it = ops.find(s);
if (it != ops.end()) {
return *it;
} else {
return NULL;
}
}
Now, instead of separately testing whether the token is an operator and later performing that operator, use a single function call to get a pointer to the operator function that needs to be called (if the token is an operator) or NULL otherwise. I.e.:
}else if(stos.top() IS OPERATOR){
int x = preEval(stos);
int y = preEval(stos);
return x OPERATOR y;
}
becomes
} else {
binary_op op = lookup_op(stos.top());
if (binary_op != NULL) {
stos.pop(); // This fixes the bug I mentioned in my top comment
int x = preEval(stos);
int y = preEval(stos);
return op(x, y);
} else {
syntax_error();
}
}