How can I identify if the number is complex in C++?
Is there any built in function like this?:
isComplex(1)->false
C++ is a strongly typed language, and the literal 1 is always an int.
The determination you ask about might be relevant when converting text... isComplex("1"), for that you can attempt streaming:
std::istringstream iss(some_text);
std::complex<double> my_complex;
char c;
if (iss >> my_complex && // conversion possible...
!(iss >> c)) // no unconverted non-whitespace characters afterwards
...use my_complex...
else
throw std::runtime_error("input was not a valid complex number");
Separately, if you're inside a template and not sure whether a type parameter is std::complex, you can test with e.g. std::is_same<T, std::is_complex<double>>::value, for example:
#include <iostream>
#include <complex>
#include <type_traits>
using namespace std;
double get_real(double n) { return n; }
double get_real(const std::complex<double>& n) { return n.real(); }
template <typename T>
std::complex<double> f(T n)
{
if (std::is_same<T, std::complex<double>>::value)
return n * std::complex<double>{1, -1} + get_real(n);
else
return -n;
}
int main()
{
std::cout << f(std::complex<double>{10, 10}) << '\n';
std::cout << f(10.0) << '\n';
}
Output:
(30,0)
(-10,0)
See the code here.
For more complicated functions, you may want to create separate overloads for e.g. double and std::complex<double>, and/or float and std::complex<float>, long double etc..
Related
int testcases;
cin >> testcases;
Is there a way to shorten the above to one line? Or more generally, can anyone provide me a good resource where I can read about code shortage that doesn't necessarily affect the readability?
There isn't a whole lot to shorten there; however if you were going to be writing many instances of the above, you could write a helper-function like this:
int readInt()
{
int i;
cin >> i;
return i;
}
... then your many instances could be just one line apiece:
int testcases = readInt();
Building on Jeremy's idea, you could make a function template that creates and reads into many variables at once:
#include <iostream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
template<class... Types, size_t... I>
void readthem(std::istream& is, std::tuple<Types...>& rv, std::index_sequence<I...>) {
// A C++17 fold expression
(is >> ... >> std::get<I>(rv));
}
template<class... Types, class Indices = std::make_index_sequence<sizeof...(Types)>>
auto readvars(std::istream& is) {
std::tuple<Types...> rv; // A tuple consisting of the types you want
readthem(is, rv, Indices{});
if(not is) throw std::runtime_error("Input failed");
return rv;
}
int main() {
// read an int, a double and a std::string
auto[i, d, s] = readvars<int, double, std::string>(std::cin);
std::cout
<< i << '\n'
<< d << '\n'
<< s << '\n';
}
I have the following code:
#include<iostream>
using namespace std;
void saludo();
void despedida();
int main(){
void (*Ptr_Funciones[2])() = {saludo, despedida};
(Ptr_Funciones[0])();
(Ptr_Funciones[1])();
return 0;
}
void saludo(){
cout<<"\nHola mundo";
}
void despedida(){
cout<<"\nAdios mundo"<<endl<<endl;
}
Based on this, a few questions were generated which I investigated before asking but did not fully understand.
The questions are:
How do I make an array of functions, if they are of a different type?
I know that in C ++ this notation is used for undetermined parameters: (type var ...) The
thing is, I don't know how to interact with them inside the function.
If questions 1 and 2 are possible, can these points be combined when creating function
arrays?
I really have investigated. But I can't find much information, and the little I did find I didn't understand very well. I hope you can collaborate with me.
Thank you very much.
How do I make an array of functions, if they are of a different type?
You can, but you don't want to. It doesn't make semantic sense. An array is a collection of the same kind of thing. If you find that you need to make a collection of different kinds of things, there are several data structures at your disposal.
I know that in C++ this notation is used for undetermined parameters: (type var ...) The thing is, I don't know how to interact with them inside the function.
Here's how you can use the syntax you mention. They're called variadic functions.
If questions 1 and 2 are possible, can these points be combined when creating function arrays?
Erm, I can't imagine why/when a combination of these two would be needed, but out of intellectual curiosity, awayyy we go...
A modified version of the code from the reference link above that kinda does what you want (i've used a map instead of an array, cuz why not):
#include <iostream>
#include <cstdarg>
#include <unordered_map>
template<typename T>
using fooptr = void (*) (T *t...);
struct A {
const char *fmt;
A(const char *s) :fmt{s} {}
};
struct B : public A {
B(const char *s) : A{s} {}
};
void simple_printf(A *a...)
{
va_list args;
auto fmt = a->fmt;
va_start(args, a);
while (*fmt != '\0') {
if (*fmt == 'd') {
int i = va_arg(args, int);
std::cout << i << '\n';
} else if (*fmt == 'c') {
// note automatic conversion to integral type
int c = va_arg(args, int);
std::cout << static_cast<char>(c) << '\n';
} else if (*fmt == 'f') {
double d = va_arg(args, double);
std::cout << d << '\n';
}
++fmt;
}
va_end(args);
}
int main()
{
A a{"dcff"};
B b{"dcfff"};
std::unordered_map<size_t, fooptr<struct A>> index;
index[1] = simple_printf;
index[5] = simple_printf;
index[1](&a, 3, 'a', 1.999, 42.5);
index[5](&b, 4, 'b', 2.999, 52.5, 100.5);
}
This still really doesn't do what you wanted (i.e., give us the ability to choose from different functions during runtime). Bonus points if you understand why that's the case and/or how to fix it to do what you want.
Use a type alias to make things readable:
Live On Coliru
using Signature = void();
Signature* Ptr_Funciones[] = { saludo, despedida };
Prints
Hola mundo
Adios mundo
More flexible:
You can also use a vector:
Live On Coliru
#include <iostream>
#include <vector>
using namespace std;
void saludo() { cout << "\nHola mundo"; }
void despedida() { cout << "\nAdios mundo" << endl << endl; }
int main() {
vector Ptr_Funciones = { saludo, despedida };
Ptr_Funciones.front()();
Ptr_Funciones.back()();
}
Prints the same.
More Flexibility: Calleables of Different Types
To bind different types of functions, type-erasure should be used. std::function helps:
Live On Coliru
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
void saludo(int value) { cout << "\nHola mundo (" << value << ")"; }
std::string despedida() { cout << "\nAdios mundo" << endl << endl; return "done"; }
int main() {
vector<function<void()>>
Ptr_Funciones {
bind(saludo, 42),
despedida
};
Ptr_Funciones.front()();
Ptr_Funciones.back()();
}
Prints
Hola mundo (42)
Adios mundo
Here is one solution that is possible, whether it fits your needs I'm not sure.
#include <Windows.h>
#include <iostream>
void saludo()
{
std::cout << "\nHola mundo" << std::endl;;
}
void despedida()
{
std::cout << "\nAdios mundo" << std::endl;
}
void* fnPtrs[2];
typedef void* (VoidFunc)();
int main()
{
fnPtrs[0] = saludo;
fnPtrs[1] = despedida;
((VoidFunc*)fnPtrs[0])();
((VoidFunc*)fnPtrs[1])();
std::getchar();
return 0;
}
Given a variable defined as
T x;
where T is a generic arithmetic type (i.e. such that std::is_arithmetic<T>::value), is there a simple expression (e.g something from std::numeric_limits) that evaluates to the lowest value y expressible in T such that y > x?
(i.e. a kind of generalized increment..)
You can use std::nextafter.
Note that here I use std::numeric_limits<Floating>::max(), if you want meaningful behavior for infinities, you might want to modify the code.
#include <iostream>
#include <limits>
#include <cmath>
#include <type_traits>
#include <iomanip>
template <typename Floating,
std::enable_if_t<std::is_arithmetic_v<Floating> && !std::is_integral_v<Floating>, bool> = false>
Floating generic_next_val(Floating val) {
return std::nextafter(val, std::numeric_limits<Floating>::max());
}
template <typename Integral,
std::enable_if_t<std::is_arithmetic_v<Integral> && std::is_integral_v<Integral>, int> = 0>
Integral generic_next_val(Integral val) {
return static_cast<Integral>(val + static_cast<Integral>(1));
}
int main() {
int a = 1;
float f = 0.0f;
std::cout << std::setprecision(20) << generic_next_val(f) << " " << generic_next_val(a) << std::endl;
return 0;
}
The <cmath> header's std::nexttoward() will do this. It accepts a float, double, long double, or integral type, and returns the next value in the direction of its second parameter.
So, given code like this:
T my_val = some_input; // float, double, int, etc.
T next = std::nexttoward(my_val, std::numeric_limits<T>::max());`
If my_val were 1.0f, next would be the next biggest float after 1; if my_val were the integer 2, you would get 3, etc.
(Note that there's a lot of fine print here around numeric overflows, which the CppReference page linked above discusses. The long and short of it is don't pass std::numeric_limits<T>::max() in for the first parameter.)
#include <type_traits>
#include <limits>
#include <iostream>
/*
NOTE: Untested code for 'proof' of concept only.
This will cover all the is_integral<T> except bool.
This should probably be a set of free functions rather than a class
but just to check out the idea. Class should have constraints but as
the final implementation should probably be free functions they are
omitted.
*/
template<typename T>
class GLB{
public:
using limits = std::numeric_limits<T>;
static T get(const T& value){
return value == limits::max() ? limits::max() : value + static_cast<T>(1);
}
};
int main(int, char**){
std::cout << GLB<int>::get(42) << '\n';
std::cout << GLB<unsigned>::get(42) << '\n';
std::cout << GLB<wchar_t>::get(42) << '\n';
return 0;
}
/*
That was the easy bit now what about the floating point numbers.
*/
While fooling around with this scur3 pointed out that cmath can solve the floating point values. So some typing and some testing required.
I'm trying check if a string representation equals given integer. I'm meant to use stringstream for this in a function. I also have an operator= for this as well.
I'm a little confused on how to execute these together and if I'm missing something. This is the last bit to an assignment I have, this is just a small snippet of my whole program. I can't find many guides on this, and I sense they all direct me to atoi or atod, which I'm not allowed to use.
#ifndef INTEGER
#define INTEGER
using std::string;
class Integer
{
private:
int intOne;
string strOne;
public:
Integer() {
intOne = 0;
}
Integer(int y) {
intOne = y;
}
Integer(string x) {
strOne = x;
}
void equals(string a);
Integer &operator=(const string*);
string toString();
};
#endif
In this header I'm not sure what argument I'm to use for the = operator.
#include <iostream>
#include <sstream>
#include <string>
#include "Integer.h"
using namespace std;
Integer &Integer::operator=(const string*)
{
this->equals(strOne);
return *this;
}
void Integer::equals(string a)
{
strOne = a;
toString(strOne);
}
string Integer::toString()
{
stringstream ss;
ss << intOne;
return ss.str();
}
#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <string>
#include <ostream>
using namespace std;
#include "Menu.h"
#include "Integer.h"
#include "Double.h"
int main()
{
Integer i1;
i1.equals("33");
cout << i1;
}
Sorry if its a bad question I'm not too familiar with this type of assignment and will take any help I can get. Thanks.
you can use std::to_strig() that lets you convert from int to a string that represents the same number.
So if i understand correctly, you want to overload operator =, and that is a bad idea, since operator= is used for assignment not for comparison.
The correct operator signature is:
ReturnType operator==(const TypeOne first, const TypeSecond second) [const] // if outside of class
ReturnType operator==(const TypeSecond second) [const] // if inside class
Since you can't compare string to integer (they are different types), you need to write your comparisment function, since you don't have one i will write one for you:
bool is_int_equal_string(std::string str, int i)
{
std::string tmp;
tmp << i;
return tmp.str() == i;
}
Last but not least, you need to merge both of those, into one convenient operator:
// inside your Integer class
bool operator==(std::string value) const
{
std::stringstream tmp;
tmp << intOne;
return tmp.str() == ref;
}
Now you can use this operator, just like any other:
Integer foo = 31;
if (foo == "31")
cout << "Is equal" << endl;
else
cout << "Is NOT equal" << endl;
I hope this helps.
If you are allowed to use std::to_string then it would be the best.
Otherwise, you could create a function to handle the equality between the string and the integer with the use of std::stringstream:
Example:
bool Integer::equal(const string& str)
{
stringstream ss(str);
int str_to_int = 0;
ss >> str_to_int;
if (intOne == str_to_int)
return true;
else
return false;
}
Combine this with an if statement:
int main()
{
Integer i{100};
if (i.equal("100"))
cout << "true" << endl;
else
cout << "false" << endl;
}
Given a struct like this:
struct Foo
{
int x;
int y;
double z;
};
BOOST_FUSION_ADAPT_STRUCT(Foo, x, y, z);
I want to generate a string like this:
"{ int x; int y; double z; }"
I have seen how to print the values of a Fusion adapted struct, but here I need to print the types and names only.
How can I do this mostly simply? I'm not married to Boost.Fusion if there's a better way.
I think you can get something similar to what you want by making some slight modifications on the code in this answer. You can easily get the member name using boost::fusion::extension::struct_member_name but, as far as I know, you can't directly get the member type name. You can get the member type using boost::fusion::result_of::value_at (amongst other options) and I've chosen to use Boost.TypeIndex to get its name (in varying degrees of prettiness, depending on the compiler and the types in question). All of this is assuming that you actually need the Fusion adaptation, if you don't you can probably get a simpler approach that does only what you need.
Full Code
Running on WandBox (gcc)
Running on rextester (vc)
#include <iostream>
#include <string>
#include <boost/mpl/range_c.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/zip.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/type_index.hpp>
namespace fusion=boost::fusion;
namespace mpl=boost::mpl;
struct Foo
{
int x;
int y;
double z;
};
BOOST_FUSION_ADAPT_STRUCT(Foo, x, y, z);
struct Bar
{
std::pair<int,int> p;
std::string s;
};
BOOST_FUSION_ADAPT_STRUCT(Bar, p, s);
template <typename Sequence>
struct Struct_member_printer
{
Struct_member_printer(const Sequence& seq):seq_(seq){}
const Sequence& seq_;
template <typename Index>
void operator() (Index) const
{
std::string member_type = boost::typeindex::type_id<typename fusion::result_of::value_at<Sequence,Index>::type >().pretty_name() ;
std::string member_name = fusion::extension::struct_member_name<Sequence,Index::value>::call();
std::cout << member_type << " " << member_name << "; ";
}
};
template<typename Sequence>
void print_struct(Sequence const& v)
{
typedef mpl::range_c<unsigned, 0, fusion::result_of::size<Sequence>::value > Indices;
std::cout << "{ ";
fusion::for_each(Indices(), Struct_member_printer<Sequence>(v));
std::cout << "}\n";
}
int main()
{
Foo foo;
print_struct(foo);
Bar bar;
print_struct(bar);
}
You can use the following solution which is compiler dependent (tested on clang / gcc / MSVC) and only works if you have c++14 (should work with c++11 after slight modifications). It does what you want but there may be simpler solutions...
First part is a bit of compiler dependent code to demangle names return by std::type_info::name:
#include <string>
#if defined __GNUC__
#include <cxxabi.h>
std::string demangle (const char *name) {
int status = 0;
return abi::__cxa_demangle(name, 0, 0, &status);
}
#elif defined _WIN32
#include <Windows.h>
#include <DbgHelp.h>
std::string demangle (const char *name) {
char buffer[1024];
UnDecorateSymbolName(name, buffer, sizeof(buffer)/sizeof(*buffer), 0);
return buffer;
}
#endif
Then the "generic" part is quite short:
#include <array>
#include <tuple>
template <typename Tuple, size_t ...Idx>
std::string to_string (std::string vars, std::index_sequence<Idx...>) {
std::array<const char *, std::tuple_size<Tuple>::value> tnames{
typeid(typename std::tuple_element<Idx, Tuple>::type).name()...};
std::stringstream res;
res << "{ ";
for (auto s: tnames) {
size_t end = vars.find(',');
res << demangle(s) << ' ' << vars.substr(0, end) << "; ";
vars = vars.substr(end + 2);
}
res << '}';
return res.str();
}
#define CREATE(S, ...) struct: S { \
using Tuple = decltype(std::make_tuple(__VA_ARGS__)); \
std::string operator()() { \
return to_string<Tuple>(#__VA_ARGS__, \
std::make_index_sequence<std::tuple_size<Tuple>::value>{}); \
}; \
}
The idea is to create a class L that inherits from the specified class (e.g. Foo) and use the __VA_ARGS__ macro to expands the attribute names into std::make_tuple to obtain their types.
The to_string retrieves the std::type_info::name of each elements from a tuple and combines it with the attribute names (e.g. "x, y, z").
The CREATE macro returns a lambda that you can use as follow:
struct Foo {
int x;
int y;
double z;
};
CREATE(Foo, x, y, z) foo_xyz;
#include <iostream>
int main () {
std::cout << foo_xyz() << std::endl;
}
Output:
{ int x; int y; double z; }
Note: Since demangling is compiler dependent, you may not get exactly the same output with all compilers... For instance if you have a std::array<int, 10>:
gcc: std::array<int, 10ul>
clang: std::__1::array<int, 10ul>
msvc: class std::array<int,10>
Note: The usage is "complicated" to support MSVC: Initially I used a lambda inside CREATE so that you could do CREATE(Foo, x, y, z)() without having to bother creating a variable (I do not know how to generate correct name - see initial version of this answer), but MSVC do not like decltype(std::make_tuple(x, y, z)) inside the lambda... (probably a bug).