question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
72,786,137
72,787,001
How to compile C++ with CMake and -L/usr/include/mariadb/mysql -lmariadbclient
My C++ file includes the mariadb/mysql.h as following. #include <mariadb/mysql.h> I compile my C++ file as following. g++ -std=c++2a -g main.cpp -o main -lmariadbclient It works fine. But if I want to compile my C++ file using CMakeLists.txt. How to compile the C++ source code with -lmariadbclient using CMake?
It looks like major distros ship with a pkg-config file for mariadb called "mysqlclient.pc". So you can do: find_package(FindPkgConfig REQUIRED) pkg_check_modules(mariadb REQUIRED IMPORTED_TARGET "mysqlclient") and then link it to your program like so: target_link_libraries(my_program PUBLIC PkgConfig::mariadb)
72,786,319
72,786,654
What is (void (*) (void))((uint32_t)&__STACK_END)?
This is some startup file excerpt with interrupt vectors. #pragma DATA_SECTION(interruptVectors, ".intvects") void (* const interruptVectors[])(void) = { (void (*) (void))((uint32_t)&__STACK_END), resetISR, nmi_ISR, fault_ISR, ... /* More interrupt vectors */ void (* const interruptVectors[])(void) - is an array of function pointers that must contain function names, but I can't understand the (void (*) (void))((uint32_t)&__STACK_END) syntax. (void (*) (void)) looks like a pointer to a function that returns nothing, without arguments and doesn't have any name. Is it possible? (uint32_t)&__STACK_END is a pointer. And why are the function pointer and pointer together?
This looks like the interrupt vector table for an ARM processor or similar. The interrupt vector table contains the addresses of interrupt handlers, so it is essentially an array of function pointers. The first entry of this table is the initialization value for the stack pointer. It's obviously not a function pointer, but a data pointer, so some type conversion is needed. Not because the processor cares about types, but because C does. So &__STACK_END is presumable some pointer type which points to a data address at the end of the stack. This is then converted to a plain 32-bit number, and finally converted to a function pointer. It might have been possible to skip the first cast to uint32_t and cast directly from a data pointer to a function pointer, if the compiler supported it as an extension. But strictly speaking, in the C standard conversion from a data pointer directly to a function pointer is not legal, and cast to interger is necessary. There are also additional implemetation defined issues programmer must consider for this kind conversion to work: sizes of types and alignments must be compatible, there must not be trap representations, etc. This is all normal when working with code that is close to hardware.
72,786,965
72,787,744
How can I create objects of a nested class inside the parent class but in another header file?
I have a class Dmx with a nested class touchSlider. So before I had these classes in my main.cpp file and just created an object array of touchSlider within the Dmx class and it worked properly. How can I implement this here, with different header files? The compiler gives an error message: invalid use of incomplete type 'class Dmx::touchSlider' The object array is: touchSlider slider[10] = {50,130,210,290,370,50,130,210,290,370}; dmx.h // dmx.h #ifndef dmx_h #define dmx_h class Dmx { public: byte number; Dmx(byte numberA) { number = numberA; } void settingsDisplay(); class touchSlider; // declaration of nested class touchSlider slider[10] = {50,130,210,290,370,50,130,210,290,370}; }; #endif touchSlider.h // touchSlider.h #ifndef touchSlider_h #define touchSlider_h #include "dmx.h" class Dmx::touchSlider{ private: int pos; public: touchSlider(int posA){ pos = posA; } void printChannel(); }; #endif main.cpp // main.cpp #include "dmx.h" #include "touchSlider.h" Dmx dmx[10] = {Dmx(1), Dmx(2),Dmx(3), Dmx(4), Dmx(5), Dmx(6), Dmx(7), Dmx(8), Dmx(9), Dmx(10)}; void Dmx::settingsDisplay() { // do something } void Dmx::touchSlider::printChannel() { // do something } My previous code (that worked great) where both classes where in the same file looked like this: class Dmx { public: byte number; Dmx(byte numberA) { number = numberA; } void channelDisplay(){ } void settingsDisplay(){ } class touchSlider{ private: int pos; public: touchSlider(int posA){ pos = posA; } void setChannel(/* some arguments*/){ } void printChannel(); } }; touchSlider slider[10] = {50,130,210,290,370,50,130,210,290,370}; }; Dmx dmx[10] = {Dmx(1), Dmx(2),Dmx(3), Dmx(4), Dmx(5), Dmx(6), Dmx(7), Dmx(8), Dmx(9), Dmx(10)};
To be able to create an array: touchSlider slider[10] = {50,130,210,290,370,50,130,210,290,370}; You need the class definition available, because the compiler needs to know the size of the struct or class in use and if there's a suitable constructor available. You now have two options, either you provide the class definition in the header but implement the class within the source file like: // header: class Dmx { public: // ... class TouchSlider { public: // only DECLARE here: TouchSlider(int posA); void setChannel(/* some arguments*/); void printChannel(); }; }; // source: Dmx::TouchSlider::TouchSlider(int posA) : pos(posA) // note: prefer the initialiser list! { } void Dmx::TouchSlider::setChannel(/* some arguments*/) { } // ... or you hide away the implementation as you intended, but then you need to allocate the memory dynamically (this is the PImpl idiom) – at best with help of a std::unique_ptr: class Dmx { public: // ... private: class TouchSlider; // just declare std::unique_ptr<TouchSlider[]> sliders; }; Important (see cppreference), though: std::unique_ptr may be constructed for an incomplete type T, such as to facilitate the use as a handle in the pImpl idiom. If the default deleter is used, T must be complete at the point in code where the deleter is invoked, which happens in the destructor, move assignment operator, and reset member function of std::unique_ptr. I.e. you cannot implement e.g. your class' destructor in the header file either but need to do so in the source file as well – after the nested class' full definition – alike any function that might re-assign another array. The std::unique_ptr avoids necessity of manual memory management (see rules of three/five), on the other hand the class gets non-copiable (but you can work around by providing your own custom copy constructor and assignment while defaulting the move constructor and assignment).
72,787,017
72,788,152
Question about how to deal with a map of std::ostream objects into a class?
I am dealing with the following class attribute: std::map <std::ostream*, std::string> colors; I was wondering if there is a way to replace the pointer to ostream with a better data-structure? I read here that using a smart-pointer in this case is not a good idea and may be useless. The map would be used only to store information and to access it to do simple stuff, without modifying the ostream objects, but simply comparing, replacing or adding them to the map itself. Thanks in advance.
Raw pointers should not be used to manage lifetime of dynamically allocated objects. As you mention nothing that goes against that, I assume the std::ostreams are stored elsewhere while your pointers are just pointers: They point somewhere. They do not participate in ownership, and they do not need to. In particular that means you are sure that the pointers are not used after the objects lifetime ended. If all that applies then there is no need for smart pointers, because smart pointers are pointers that manage lifetime of objects. Raw pointers are pointers that do not participate in lifetime management. Before there were smart pointers there were owning raw pointers and non-owning raw pointers, and everything was much more messy. Nowadays, raw owning pointers can and should be avoided completely, and raw pointers and smart pointers aren't really alternatives to be considered for the same use cases. I was wondering if there is a way to replace the pointer to ostream with a better data-structure? This of course depends on what you want to use the map for. Considering ownership and managment of lifetime a raw pointer is just the right choice to signal that the pointer does not participate in ownership and there is no apparent need to replace them with something else.
72,787,135
72,787,448
How to explicitly tell compiler to choose exactly one parameter template during template pack expansion?
I'm trying using pack parameter template to fit some cases. I want to stop the template packed parameter expanding when there is only one parameter in the list. I want to use the typename explicitly when instancing the template, rather than using the typename to declare variables. Here is a minimal example: template <class T> void f() {} template <class T, class... Args> void f() { f<Args...>(); } int main() { f<int, int, double>(); return 0; } When compiling the code, I got the error: demo.cc: In instantiation of ‘void f() [with T = int; Args = {double}]’: demo.cc:6:13: required from ‘void f() [with T = int; Args = {int, double}]’ demo.cc:10:23: required from here demo.cc:6:13: error: call of overloaded ‘f<double>()’ is ambiguous 6 | f<Args...>(); | ~~~~~~~~~~^~ demo.cc:2:6: note: candidate: ‘void f() [with T = double]’ 2 | void f() {} | ^ demo.cc:5:6: note: candidate: ‘void f() [with T = double; Args = {}]’ 5 | void f() { | ^ I have read the following information from cppreferrence here: A pattern followed by an ellipsis, in which the name of at least one parameter pack appears at least once, is expanded into zero or more comma-separated instantiations of the pattern, where the name of the parameter pack is replaced by each of the elements from the pack, in order. It may be why the compiler can't decide whether to use void f() [with T = double] or void f() [with T = double; Args = {}] Can I stop the unpacking only by using template parameters rather than using input argument of function?
You can constrain the variadic version of the function with SFINAE to stop it from being called if the parameter pack is empty. That would look like template <class T, class... Args, std::enable_if_t<(sizeof...(Args) > 0), bool> = true> void f() { f<Args...>(); }
72,787,319
72,788,123
Why when I define the variable I defined in the for loop as global, it only writes once on the serial monitor?
as you can see below, I have defined the variable that I need to define in the for loop global, and this time the for loop only worked once, even though it was inside the void loop. Could you tell me why? char i = 'A'; void setup() { Serial.begin(9600); } void loop() { for ( ; i <= 'Z'; i++) Serial.print(i); delay(500); }
Since i is a global variable, it's value persists through each call to loop(). First time loop() is called: void loop() { // i == 'A', it's initial value for ( ; i <= 'Z'; i++) Serial.print(i); // Now, i == '[' because of i++ in the loop delay(500); } Second time loop() is called: void loop() { // i == '[', it's value from before, when loop finished the first time for ( ; i <= 'Z'; i++) Serial.print(i); // i == '[' because the loop is not entered because `[` is not lte `Z` delay(500); } And i stays equal to '[' since it does not get reset anywhere. You can reset it in the loop each time: for (i = 'A'; i <= 'Z'; i++) In your code, there is no reason I can see to make i global, so you can just declare it locally: for (char i = 'A'; i <= 'Z'; i++)
72,787,583
72,787,753
How do you initialize a vector bool matrix in C++?
I come from a mostly Java background (I use Java for algorithm challenges) , but I'm trying to practice my C++. This is my solution to a problem in which I need a vector bool matrix. class Solution { public: string longestPalindrome(string s) { string result = ""; vector<vector<bool>> dp(s.length()); for (int i = s.length() - 1; i >= 0; i--) { for (int j = 0; j < s.length(); j++) { dp[i][j] = s[i] == s[j] && (j - i < 3 || dp[i + 1][j - 1]); if (dp[i][j] && (result.empty() || j - i + 1 > result.length())) { result = s.substr(i, j + 1); } } } return result; } }; This solution works in Java actually. In Java, I just do: boolean[][] = new boolean[s.length()][s.length()]; As you see, I want to create a bool matrix in which the rows and columns are all of size s.length(). Unfortunately in my C++ solution, the compiler gives me this error: Line 86: Char 2: runtime error: store to null pointer of type 'std::_Bit_type' (aka 'unsigned long') (stl_bvector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_bvector.h:95:2 I am certain the problem is how I am initializing the vector bool matrix. What can I do to solve this issue ? How do I initialize the vector matrix ?
You can initialize a vector matrix like this: std::vector<std::vector<type>> vec_name{ rows, std::vector<type>(cols) }; ..which in your case is: std::vector<std::vector<bool>> dp{ s.length(), std::vector<bool>(s.length()) };
72,788,279
72,788,561
C4594 warning in visual studio
I wrote this code so I can understand more about c++ , I know that I get this warning because of the virtual inheritance in class B and class C is not virtual public inheritance ,and I know that this warning can go if I changed it . but what I don't understand is : why my code works and why it wont get this warning if I only made this change ---> class C :virtual public A and not made the change for both classes (C and B) : #include <iostream> using namespace std; class A { public: A() { cout << "A"; } A(const A&) { cout << "a"; } }; class B : virtual A { public: B() { cout << "B"; } B(const B&) { cout << "b"; } }; class C : virtual A { public: C() { cout << "C"; } C(const C&) { cout << "c"; } }; class D :B, C { public: D() { cout << "D"; } D(const D&) { cout << "d"; } }; int main() { D d1; D d2(d1); } : warning C4594: class 'D' can never be instantiated - indirect virtual base class 'A' is inaccessible : message : 'A' is a private base class of 'B'
Actually protected instead of public would suffice... Now assume your classes would not inherit virtually. What now happens is that any instance of B incorporates its own instance of A as well as does any instance of C. Both B and C call A's constructor already, an inheriting class D doesn't need to care for. This changes if virtual inheritance is introduced: Now the task of constructing the sole instance of A is delegated to the most derived class, which is D in given case. D now needs access to this common instance of A to be able to call it's constructor. This can occur via B or (!) via C – so it suffices if at least one of these provides at least protected access to that single instance – C in given case but could have been B as well.
72,788,311
72,788,966
Beast SSL Connection Graceful Shutdown
I am implementing an HTTPS client that tries to read information from the server. During its work the shutdown can be requested. It can be expresses in the following code: http::async_read( stream_, buffer_, res_, beast::bind_front_handler( &session::on_read, shared_from_this())); beast::get_lowest_layer( stream_ ).cancel(); As soon as the read is cancelled (on_read is called with operation cancel error) I call stream_.async_shutdown([t = shared_from_this()] ( beast::error_code ec ) { t->on_shutdown(ec); }); The shutdown finishes with the following error: application data after close notify The question is whether it is safe to ignore this error?
You can ignore this error. It happens if a server sends data concurrently - started sending an application data chunk asynchronousely right before has received close notify. stream_.async_shutdown([t = shared_from_this()] ( beast::error_code ec ) { if (ec ...) // add proper condition here ec = beast::error_code(success); t->on_shutdown(ec); }); I would also add some flag to session and set it before cancel, so session::on_read is not unexpected, can be ignored after shutdown.
72,789,515
72,789,581
c++ vector pointer reference issue
so I am having some issues with creating and using pointers for vectors. The problem I'm trying to solve with these pointers, is referencing data, without having an excess amount of code. This is how I'm currently defining the variables: // Data vectors std::vector<int16_t> amountData; std::vector<float> speedData; std::vector<int16_t> *pointerr = &amountData; // Should be auto, just testing I reference the data used multiple times through the code, which is why it would be easier if I could just have a pointer for the active data (data which I intend to use). I can't get it to work though, with using commands such as "*pointerr.size();" and such. I get the error: request for member 'size' in 'pointerr', which is of pointer type 'std::vector<short int>*' (maybe you meant to use '->' ?) and when using '*pointerr->size();', I get: invalid type argument of unary '*' (have 'std::vector<short int>::size_type {aka long long unsigned int}') I know its probably just me not fully understanding pointers/vectors, and that I'm probably missing something. Most of the other simallar questions don't really answer my problem (as far as I understand). I appreciate any sort of help/ideas and such, thanks in advance:)
You want pointerr->size() (without a *); the -> operator does the dereference of pointerr for you. Or alternatively, (*pointerr).size() which is equivalent. Your attempt of *pointerr.size() was close, but the . operator has higher precedence than *, and you have to derefence the pointer before you can apply . to the object it points to.
72,789,833
72,789,869
__stdcall in function paramater
does anybody know if is possible to add __stdcall (CALLBACK) in function parameter like this?: void Function(LRESULT CALLBACK (*f)(HWND, UINT, WPARAM, LPARAM)); It gives me following error: a calling convention may not be followed by a nested declarator Any solutions? Thx in advance <3
Put the calling convention inside the parenthesis. void Function(LRESULT (CALLBACK *f)(HWND, UINT, WPARAM, LPARAM));
72,790,232
73,557,091
PyArg_Parse for multiple returns of python on c++
I am calling python from c++ using PyObject_CallObject as the python return only a floating point number, i can get it by: float output_of_python; PyObject *pValue,*pArgs; pValue = PyObject_CallObject(pFunc, pArgs); PyArg_Parse(pValue, "f", &output_of_python); however, if python's returns 2 (return first,second), which format of PyArg_Parse(pValue... should i use to assign them to 2 c++ float variables? p/s: this one does not work: PyArg_Parse(pValue, "f,f", &output_of_python1,&output_of_python2);
i found it, post it here for anyone needs: In c++, in order to get 2 variables from return of python, it is float va1,va2; PyArg_ParseTuple(pValue, "ff", &va1,&va2);
72,790,741
72,790,802
Is there a better way to write these If-Statements?
I'm building a Random Character Generator in C++, and I have around 12 large blocks of if statements, like this: int wisdom = rand() % 18; cout << "\n"; if (wisdom == 0 || wisdom == 1) { cout << "Wisdom Score: 1\n"; cout << "Modifier: -5\n"; } else if (wisdom == 2 || wisdom == 3) { cout << "Wisdom Score: " << wisdom << "\n"; cout << "Modifier: -4\n"; } else if (wisdom == 4 || wisdom == 5) { cout << "Wisdom Score: " << wisdom << "\n"; cout << "Modifier: -3\n"; } else if (wisdom == 6 || wisdom == 7) { cout << "Wisdom Score: " << wisdom << "\n"; cout << "Modifier: -2\n"; } else if (wisdom == 8 || wisdom == 9) { cout << "Wisdom Score: " << wisdom << "\n"; cout << "Modifier: -1\n"; } else if (wisdom == 10 || wisdom == 11) { cout << "Wisdom Score: " << wisdom << "\n"; cout << "Modifier: +0\n"; } else if (wisdom == 12 || wisdom == 13) { cout << "Wisdom Score: " << wisdom << "\n"; cout << "Modifier: +1\n"; } else if (wisdom == 14 || wisdom == 15) { cout << "Wisdom Score: " << wisdom << "\n"; cout << "Modifier: +2\n"; } else if (wisdom == 16 || wisdom == 17) { cout << "Wisdom Score: " << wisdom << "\n"; cout << "Modifier: +3\n"; } else { cout << "Wisdom Score: 18\n"; cout << "Modifier: +4\n"; } I'm wondering, is there a better way to write this? Perhaps some type of function?
The better way is to not write chained ifs at all, but instead compute the value you care about. if (wisdom == 0) wisdom = 1; // Handle edge case treating 0 as 1 int modifier = wisdom / 2 - 5; cout << "Wisdom Score: " << wisdom << '\n'; cout << "Modifier: " << modifier << '\n'; Note that your calculation of int wisdom = rand() % 18; cannot produce 18 (and does produce 0, which you don't want), so you probably want to change it to: int wisdom = rand() % 18 + 1; // Result guaranteed to be 1-18 inclusive allowing you to simplify the code by removing the if (wisdom == 0) wisdom = 1; edge case. As another answer has already noted, rand is typically considered a bad API, so unless you're okay with biased results (e.g. slightly more low rolls than high rolls), you'll want to use modern C++ PRNG APIs (they're a little more work to set up, but trivial to use once you've done so, and they should avoid bias issues).
72,790,846
72,810,001
How do I efficiently select ports in multi process C++ linux servers?
I am using Amazon Gamelift to manage a c++ game server in an Amazon Linux 2 environment. This service will launch multiple instances of the same game server on the same machine at nearly the same time. These processes then report back when they are ready and what port they are bound to. What is the best way to attempt to bind to ports in the same range. For instance, I may choose to use between 1900 and 2100, but I may need 100 processes started up. How do I avoid a ton of collisions as these processes try to all bind to different ports at nearly the same time?
So I kind of hate that the only answer now is seemingly trying random ports within the unblocked range and retrying on collision, but that is all I seem to have to go on, so I implemented it. Here is the code if its helpful to anyone: bool MultiplayerServer::tryToBindPort(int port, int triesLeft) { ServerPort = port; cout << "Trying Port " << port << "\n"; triesLeft--; Server.Bind(port, [this, port, triesLeft](int errorCode, string errorMessage) { cout << errorCode << " : " << errorMessage << "\n"; cout << "Unable to bind to port: " + port << "\n"; if(triesLeft <= 0) { cout << "Ran out of tries to find a good port. Ending \n"; MyGameLiftServer.TerminateGameSession(); return; } tryToBindPort(getRandomPortInRange(), triesLeft); }); } int MultiplayerServer::getRandomPortInRange() { std::random_device rd; std::mt19937 mt(rd()); uniform_int_distribution<int> intDistro(MinPort, MaxPort); return intDistro(mt); } It seems to work good so far. I plan on opening about 500 ports and then have a max of around 150 server processes started. The chances of a long string of collisions happening then should be fairly small.
72,791,682
72,791,901
How to set pack of type by number?
I need some thing like this template<unsigned N> class Class { std::function<double(double, double ...)> _function1; // double N times std::function<double(double, ...)> _function2; // double N - 1 times }
Something along these lines, perhaps: template <typename R, typename T, size_t N> struct MakeFunctionType { template <size_t> using SwallowIndex = T; template <size_t... Is> static std::function<R(SwallowIndex<Is>...)> MakeFunctionTypeHelper(std::index_sequence<Is...>); using type = decltype(MakeFunctionTypeHelper( std::make_index_sequence<N>{})); }; Demo
72,791,713
72,792,127
Issues with infinite grid in OpenGL 4.5 with GLSL
I've been toying around with an infinite grid using shaders in OpenGL 4.5, following this tutorial here. Since the tutorial was written for Vulkan and a higher version of GLSL (I'm using 450 core), I had to move the vertices out of the vertex shader and into the application code. I'm rendering the quad using an element buffer, so my vertices ended up looking like this: std::vector<glm::vec3> points{glm::vec3{-1, -1, 0}, glm::vec3{1, -1, 0}, glm::vec3{1, 1, 0}, glm::vec3{-1, 1, 0}}; std::vector<GLuint> indices{0, 1, 2, 2, 3, 0}; // Render like this: glBindVertexArray(m_vao); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); I've managed to get the grid fully working, but it has two issues that I can't figure out: Objects that are drawn on top of the grid are getting clipped as the horizon moves up. This feels like z-fighting, but I'm not 100% sure why this would happen, seeing how the cube is being rendered after the grid. The underside of the grid is completely solid. This one also confuses me, because based on the fragment shader, the spaces in between the grid lines should be fully transparent... and yet they appear to be completely solid. Here are some sample images of what is happening: See that the cube is sliced in half. If I move the camera down, the rest of the cube will slowly appear. Conversely, if I move the camera up, the cube eventually disappears completely. This is the underside of the grid. I should be able to see the cube through the grid, but the grid behaves like a solid object. Does anyone have any ideas of what I'm doing wrong? Should I be enabling something in the application? For reference, I currently have this enabled: glEnable(GL_MULTISAMPLE); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Blending only works when the Depth Test is disabled or the objects are drawn from back to front. When the depth test is enabled (with its default function GL_LESS) closer objects win against more distant objects. Even if a fragment's alpha channel is 0, the fragment affects the depth buffer and the depth test. Thus, a more distant fragment is discarded if a closer, transparent fragment was previously drawn. You only have one object with transparent fragments, the grid. To solve your problem, just draw the grid after the cube: enable depth test draw solid objects (cube) enable blending draw grid
72,792,218
72,792,246
Why does main(int argc, char** argv) allow to override 'argv' parameters? Why and how does this work?
I found that main() allows overriding the argv[] parameters, because they are not const. #include <cstdio> int main(int argc, char** argv) { printf("%i %s\n", argc, argv[1]); argv[1][0] = 'X'; argv[1][4] = 'X'; printf("%i %s\n", argc, argv[1]); return 0; } And below is the result. It compiled and worked. At first, I expected some program crush like undefined behaviour. However, it may make sense that I may want to have a program that accept sensitive data as parameter, but after I use it, I would like to override it it immediately. Is this is the only reason or there are others? I would like to understand how this is working. I.e, where is the char** argv[] strings array located? How is it created and deleted? Etc.
On Linux/x86-64, the argc, argv, and env parameters are stored on the call stack by the kernel doing the execve(2) according to ABI conventions. See also this and the Linux Assembly HOWTO.
72,792,332
72,828,983
Check if Eigen Decomposition has been computed
How can I check to see if compute has previously been run on an Eigen::Solver? There is a protected member variable m_isInitialized in Eigen/src/EigenValues/EigenSolver.h but I don't see a getter for it. The code below shows an example of how you would create a matrix and compute the eigen decomposition on it. In my case, I have a reference/pointer to an Eigen::Solver so I don't know if it's been previously computed or not. EigenSolver.h docs EigenSolver.h source #include <Eigen/Eigenvalues> ... Eigen::Matrix<double, 3, 3> matrix; matrix << 1,2,3, 1,2,3, 1,2,3; Eigen::Solver<double, 3, 3> eigen_decomp; // This next line is the compute I'm referring to eigen_decomp.compute(matrix, /* computeEigenvectors = */ true); std::cout << eigen_decomp.eigenValues() << "\n";
Just for completeness, assuming you don't want to wait for a feature request for Eigen, the easiest wokaround is std::optional std::optional<Eigen::Solver<double, 3, 3>> eigen_decomp; if(! eigen_decomp) eigen_decom.emplace(matrix, /* computeEigenvectors = */ true); std::cout << eigen_decomp->eigenValues() << "\n";
72,792,423
72,792,940
How do you parse or save data from or to json files with c++?
I'm currently trying to gain some experience in coding with c++. I've already done some projects in other languages such as c# and other but I quickly realized that stuff is done quite different and that I got a lot to learn before I can start programming some more advanced projects. However, I'm quite experienced in reading and writing data storing file formats such as json or csv (I already succeeded in writing to a csv file in c++ tho). But as it turns out it seems like you can't just work with json files in c++ as easy as you may know it from other programming languages. I'd like to know if there are more common ways to create some easily accessable storage files that work in a similar way? (For better understanding:) As I already mentioned, I am aware that c++ is quite different from c# and a lot more difficult to learn because of its advanced syntax. I also worked on a beginning Project (which I thought would be possible to code) for a few hours where I want to log into some "accounts" whose (encrypted) login credentials are stored in a Json file (so I don't really think a code sample is necessary in this case). On the Internet I could find a lot of tutorials teaching how to work with simple text files, but I don't think that's gonna work for me because I plan to work with structured information formats that are easy to navigate. After watching a few tutorials and reading a lot of stackoverflow pages, I decided to ask myself. Thanks for your Help!
The reason you perceive other languages "simpler" to work with JSON is because those languages have built in class libraries to deal with JSON or they provide a near seamless dependency management framework that lets you very easily choose a 3rd party class library for the task. The C++ standard makes very little assumptions of the environment that will run the code and thus has a much more limited set of "built in" libraries. And even the word "built in" is a bit of a stretch in the case of C++, since you can make a perfectly decent C++ compiler without providing most of the standard template library. In managed languages like C# or Java we tend to blur the line between "language", "class libraries" and "runtime" and even the build system, so when we encounter a language that has a much clearer distinction between these concepts, we are surprised. Having said that, googling around a bit, you will find plenty of json parsing libraries for C++. I recommend trying out Niels Lohmann's json library. I have absolutely NO intention on implying that it is the "best" or "fastest" or "easiest" or anything of the sorts. Why I would recommend it is that you only have to include the header file and don't have to install and link to dlls, static or dynamic libraries, etc... Which is convenient if you only want a simple project without getting involved more deeply in building and linking and so on. But as I said earlier there are other solutions as well.
72,792,490
72,792,600
c++ Thread handling in class
I would like to create a object in which I can start a thread and have a function to join withe the created thread. Everything insight the object, so that the thread is a private component of the object. I have tried a bit and got those Results. Could some of you explain me what I have done wrong, and why I get this errors? A.h #include <thread> class A{ std::thread a; public: //this should be a void function std::thread startThread(); void join(); void (*threadFunction)() = nullptr; }; and the A.cpp #include "../header/A.h" std::thread A::startThread() { std::thread a((*threadFunction)); return a; } void A::join() { a.join(); } main.cpp void newFunc(){ std::cout<<"I'm a thread"<<std::endl; } int main(){ auto object = new A(); object->threadFunction = &newFunc; //Version 1) Error "terminate called without an active exception" object->startThread(); object->join(); /* Version 2) terminate called after throwing an instance of 'std::system_error' I'm a thread what(): Invalid argument */ auto value = object->startThread(); object->join(); //Version 3) I'm a thread auto value = object->startThread(); value.join(); } I don't see the difference. I have stored the thread in the object, so it is not lost... and when I store the return value and don't use it, its almost fine... but not really ... and directly join() is perfect ... I don't get it :D Please help me
std::thread A::startThread() { std::thread a((*threadFunction)); return a; } Does not interact with the member variable a, but it creates a new local variable std::thread object and then moves it to the result (unless the move is optimized out). The thread A::a always remains the default constructed one. A default constructed thread object is non-joinable, i.e. throws an exception on the call of std::thread::join. The only thread join can be called for without causing an exception is the thread object returned from the function. If you don't join the returned thread and its destructor runs (happens when you drop the temporary thread object returned (Version 1)), std::terminate shuts your program down. To make this work you need to move assign a newly created thread to the member variable and not return the thread object or just return a reference to it: void A::startThread() { a = std::thread(threadFunction); } or std::thread& A::startThread() { a = std::thread(threadFunction); return a; } I wouldn't recommend the second alternative, it drastically reduces your ability to enforce class invariants with regards to the thread lifecycle.
72,792,573
72,792,638
How do I cast the result of GetProcAddress to a function pointer without -fpermissive on mingw?
When I use -fpermissive I can just write something like this: void (*NtSetTimerResolution)(ULONG, bool, PULONG) = 0; int main() { NtSetTimerResolution = GetProcAddress(GetModuleHandle("ntdll.dll"), "NtSetTimerResolution"); ULONG pointless; NtSetTimerResolution(0x1388, 1, &pointless); return 0; } and it compiles and runs just fine with no runtime errors. How can I re-write this code to not include fpermissive?
You need an explicit cast: NtSetTimerResolution = reinterpret_cast <void (*)(ULONG, bool, PULONG)> (GetProcAddress(GetModuleHandle("ntdll.dll"), "NtSetTimerResolution")); You might still be violating strict aliasing rules here, but you can use -fno-strict-aliasing to get round that. And, inspired by @Remy's comment, this might be better still (DRY and all that): NtSetTimerResolution = reinterpret_cast <decltype (NtSetTimerResolution)> (GetProcAddress(GetModuleHandle("ntdll.dll"), "NtSetTimerResolution")); And I would recommend using nullptr in the initialisation, rather than 0, just for form's sake if nothing else.
72,793,403
72,794,857
Compiler Error C2440 IMAGE_NT_HEADERS64 cant be used to initialize an entity of type IMAGE_NT_HEADERS
So im writing a .dll for an injection, i ran into this problem and i have no clue abt how to fix tiError C2440 'initializing': cannot convert from 'const IMAGE_NT_HEADERS64 *' to 'const IMAGE_NT_HEADERS *' mod C:\Users\user\source\repos\mod\mod\Pattern.cpp 21 the code im using here: const IMAGE_NT_HEADERS* ntHeader = reinterpret_cast<const IMAGE_NT_HEADERS64*>(reinterpret_cast<const uint8_t*>(dosHeader) + dosHeader->e_lfanew); How can i fix this?
You are trying to assign a const IMAGE_NT_HEADERS64* to a const IMAGE_NT_HEADERS*. They are not the same type. Either cast the adjusted pointer to const IMAGE_NT_HEADERS*, or declare ntHeader as const IMAGE_NT_HEADERS64*.
72,793,413
72,797,252
Create custom Hash Function
I tried to implement an unordered map for a Class called Pair, that stores an integer and a bitset. Then I found out, that there isn't a hashfunction for this Class. Now I wanted to create my own hashfunction. But instead of using the XOR function or comparable functions, I wanted to have a hashfunction like the following approach: the bitsets in my class obviously have fixed size, so I wanted to do the following: example: for a instance of Pair with the bitset<6> = 101101, and the integer 6: create a string = "1011016" and now use the default hashfunction on this string because the bitsets have fixed size, each key would be unique how could I implement this approach? thank you in advance
To expand on a comment, as requested: Converting to string and then hashing that string would be somewhat slow. At least slower than it needs to be. A faster approach would be to combine the bit patterns, e.g. like this: struct Pair { std::bitset<6> bits; int intval; }; template<> std::hash<Pair> { std::size_t operator()(const Pair& pair) const noexcept { std::size_t rtrn = static_cast<std::size_t>(pair.intval); rtrn = (rtrn << pair.bits.size()) | pair.bits.to_ulong(); return rtrn; } }; This works on two assumptions: The upper bits of the integer are generally not interesting The size of the bitset is always small compared to size_t I think it is a suitable hash function for use in unordered_map. One may argue that it has poor mixing and a very good hash should change many bits if only a few bits in its input change. But that is not required here. unordered_map is generally designed to work with cheap hash functions. For example GCC's hash for builtin types and pointers is just a static- or reinterpret-cast. Possible improvements We can preserve the upper bits by rotating instead of shifting. template<> std::hash<Pair> { std::size_t operator()(const Pair& pair) const noexcept { std::size_t rtrn = static_cast<std::size_t>(pair.intval); std::size_t intdigits = std::numeric_limits<decltype(pair.intval)>::digits; std::size_t bitdigits = pair.bits.size(); // can be simplified to std::rotl(rtrn, bitdigits) in C++20 rtrn = (rtrn << bitdigits) | (rtrn >> (intdigits - bitdigits)); rtrn ^= pair.bits.to_ulong(); return rtrn; } }; Nothing will change for small integers (except some bitflips for small negative ints). But for large integers we still use the whole range of inputs, which might be of interest for pathological cases such as integer series 2^30, 2^30 + 2^29, 2^30 + 2^28, ... If the size of the bitset may increase, stop doing fancy stuff and just combine the hashes. I wouldn't just xor them to avoid hash collisions on small integers. std::hash<Pair> { std::size_t operator()(const Pair& pair) const noexcept { std::hash<decltype(pair.intval)> ihash; std::hash<decltype(pair.bits)> bhash; return ihash(pair.intval) * 31 + bhash(pair.bits); } }; I picked the simple polynomial hash approach common in Java. I believe GCC uses the same one internally for string hashing. Someone else may expand on the topic or suggest a better one. 31 is commonly chosen as it is a prime number one off a power of two. So it can be computed quickly as (x << 5) - x
72,793,495
72,793,567
How can I conditionally instantiate a member object to exhibit different behaviors depending on parent object?
I'm creating two objects of struct Player, each with a pawn container. I want this member to be defined with a different type depending on the Player object it is in, such that white.pawn.say() and black.pawn.say exhibit different behaviors. I've tried making WhitePawn and BlackPawn classes respectively, but I don't know of a factory design pattern that will allow me to instantiate member objects inside of a class. template <bool N> struct Pawn : public Piece { Pawn(U64 bb) : Piece(bb, 1) {}; }; template <> struct Pawn<0> : public Piece { void say(U64 x) { std::cout << "White pawns" << (x << 8) << "\n"; } }; template <> struct Pawn<1> : public Piece { void say(U64 x) { std::cout << "Black pawns" << (x >> 8) << "\n"; } }; struct Player { Pawn<color> pawn; // Expected compile-time constant expression Knight knight; Bishop bishop; Player(U64 p, U64 n, U64 b, bool color) : pawn(p) , knight(n) , bishop(b) {}; }; Player white( 0xFF000000000000, // pawns 0x4200000000000000, // knights 0x2400000000000000, // bishops 0 // color (white) ); Player black( 0xFF00, // pawns 0x42, // knights 0x24, // bishops 1 // color (black) ); I don't want to make Player a templated struct because it is called as a datatype later on. (int makeMove(Player& own, Player& enemy, U16 move) {...) Is there perhaps a way to make convert color to a constant expression so the compiler picks up on it? What's the best way to go about conditionally instantiating member objects of different types for different parent objects?
In your case, you're sure that there are only a given number of possible classes to choose from. This is called discriminated union in type systems and can be represented using a variant: Example code: struct Player { using PawnType = std::variant<Pawn<0>, Pawn<1>>; PawnType pawn; Knight knight; Bishop bishop; Player(U64 p, U64 n, U64 b, bool color) : pawn(color ? PawnType(Pawn<1>(p)) : PawnType(Pawn<0>(p)) , knight(n) , bishop(b) {}; }; Usage of pawn at this point requires writing a visitor: auto v = [&](auto&& pawn) { /* here goes the code accessing the actual Pawn<0> or Pawn<1> as pawn */ }; std::visit(v, player.pawn); E.g., instead of white.pawn.say(x);, you'd write: auto v = [&](auto&& actualPawn) { actualPawn.say(x); }; // this is a visitor std::visit(v, white.pawn); or, in case of such a small visitor, you can write in one line: std::visit([&](auto&& actualPawn) { actualPawn.say(x) }, white.pawn);
72,794,541
72,794,571
C++: copying a struct containing a std::vector efficiently
struct MZEntry { uint32_t machineID; bool mode; uint32_t area; uint32_t occupancy; using ZList = std::vector<uint32_t>; ZList authorisationZ; ZList blockExceptionZ; void clear() { machineID = 0; mode = false; area = 0; occupancy = 0; authorisationZ.clear(); blockExceptionZ.clear(); } MZEntry(){ clear(); } MZEntry(const MZEntry& mzEntry) { machineID = mzEntry.machineID; mode = mzEntry.mode; area = mzEntry.area; occupancy = mzEntry.occupancy; authorisationZ = mzEntry.authorisationZ; blockExceptionZ = mzEntry.blockExceptionZ; } }; I have the above structure in my code. Is there any benefit in me explictly declaring the copy-constructor? Let's say I have two variables MZEntry entry_1; MZEntry entry_2; if I do entry_1 = entry_2, will all the fields in the entry_2 get copied over to entry_1 including the vectors in it? Or is an explict copy-constructor required. Also is the above explict copy-constructor more efficient?
Declaring a copy constructor is a bad idea. Follow the rule-of-zero whenever you can and don't declare any copy/move constructor or assignment operator or destructor if you don't need custom destructor behavior because the class must manage some resource (and if it has to, always encapsulate that in a class specifically limited to that purpose, following the rule-of-five (or rule-of-three)). See also the C++ core guidelines. If you declare the copy constructor manually you inhibit the implicit definition of the move operations which would be used instead of a copy operations whenever possible to perform a move efficient move (rather than copy) of the members. For example MZEntry entry_1; MZEntry entry_2; /*...*/ entry_1 = std::move(entry_2); With the (implicit) move assignment operator, this allows entry_1 to just take over the memory which the vector members of entry_2 allocated. entry_2 will afterwards be in an unspecified state, but that is often fine. With the manual declaration of your copy constructor there won't be an implicit move assignment operator and the above would perform a full copy of all vector elements, the same as entry_1 = entry_2 would (with or without your manually defined copy constructor). Also, as mentioned in the question comments, your implementation of the copy constructor is actually worse performance-wise than the compiler-generated one, although it produces exactly the same behavior in the end. Similarly manual definition of the default constructor can be avoided by using in-class default member initializers instead and letting the compiler generate the default constructor from that. Calling .clear() on the vector members is redundant, since their default constructor will put them into an empty state anyway. Following the core guidelines you would have: struct MZEntry { uint32_t machineID = 0; bool mode = false; uint32_t area = 0; uint32_t occupancy = 0; using ZList = std::vector<uint32_t>; ZList authorisationZ; ZList blockExceptionZ; }; or alternatively (same result, matter of style): struct MZEntry { uint32_t machineID{}; bool mode{}; uint32_t area{}; uint32_t occupancy{}; using ZList = std::vector<uint32_t>; ZList authorisationZ{}; ZList blockExceptionZ{}; }; which lets the compiler generate all of the special member functions optimally. And if you need the clear method for some other purpose, it can then be implemented simply as void clear() { *this = MZEntry(); } or (again matter of style, same result): void clear() { *this = {}; } (Although your more explicit implementation of the clear member function as such might be more performant overall, since it won't cause memory of the vectors to be released, so that they may then reuse it later without new allocations.)
72,794,542
72,799,450
C++ Vulkan swapchain image_index vs current_frame
I am new to vulkan and following the vulkan-tutorial. In the chapter about swapchain and multiple frames in flight (frames_in_flight) there is something I dont understand. The variable imageIndex gets set by the function vkAcquireNextImageKHR uint32_t imageIndex; vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); and the variable currentFrame gets incremented each frame currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT; The imageIndex variable just gets used for the pImageIndices field of the VkPresentInfoKHR struct and for the indexing into the std::vector<VkFramebuffer>. All other vectors e.g. the VkFence or VkCommandBuffer are indexed with the currentFrame variable. What exactly is the defferece between imageIndex and currentFrame and why do I need to keep track of woth?
The difference is: vkAcquireNextImageKHR::imageIndex is "random". It can return any number in any order. The currentFrame changes strictly in round-robin fashion. Additionally the max-count may differ from swapchain image count. You would use vkAcquireNextImageKHR::imageIndex for things tied to a specific swapchain image. And you would use currentFrame for things tied to the sequence of frames (e.g. odd frames vs even frames).
72,794,831
72,795,029
Why std::vector<T>.resize() requires T has default ctor(with no parameter)?
I've got test code snippet: #include<vector> using namespace std; struct My { My(int i) {} My(My&&) noexcept {} My(const My&) {} }; int main() { vector<My> vm; vm.emplace_back(My(3)); vm.resize(3); // compile error return 0; } g++ compile with error: In file included from /usr/include/c++/9/vector:65, from defaultCtor.cpp:1: /usr/include/c++/9/bits/stl_construct.h: In instantiation of ‘void std::_Construct(_T1*, _Args&& ...) [with _T1 = My; _Args = {}]’: /usr/include/c++/9/bits/stl_uninitialized.h:545:18: required from ‘static _ForwardIterator std::__uninitialized_default_n_1<_TrivialValueType>::__uninit_default_n(_ForwardIterator, _Size) [with _ForwardIterator = My*; _Size = long unsig ned int; bool _TrivialValueType = false]’ /usr/include/c++/9/bits/stl_uninitialized.h:601:20: required from ‘_ForwardIterator std::__uninitialized_default_n(_ForwardIterator, _Size) [with _ForwardIterator = My*; _Size = long unsigned int]’ /usr/include/c++/9/bits/stl_uninitialized.h:663:44: required from ‘_ForwardIterator std::__uninitialized_default_n_a(_ForwardIterator, _Size, std::allocator<_Tp>&) [with _ForwardIterator = My*; _Size = long unsigned int; _Tp = My]’ /usr/include/c++/9/bits/vector.tcc:627:35: required from ‘void std::vector<_Tp, _Alloc>::_M_default_append(std::vector<_Tp, _Alloc>::size_type) [with _Tp = My; _Alloc = std::allocator<My>; std::vector<_Tp, _Alloc>::size_type = long unsi gned int]’ /usr/include/c++/9/bits/stl_vector.h:937:4: required from ‘void std::vector<_Tp, _Alloc>::resize(std::vector<_Tp, _Alloc>::size_type) [with _Tp = My; _Alloc = std::allocator<My>; std::vector<_Tp, _Alloc>::size_type = long unsigned int] defaultCtor.cpp:12:16: required from here /usr/include/c++/9/bits/stl_construct.h:75:7: error: no matching function for call to ‘My::My()’ 75 | { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); } | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ defaultCtor.cpp:6:5: note: candidate: ‘My::My(const My&)’ 6 | My(const My&) {} | ^~ defaultCtor.cpp:6:5: note: candidate expects 1 argument, 0 provided defaultCtor.cpp:5:5: note: candidate: ‘My::My(My&&)’ 5 | My(My&&) {} | ^~ defaultCtor.cpp:5:5: note: candidate expects 1 argument, 0 provided defaultCtor.cpp:4:5: note: candidate: ‘My::My(int)’ 4 | My(int i) {} | ^~ If resize() insolves reallocation of memory and moving objects, as I already defined My(My&&): internal implementation of STL shouldn't fail our client code, right? What's the semantic rule behind this? If resize() requires default ctor, then it actually creates some empty My objects, which might harm client code design: some client code base forbids trivial default ctors, by making it private and =default or even deleted. So STL resize() function actually breaks this kind of coding rule, any workaround for it?
The rule doesn't break your class semantics -- it actually enforces them. When you resize a vector, any new elements added are default-constructed. Since that is not allowed, then you may not resize a vector this way. Instead, you can use another overload of resize that accepts a value to initialize new elements with. See reference: void resize( size_type count, const value_type& value ); This relies on the ability to copy values. You defined a copy constructor already and you just need an assignment operator to complete that picture. The default assignment operator will use the copy constructor, but you must explicitly make it available. In C++11 that's easy. In older language editions, you must implement it explicitly. So, this will compile: #include<vector> using namespace std; struct My { My(int i) {} My(My&&) noexcept {} My(const My&) {} My& operator=(const My&) = default; }; int main() { vector<My> vm; vm.emplace_back(My(3)); vm.resize(3, My(0)); return 0; } In the above, any additional elements will be initialized with a copy of My(0). We have not broken the semantics of your design, because it explicitly allows copies. It should be mentioned that if you are allowing such values as My(0) (or whatever) to represent some kind of "empty" or "unused" state, then one wonders why you don't simply make the int parameter in the constructor optional (default to some value) in the first place. My(int i = 0) {} That effectively means you can default-construct the object and would not run into this problem in the first place.
72,795,189
72,795,239
How can I wrap std::format() with my own template function?
Note: this question uses C++20, and I'm using Visual Studio 2022 (v17.2.2). I would like to create a template function wrapper to allow me to use std::format style logging. The wrapper function will eventually do some other non-format related stuff that is not important here. Refer to the code below. Note that Log1() works fine, but feels clunky to use. Log2() is ok, but using std::vformat() loses compile-time checking of log format strings. What I really want to do is Log3(). Problem is that Visual Studio (v17.2.2) doesn't like this. Is there any way I can get this to work (without macros)? #include <iostream> #include <format> #include <string_view> // works fine: usage is clunky auto Log1(std::string_view sv) { std::cout << sv; } // works, but fmt string is checked at runtime - not compile time template<typename... Args> auto Log2(std::string_view fmt, Args&&... args) { std::cout << std::vformat(fmt, std::make_format_args(args...)); } // this doesn't work template<typename... Args> auto Log3(std::string_view fmt, Args&&... args) { std::cout << std::format(fmt, std::forward<Args>(args)...); } int main() { Log1(std::format("Hello, {}\n", "world!")); // ok - clunky Log2("Hello, {}\n", "world!"); // ok - no compile time checking of fmt string Log2("Hello, {:s}\n", 42); // ok - throws at runtime Log3("Hello, {}\n", "world!"); // ERROR: doesn't compile return 0; }
You need P2508 (my paper) to land, which exposes the currently exposition-only type std::basic-format-string<charT, Args...>, which will allow you to write: template<typename... Args> auto Log3(std::format_string<Args...> fmt, Args&&... args) Until then, you can just be naughty and use the MSVC implementation's internal helper for this, with understanding that they can rename this type at will at any point. template<typename... Args> auto Log3(std::_Fmt_string<Args...> fmt, Args&&... args)
72,795,259
72,818,340
Why is there a loop in this division as multiplication code?
I got the js code below from an archive of hackers delight (view the source) The code takes in a value (such as 7) and spits out a magic number to multiply with. Then you bitshift to get the results. I don't remember assembly or any math so I'm sure I'm wrong but I can't find the reason why I'm wrong From my understanding you could get a magic number by writing ceil(1/divide * 1<<32) (or <<64 for 64bit values, but you'd need bigger ints). If you multiple an integer with imul you'd get the result in one register and the remainder in another. The result register is magically the correct result of a division with this magic number from my formula I wrote some C++ code to show what I mean. However I only tested with the values below. It seems correct. The JS code has a loop and more and I was wondering, why? Am I missing something? What values can I use to get an incorrect result that the JS code would get correctly? I'm not very good at math so I didn't understand any of the comments #include <cstdio> #include <cassert> int main(int argc, char *argv[]) { auto test_divisor = 7; auto test_value = 43; auto a = test_value*test_divisor; auto b = a-1; //One less test auto magic = (1ULL<<32)/test_divisor; if (((1ULL<<32)%test_divisor) != 0) { magic++; //Round up } auto answer1 = (a*magic) >> 32; auto answer2 = (b*magic) >> 32; assert(answer1 == test_value); assert(answer2 == test_value-1); printf("%lld %lld\n", answer1, answer2); } JS code from hackers delight var two31 = 0x80000000 var two32 = 0x100000000 function magic_signed(d) { with(Math) { if (d >= two31) d = d - two32// Treat large positive as short for negative. var ad = abs(d) var t = two31 + (d >>> 31) var anc = t - 1 - t%ad // Absolute value of nc. var p = 31 // Init p. var q1 = floor(two31/anc) // Init q1 = 2**p/|nc|. var r1 = two31 - q1*anc // Init r1 = rem(2**p, |nc|). var q2 = floor(two31/ad) // Init q2 = 2**p/|d|. var r2 = two31 - q2*ad // Init r2 = rem(2**p, |d|). do { p = p + 1; q1 = 2*q1; // Update q1 = 2**p/|nc|. r1 = 2*r1; // Update r1 = rem(2**p, |nc|. if (r1 >= anc) { // (Must be an unsigned q1 = q1 + 1; // comparison here). r1 = r1 - anc;} q2 = 2*q2; // Update q2 = 2**p/|d|. r2 = 2*r2; // Update r2 = rem(2**p, |d|. if (r2 >= ad) { // (Must be an unsigned q2 = q2 + 1; // comparison here). r2 = r2 - ad;} var delta = ad - r2; } while (q1 < delta || (q1 == delta && r1 == 0)) var mag = q2 + 1 if (d < 0) mag = two32 - mag // Magic number and shift = p - 32 // shift amount to return. return mag }}
In the C CODE: auto magic = (1ULL<<32)/test_divisor; We get Integer Value in magic because both (1ULL<<32) & test_divisor are Integers. The Algorithms requires incrementing magic on certain conditions, which is the next conditional statement. Now, multiplication also gives Integers: auto answer1 = (a*magic) >> 32; auto answer2 = (b*magic) >> 32; C CODE is DONE ! In the JS CODE: All Variables are var ; no Data types ! No Integer Division ; No Integer Multiplication ! Bitwise Operations are not easy and not suitable to use in this Algorithm. Numeric Data is via Number & BigInt which are not like "C Int" or "C Unsigned Long Long". Hence the Algorithm is using loops to Iteratively add and compare whether "Division & Multiplication" has occurred to within the nearest Integer. Both versions try to Implement the same Algorithm ; Both "should" give same answer, but JS Version is "buggy" & non-standard. While there are many Issues with the JS version, I will highlight only 3: (1) In the loop, while trying to get the best Power of 2, we have these two statements : p = p + 1; q1 = 2*q1; // Update q1 = 2**p/|nc|. It is basically incrementing a counter & multiplying a number by 2, which is a left shift in C++. The C++ version will not require this rigmarole. (2) The while Condition has 2 Equality comparisons on RHS of || : while (q1 < delta || (q1 == delta && r1 == 0)) But both these will be false in floating Point Calculations [[ eg check "Math.sqrt(2)*Math.sqrt(0.5) == 1" : even though this must be true, it will almost always be false ]] hence the while Condition is basically the LHS of || , because RHS will always be false. (3) The JS version returns only one variable mag but user is supposed to get (& use) even variable shift which is given by global variable access. Inconsistent & BAD ! Comparing , we see that the C Version is more Standard, but Point is to not use auto but use int64_t with known number of bits.
72,795,407
72,866,581
How to keep track with std::forward_list 's first element?
I want to save an iterator of the first elements in a forward list as it and do some insert on the list. Then I want to erase the element at it. For example, in {20,30,40,50} and insert 10 at front. We get {10,20,30,40,50}. Then I want to erase 20, which means I want {10,30,40,50}. I tried to use before_begin() but it seems that it always point to the before of begin() of the list even after inserting. #include <bits/stdc++.h> using namespace std; int main() { forward_list<int> fl = { 20, 30, 40, 50 }; auto it = fl.before_begin(); fl.emplace_front(10); fl.erase_after(it); cout << "Element of the list are:" << endl; for (auto it = fl.begin(); it != fl.end(); ++it) cout << *it << " "; return 0; } Have 20,30,40,50 rather than 10,30,40,50. Is there any way to store a inerator that after ++, it will point to the begin element.
I solve this problem by adding an count, counting the number inserted at front and then move iterators from begin().
72,795,620
72,797,453
Why max() function in C++ giving error "no matching function for call to max"? Same code works if I do it explicitly with conditional statement
Both parameters of max are of type int, then why am I getting this error? Code is to find maximum depth of paranthesis in a string int maxDepth(string s) { stack<char> stac; int maxDepth = 0; for(auto &elem: s) { if(elem == '(') stac.push(elem); else if(elem == ')') { // maxDepth = max(maxDepth, stac.size()); // this doesn't work if(stac.size() > maxDepth) // this works, why? maxDepth = stac.size(); stac.pop(); } } return maxDepth; }
The reason why your compiler reject your call to std::max function is because it cannot deduce the type it need. Below is typical implementation of std::max template<typename _Tp> _GLIBCXX14_CONSTEXPR inline const _Tp& max(const _Tp& __a, const _Tp& __b) { // concept requirements __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) //return __a < __b ? __b : __a; if (__a < __b) return __b; return __a; } so both parameters receive _Tp but the way how template type deduction work is it evaluate the type for each of the template parameters and then compare if they match. and since one of your parameter are int and other is size_t which is unsigned int then you will have an error. When using the std::max what you can do. do cast so the parameters match: maxDepth = max(static_cast<size_t>(maxDepth), stac.size()); declare the type - which is also more readable: maxDepth = max<size_t>(maxDepth, stac.size()) Regarding your own program, i advice that change the type of maxDepth to size_t. and also for readability change the function name so it will not hold the same name as the variable. Hope it clear things out.
72,795,680
72,933,243
C++ Child Class Change Parent Class's Constructor
Modified the question a bit, thanks for your help on this! Is there a way to change Parent's constructor(e.g. change the value of protected field) when initialize the Child class. For example, I have two class - Base and Child below. In the Base constructor, string 'a' will be assigned to a protected field - 'a_' and 'val'(e.g. if a is "str", then a_ is 'a', val is 'a!'). There is a Child class that inherits class Base, and the constructor takes two arguments - string a and b. What I want is assign 'a+b+"!"' to val, e.g. a = "first ", b = "second", then a_ is "first", b_ is "second", c's value should be "first second!" class Base { public: explicit Base(string a) : a_(a), val(a + "!"){}; protected: string a_; string val; } class Child : public Base { public: explicit Child(String a, String b) : Base(a), b_(b)... protected: string b_; }
Thanks for all the reply. After reconsideration, I decided to extract a base class(class 'RealBase') from Base class and Child class. I feel the Child class should always obey the rules defined in parent class(e.g. same attributes, same method, etc.), otherwise, it's better to extract an abstract base class that contains the shared attributes. Here is the codes sample: class RealBase { public: RealBase(string a) : a_(a) {}; protected: string a_; } class Base : public RealBase { public: explicit Base(string a) : RealBase(a), val(a + "!"){}; protected: string val; } class Child : public RealBase { public: explicit Child(String a, String b) : RealBase(a), b_(b), val_(a+b+"!) {}; protected: string b_; string val; }
72,795,690
72,802,189
CGAL: How to get segmentation within polyline like CGAL Demo does?
I have a surface mesh with some sharp features. I want segment the mesh within the polyline composed of these features. In CGAL Demo, "Detect Sharp Features" function can fulfill my requirement, as the pic shows. Right now, I can get the polyline with domain.detect_features() which calls add_features_from_split_graph_into_polylines() internally. But how can i get the surface patch inside the polyline and cut them? CGAL Demo Result #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Mesh_triangulation_3.h> #include <CGAL/Mesh_complex_3_in_triangulation_3.h> #include <CGAL/Mesh_criteria_3.h> #include <CGAL/Polyhedral_mesh_domain_with_features_3.h> #include <CGAL/make_mesh_3.h> #include <CGAL/IO/output_to_vtu.h> #include <CGAL/IO/facets_in_complex_3_to_triangle_mesh.h> #include <CGAL/Surface_mesh.h> // Domain typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Mesh_polyhedron_3<K>::type Polyhedron; typedef CGAL::Polyhedral_mesh_domain_with_features_3<K> Mesh_domain; #ifdef CGAL_CONCURRENT_MESH_3 typedef CGAL::Parallel_tag Concurrency_tag; #else typedef CGAL::Sequential_tag Concurrency_tag; #endif // Triangulation typedef CGAL::Mesh_triangulation_3<Mesh_domain, CGAL::Default, Concurrency_tag>::type Tr; typedef CGAL::Mesh_complex_3_in_triangulation_3< Tr, Mesh_domain::Corner_index, Mesh_domain::Curve_index> C3t3; // Criteria typedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria; // To avoid verbose function and named parameters call using namespace CGAL::parameters; //Mesh typedef CGAL::Surface_mesh<K::Point_3> Mesh; int main(int argc, char*argv[]) { const char* fname = (argc > 1) ? argv[1] : "data/fandisk.off"; std::ifstream input(fname); Polyhedron polyhedron; input >> polyhedron; if (input.fail()) { std::cerr << "Error: Cannot read file " << fname << std::endl; return EXIT_FAILURE; } if (!CGAL::is_triangle_mesh(polyhedron)) { std::cerr << "Input geometry is not triangulated." << std::endl; return EXIT_FAILURE; } // Create domain Mesh_domain domain(polyhedron); // Get sharp features domain.detect_features(); // Mesh criteria Mesh_criteria criteria(edge_size = 0.025, facet_angle = 25, facet_size = 0.05, facet_distance = 0.005, cell_radius_edge_ratio = 3, cell_size = 0.05); // Mesh generation C3t3 c3t3 = CGAL::make_mesh_3<C3t3>(domain, criteria); // use cgal demo open vtu file can't get desired result // Output /*std::ofstream file("out.vtu"); CGAL::output_to_vtu(file, c3t3, CGAL::IO::ASCII);*/ //use function below can get mesh but doesn't contain segmentation info Mesh mesh; facets_in_complex_3_to_triangle_mesh(c3t3, mesh); std::ofstream output("mesh_smoothed.off"); output.precision(17); output << mesh; // Could be replaced by: // c3t3.output_to_medit(file); return EXIT_SUCCESS; }
The function sharp_edges_segmentation() should do something similar.
72,795,727
72,797,139
Boost ASIO SSL handshake failure
When attempting to securely connect to a remote IMAP server using Boost ASIO, the server handshake fails on every connection. The exception message reads: handshake: unregistered scheme (STORE routines) [asio.ssl:369098857] My code is below (url is a std::string_view containing the host URL): using boost::asio::ip::tcp; namespace ssl = boost::asio::ssl; using SSLSocket = ssl::stream<tcp::socket>; boost::asio::io_context context; ssl::context ssl_context(ssl::context::tls); SSLSocket socket(context, ssl_context); ssl_context.set_default_verify_paths(); tcp::resolver resolver(context); auto endpoints = resolver.resolve(url, "993"); boost::asio::connect(socket.next_layer(), endpoints); socket.set_verify_mode(ssl::verify_peer); socket.set_verify_callback(ssl::host_name_verification(url.data())); socket.handshake(SSLSocket::client); The code immediately throws an exception on the final line, which is a blocking synchronous handshake. The prior two lines set up host name verification, similar to how it's done in the official ASIO tutorial. These checks seem to be causing an issue, however, because when they are removed the handshake succeeds. Obviously, this is not a good solution. After stepping through some of ASIO's internals, I found that the last three lines of the above snippet could be replaced by: SSL_set_verify(socket.native_handle(), SSL_VERIFY_PEER, nullptr); socket.handshake(SSLSocket::client); and the same error occurs. SSL_set_verify is an OpenSSL function, and the fact that setting a null callback directly causes the same issue makes me think that the issue is with my system's OpenSSL environment and not ASIO or the host name verification callback. However, I have not been able to determine what exactly the error means and what could be causing it. Here is a list of things I have tried while troubleshooting: Load the system's certificate (.pem) file explicitly Thinking maybe ASIO and/or OpenSSL's were not able to load the right certificates to do the validation, I found my system's (a Mac) certificate file at /private/etc/ssl/cert.pem. I then inserted the following line: ssl_context.load_verify_file("/private/etc/ssl/cert.pem"); directly after set_default_verify_paths() is called. My program loads this certificate file without complaining, but it doesn't fix the handshake error. Use a different version of OpenSSL At first I was using Apple's system version of OpenSSL (which is really LibreSSL 2.8.3). I then rebuilt my code using the Homebrew package manager's version of OpenSSL (OpenSSL 3.0.4). This also did not fix the issue, even when I tried calling load_verify_file as in point 1. Sanity check using the OpenSSL command-line tool To make sure my network connection and URL/port number were correct, I tried connecting to the IMAP server over SSL using the following command: openssl s_client -connect my.url.com:993 -crlf -verify 1 and it worked fine, connecting to the IMAP server and enabling me to send/receive IMAP responses. Has anyone encountered similar issues when using OpenSSL and ASIO? I'm not very familiar with setting up an SSL/TLS connection, but I don't see what could be causing the problem. Thanks for your help!
Given that openssl s_client -connect my.url.com:993 -crlf -verify 1 succeeds there is not a lot that seems wrong. One thing catches my eye: I'd configure the context before constructing an SSL stream from it: ssl::context ssl_context(ssl::context::tls); ssl_context.set_default_verify_paths(); SSLSocket socket(context, ssl_context); Also, openssl likely uses SNI extensions: // Set SNI Hostname (many hosts need this to handshake successfully) if(! SSL_set_tlsext_host_name(socket.native_handle(), hostname.c_str())) { throw boost::system::system_error( ::ERR_get_error(), boost::asio::error::get_ssl_category()); } Finally, make sure the url string view contains correct data, notably that it's a valid hostname and null-terminated string. In this case I'd prefer to use a string representation that guarantees null-termination: Summary #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> using boost::asio::ip::tcp; namespace ssl = boost::asio::ssl; using SSLSocket = ssl::stream<tcp::socket>; int main() { boost::asio::io_context context; ssl::context ssl_context(ssl::context::tls); ssl_context.set_default_verify_paths(); SSLSocket socket(context, ssl_context); tcp::resolver r(context); std::string hostname = "www.example.com"; auto endpoints = r.resolve(hostname, "443"); boost::asio::connect(socket.next_layer(), endpoints); socket.set_verify_mode(ssl::verify_peer); socket.set_verify_callback(ssl::host_name_verification(hostname)); // Set SNI Hostname (many hosts need this to handshake successfully) if(! SSL_set_tlsext_host_name(socket.native_handle(), hostname.c_str())) { throw boost::system::system_error( ::ERR_get_error(), boost::asio::error::get_ssl_category()); } socket.handshake(SSLSocket::client); }
72,796,200
72,796,271
Not able to construct List Iterator from list.begin()
I am solving this problem https://leetcode.com/problems/queue-reconstruction-by-height/ This is the code that I wrote vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { list<vector<int>> dyn; sort(people.begin(), people.end(), [](vector<int> a, vector<int> b) { if (a[0] > b[0]) return true; else if (a[0] == b[0] && a[1]<b[1]) return true; return false; }); for (auto p: people) cout << p[0] << " " << p[1] << endl; for (int i = 0; i != people.size(); i++) { auto it = dyn.begin() + people[i][1]; dyn.insert(it, people[i]); } vector<vector<int>> ans(dyn.begin(), dyn.end()); return ans; } the test case is people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] I have not used lists that much. It gives error at auto it = dyn.begin() + people[i][1]; Line 17: Char 35: error: invalid operands to binary expression ('std::__cxx11::list<std::vector<int, std::allocator<int>>, std::allocator<std::vector<int, std::allocator<int>>>>::iterator' (aka '_List_iterator<std::vector<int, std::allocator<int>>>') and '__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type' (aka 'int')) auto it = dyn.begin() + people[i][1]; ~~~~~~~~~~~ ^ ~~~~~~~~~~~~ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_bvector.h:303:3: note: candidate function not viable: no known conversion from 'std::__cxx11::list<std::vector<int, std::allocator<int>>, std::allocator<std::vector<int, std::allocator<int>>>>::iterator' (aka '_List_iterator<std::vector<int, std::allocator<int>>>') to 'std::ptrdiff_t' (aka 'long') for 1st argument operator+(ptrdiff_t __n, const _Bit_iterator& __x) ^ I have dry run and at least in this particular test case, there is no out-of-bound possibility. Can anyone please suggest why this is happening.
std::list.begin() produces a BidirectionalIterator. As per the documentation at https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator, this type of iterator does not support the `+' operator. The only permissable operators are: ++: Move to next iterator location. --: Move to previous iterator location *--: Dereference the iterator (return the item) and then move to next. To achieve what you want, you will need the std::advance function, which takes a reference to the iterator (so you cannot pass list.begin() directly) and the number of steps you wish to take. It is roughly equivalent to the following loop (for a positive value): ListType::iterator it = list.begin(); for (int i = 0; i < count; ++i) ++it; So, to solve your immediate problem, your code needs to be: for(int i=0; i!=people.size(); i++) { auto it = dyn.begin(); std::advance(it, people[i][1]); dyn.insert(it, people[i]); } Alternatively, you may want to switch to an std::vector, which produces a RandomAccessIterator which can be used a lot like you would use an array pointer. (https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator)
72,796,284
72,796,361
'Type' does not refer to a value
I've checked other questions with similar errors, and they didn't seem comparable to the issue that I'm running into. I'm trying to instantiate an object and assign it in a constructor initialization list. However, on line 11, I'm getting an error saying 'Enemy' does not refer to a value. Furthermore, also on line 11, the log is giving me: error: expected primary-expression before 'Goblin' #include "Room.h" #include <iostream> #include "Enemy.h" #include "Chest.h" #include <string> Room::Room(Enemy enem_obj) :symbol{"_ "}, enemy{enem_obj}{ } Room::Room() : Room{Enemy Goblin{"Goblin"}}{ } void Room::print(std::ostream& os){ os << symbol; } #ifndef ROOM_H #define ROOM_H #include "I_Mapsquare.h" #include "Enemy.h" #include "Chest.h" #include <string> class Room : public I_Mapsquare { private: std::string symbol; Enemy enemy; Chest chest; public: Room(Enemy enem_obj); Room(); virtual ~Room() = default; virtual void print(std::ostream& os) override; }; #endif // ROOM_H #ifndef ENEMY_H #define ENEMY_H #include "I_Player.h" class Enemy : public I_Player { private: static constexpr const char* def_name = "Enemy"; static constexpr double def_hp = 20.0; static constexpr double def_def = 3.0; static constexpr double def_str = 2.0; static constexpr double def_dex = 1.0; static constexpr double def_wepdmg = 4.0; public: Enemy(std::string name = def_name, double hp = def_hp, double str = def_str, double defense = def_def, double dex = def_dex, double wepdmg = def_wepdmg); Enemy(std::string name); virtual ~Enemy() = default; virtual void attack(I_Player& obj) override; }; #endif // ENEMY_H #include "Enemy.h" #include <string> Enemy::Enemy(std::string name, double hp, double str, double defense, double dex, double wepdmg) : I_Player {name, hp, str, defense, dex, wepdmg} { } Enemy::Enemy(std::string name) : Enemy{name, 20.0, 3.0, 2.0, 1.0, 4.0} { } void Enemy::attack(I_Player& obj){ obj.takedmg(*this); } I'm sure this code is beyond horrendous, as this is the first independent program I've made, and I just wanted to try to make some sort of functional program using cpp. I'm also fairly certain that I'm trying to do some sort of horribly moronic operation here and that is why this isn't compiling. Pointing me in the right direction or to some material that would help me understand what is going on here would be helpful. Thank you all for your time!
Not sure why you are trying to name this object, just Room::Room() : Room{Enemy{"Goblin"}}{ } Temporaries (like Enemy{"Goblin"}) are objects without names.
72,796,784
72,796,923
cannot declare pointer to node& in c++
#include <bits/stdc++.h> using namespace std; class node{ public: int data; vector<node*> children; }; node* createTree(const vector<int>& nums){ stack<node*> st; node *root = new node(nums[0]); st.push(root); for(int i=1;i<nums.size();i++){ if(nums[i]==-1){ st.pop(); }else{ node *n = new node(nums[i]); st.top()->children.push_back(n); st.push(n); } } return root; } void display(node& *root){ cout << root->data << "->"; for(node& *child:root->children) cout << child->data << " "; cout <<"\n"; for(node& *child:root->children) display(child); } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); freopen("error.txt","w",stderr); #endif vector<int> nums = {10,20,-1,30,50,-1,60,-1,-1,4,-1,-1}; node *root = createTree(nums); display(root); return 0; } <source>:25:20: error: 'root' declared as a pointer to a reference of type 'node &' void display(node& *root){ ^ <source>:27:15: error: 'child' declared as a pointer to a reference of type 'node &' for(node& *child:root->children) ^ <source>:30:15: error: 'child' declared as a pointer to a reference of type 'node &' for(node& *child:root->children) ^ Here i am trying to implement a generic tree and when i try to compile the program i get an an error message saying that in display function i cannot declare a pointer to node&. I know that we cannot create a pointer to a reference since references do not have separate physical address, for example something like int* &b would not be permissible but int& *b would be permissible.Since here i have used node& *, i should not have got any error.Then why the program above is giving error?
You're correct about the pointer to a reference vs reference to a pointer but got the syntax wrong. Pointer to a reference is declared as: type&* obj Reference to a pointer is declared as: type*& obj Thus, the way that you think is "wrong", turns out to be correct: void display(node*& root) Edit: It's easier to imagine this way: (type*)& obj vs (type&)* obj
72,797,938
72,798,027
Creating an array of Semaphores C++
I am trying to create an array of semaphores, however my code is not running correctly so I am hoping to get some feedback on whether I am doing this correct. Creating the semaphore array as a global variable, I have: sem_t sems [10] = {}; Then filling the array (in main): sem_t sem0; sems[0] = sem0; sem_t sem1; sems[1] = sem1; sem_t sem2; sems[2] = sem2; ... And finally, initalizing the semaphores: sem_init(&sem0, 0, 1); sem_init(&sem1, 0, 0); sem_init(&sem2, 0, 0); ... I am referring to each semaphore by using &sems[threadID], where each threadID is between 0 and 9. It seems to work, but sem_wait() is being ignored and threads are running when they should be waiting. I am not great at C++ and am hoping for any indication of what I am doing wrong. Thank you in advance.
I don't know what you expect the middle part of your process to do. The additional variables you are declaring are independent semaphores from those in the array. Assignment will only copy the sem_t value (which is going to technically cause undefined behavior because you didn't initialize them). You can just pass a pointer to the sem_t in the array to sem_init: sem_init(&sems[0], 0, 1); sem_init(&sems[1], 0, 0); sem_init(&sems[2], 0, 0); If you can use C++20, consider using the C++ standard library's semaphore types instead. They have a proper C++ API instead of the C API you are using here. See https://en.cppreference.com/w/cpp/header/semaphore. Also, given that you have tagged pthreads, don't use pthreads directly if you are using C++11 or later (which you should) and use the standard library threading facilities instead, see https://en.cppreference.com/w/cpp/thread/thread.
72,798,527
72,798,714
A template function as a template argument
How to make the pseudo code below compile? #include <vector> template <class T> void CopyVector() { std::vector<T> v; /*...*/} template <class T> void CopyVectorAsync() { std::vector<T> v; /*...*/} template <template <class> void copy()> void Test() { copy<char>(); copy<short>(); copy<int>(); } int main() { Test<CopyVector>(); Test<CopyVectorAsync>(); } CopyVector and CopyVectorAsync are the functions that copy some vector of elements of type T using different algorithms. Test function calls a given copy functions with different element types. main function calls CopyVector and CopyVectorAsync for all the element types.
You can't have a template template parameter that accepts function templates, only class templates. Luckily we can make a class that looks rather like a function. #include <vector> template <class T> struct CopyVector { void operator()() { std::vector<T> v; /*...*/} }; template <class T> struct CopyVectorAsync{ void operator()() { std::vector<T> v; /*...*/} }; template <template <class> class copy> void Test() { copy<char>{}(); copy<short>{}(); copy<int>{}(); } int main() { Test<CopyVector>(); Test<CopyVectorAsync>(); }
72,798,545
72,798,866
std::unique_ptr custom deleter that takes two arguments
I am working on legacy code where memory allocation/deallocation done in traditional C style, but want to wrap it in a unique_ptr with a custom deleter. Consider a case where a 2 dimensional array is allocated by legacy code by calling calloc/malloc. I need to call the corresponding legacy deallocator function taking two parameters - pointer to array and size of the array. How to define a custom deleter that takes 2 parameters in this case, both will be passed only at the time of initializing the unique_ptr to take ownership of already allocated array? Thanks in advance. A simplified(yet contrived) example below: // function allocates memory and returns size of the buffer void legacyFunction(char **array, int *num) { char *p = (char *)calloc(5, sizeof(char)); for (auto i=0; i<5; ++i) { p[i] = 'a'; } *num = 5; *array = p; return; } int main() { char *array = nullptr; int numofElts = 0; legacyFunction(&array, &numofElts); // unique_ptr here to take ownership of array // custom deleter should take both pointer and size // the size could be any number based on business use case return 0; }
The deleter is an object. It can hold onto the size. struct LegacyDeleter { int size; void operator()(char** ptr) const noexcept { legacyDeallocate(ptr, size); } }; using legacy_ptr = std::unique_ptr<char*, LegacyDeleter>; int main() { legacy_ptr ptr(legacyAllocatorFunction(5), LegacyDeleter{5}); }
72,800,031
72,811,554
Serialise / deserialise std::optional with nlohmann-json
I wish to serialise a std::optional<float> with nlohmann-json. The example given here in the docs for a boost::optional seems very close to what I want, but I don't understand where my adaptation of it is going wrong. It seems that the deserialization component is working for me, but not the to_json aspect. Here is a minimal working example // OptionalSeriealisationTest.cpp //#define JSON_USE_IMPLICIT_CONVERSIONS 0 // Tried toggling this as per this comment // https://github.com/nlohmann/json/issues/1749#issuecomment-772996219 with no effect // (no effect noticed) #include <iostream> #include <optional> #include <nlohmann/json.hpp> namespace nlohmann { template <typename T> struct adl_serializer<std::optional<T>> { // This one is the issue static void to_json(json& j, const std::optional<T>& opt) { //if (opt == std::nullopt) { // j = nullptr; //} //else { // j = *opt; // this will call adl_serializer<t>::to_json which will // // find the free function to_json in t's namespace! //} if (opt) { j = opt.value(); } else { j = nullptr; } //NB same errors on the block above and the commented-out version } static void from_json(const json& j, std::optional<T>& opt) { if (j.is_null()) { opt = std::nullopt; } else { opt = j.get<T>(); // same as above, but with // adl_serializer<t>::from_json } } }; } using json = nlohmann::ordered_json; int main() { { // Seems ok, breakpoints on the from_json are hit json j; j["x"] = 4.0f; std::optional<float> x; j.at("x").get_to<std::optional<float>>(x); std::cout << x.has_value() << std::endl; std::cout << x.value() << std::endl; } { // Seems ok, breakpoints on the from_json are hit json j; j["x"] = nullptr; std::optional<float> x = 4.0f; j.at("x").get_to<std::optional<float>>(x); std::cout << x.has_value() << std::endl; //std::cout << x.value() << std::endl; } { // Won't compile on MSVC std::optional<float> x = 4.0; json j; j["x"] = x; } { // Won't compile on MSVC std::optional<float> x = 4.0; auto j = json({ "x", x }); } } The the to_json aspects will not compile in MSVC with the following error Severity Code Description Project File Line Suppression State Error (active) E0289 no instance of constructor "nlohmann::basic_json<ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType>::basic_json [with ObjectType=nlohmann::ordered_map, ArrayType=std::vector, StringType=std::string, BooleanType=bool, NumberIntegerType=int64_t, NumberUnsignedType=uint64_t, NumberFloatType=double, AllocatorType=std::allocator, JSONSerializer=nlohmann::adl_serializer, BinaryType=std::vector<uint8_t, std::allocator<uint8_t>>]" matches the argument list My specific asks are What's the fix? Why does this go wrong, when it seems so close to their example (boost::optional vs std::optional?) I note there are some quite lengthy discussions on the project about trouble incorporating std::optionals into the lib itself although I don't fully follow it and understand what it means for me in practice wanting to use std::optional as a third-party object. Some of the comments suggest approaches similar to what I have here work, so I hope it amounts to an oversight / silly mistake. Cheers!
This amounted to a dumb-one that's hard to spot because you're too worried its something esoteric. It's probabally quite specific to my mistake and wont likely be too much use to anyone finding this in the future though. Nonetheless, answer is as follows. My MWE about is a simplification of something in a real codebase. The codebase uses orderd_json specifically, but short hands it to json, i.e. using json = nlohmann::ordered_json; The class using the word json in nlohmann is a different, more general class. It looks like when serialising to an ordered_json it needs to be specifically for the type ordered_json and can't be automagically coaxed in. I.e. I should ha to_json taking type ordered_json as it's first argument. static void to_json(ordered_json& j, const std::optional<T>& opt) {/*...*/} rather than static void to_json(json& j, const std::optional<T>& opt) {/*...*/} It just turned out from_json worked anyway.
72,800,340
72,802,989
Can anyone give me code example of how multiple outputs of a single fragment shader is recorded and how to read them seperately(VULKAN)
Take the fragment shader as example: #version 450 //#extension GL_ARB_seperate_shader_objects : enable layout(location = 0) in vec3 color1; layout(location = 0) out vec4 outColor; layout(location = 1) out float outID; void main() { outColor = vec4(color1, 1.0); outID = 0.7; } Now can anyone tell me how to record both the outputs of the fragment shader. Now for a single output (outColor) i know it can be read in a image format of size (width, height, 4) but as we have two outputs here (outColor, outID) how exactly the are to be read.
Output at location 0 goes to color attachment 0. Output at location 1 goes to color attachment 1. Teh spec (Fragment Output Interface): A fragment shader output variable identified with a Location decoration of i is associated with the color attachment indicated by pColorAttachments[i]. VkSubpassDescription: Each element of the pColorAttachments array corresponds to an output location in the shader, i.e. if the shader declares an output variable decorated with a Location value of X, then it uses the attachment provided in pColorAttachments[X].
72,800,478
72,812,353
Change for loop increment/decrement value
Consider this code: # include <iostream> using namespace std; int main() { for(int i = 5; i>0;) { i--; cout <<i<<" "; } return 0; } The output of this code would be 4 3 2 1 0. Can I change the decrement/increment value? In detail, this means that the default decrement/increment value is 1. So you either minus 1 or add 1. Can I change it to minus 0.2 or add 1.3? If so, is there a way to tell the compiler that I want to change the -- value from 1 to 0.2 and still using the -- operator instead of changing it to -= 0.2?
d-- is shorthand for d -= 1, which is shorthand for d = d - 1. You should not read this as a mathematical equation, but as "calculate d - 1 and assign the result as the new value of d". #include <iostream> int main() { float day = 1.2; for(int i = 0; i < 5; i++) { day -= 0.2; std::cout << day; } return 0; } (I also removed using namespace std as it is bad practice). Note the second part of the for loop is a condition that keeps the loop going as long as it is true. In your case, i > 5 is false from the beginning (because 0 < 5) so the loop will never run. I assumed you meant i < 5 instead.
72,801,432
72,807,679
Why do I get the "child has a base whose type uses the anonymous namespace" warning here
I am trying to understand why I get a warning -Wsubobject-linkage when trying to compile this code: base.hh #pragma once #include <iostream> template<char const *s> class Base { public: void print() { std::cout << s << std::endl; } }; child.hh #pragma once #include "base.hh" constexpr char const hello[] = "Hello world!"; class Child : public Base<hello> { }; main.cc #include "child.hh" int main(void) { Child c; c.print(); return 0; } When running g++ main.cc I get this warning: In file included from main.cc:1: child.hh:7:7: warning: ‘Child’ has a base ‘Base<(& hello)>’ whose type uses the anonymous namespace [-Wsubobject-linkage] 7 | class Child : public Base<hello> | ^~~~~ This warning does not occur if the templated value is an int or if child.hh is copied in main.cc I do not understand what justifies this warning here, and what I'm supposed to understand from it.
The warning is appropriate, just worded a bit unclear. hello is declared constexpr, as well as redundantly const. A const variable generally has internal linkage (with some exceptions like variable templates, inline variables, etc.). Therefore hello in the template argument to Base<hello> is a pointer to an internal linkage object. In each translation unit it will refer to a different hello local to that translation unit. Consequently Base<hello> will be different types in different translation units and so if you include child.hh in more than one translation unit you will violate ODR on Child's definition and therefore your program will have undefined behavior. The warning is telling you that. The use of "anonymous namespace" is not good. It should say something like "whose type refers to an entity with internal linkage". But otherwise it is exactly stating the problem. This happens only if you use a pointer or reference to the object as template argument. If you take just the value of a variable, then it doesn't matter whether that variable has internal or external linkage since the type Base<...> will be determined by the value of the variable, not the identity of the variable. I don't know why you need the template argument to be a pointer here, but if you really need it and you actually want to include the .hh file in multiple .cc files (directly or indirectly), then you need to give hello external linkage. Then you will have the problem that an external linkage variable may only be defined in one translation unit, which you can circumvent by making the variable inline: inline constexpr char hello[] = "Hello world!"; inline implies external linkage (even if the variable is const) and constexpr implies const. If you only need the value of the string, not the identity of the variable, then since C++20 you can pass a std::array<char, N> as template argument: #include<array> #include<concepts> /*...*/ template<std::array s> requires std::same_as<typename decltype(s)::value_type, char> class Base { public: void print() { std::cout << s.data() << std::endl; } }; /*...*/ constexpr auto hello = std::to_array("Hello world!"); With this linkage becomes irrelevant. Writing Base<std::to_array("Hello world!")> is also possible. Before C++20 there isn't really any nice way to pass a string by-value as template argument. Even in C++20 you might want to consider writing your own std::array-like class specifically for holding strings. Such a class needs to satisfy the requirements for a structural type. (std::string does not satisfy them.) On the other hand you might want to widen the allowed template parameter types by using the std::range concept and std::range_iter_t instead of std::array to allow any kind of range that could represent a string. If you don't want any restrictions just auto also works.
72,802,168
72,823,464
Correctly abstracting the model from the view in an MVC Design Pattern
Context I am developing a simple CandyCrush lookalike game in C++ to familiarise myself more with Object Oriented Programming and Design Patterns, namely MVC. The general structure of the Model is as such : Idea My idea is to use a packaging logic, such that each GameComponent can be packaged into a primitive type representation. For example, a RedCandy object would be represented by "R" when packaged. When needed, the Control will package the model by packaging all the individual GameComponents and returning the results as a matrix of strings. This matrix is then communicated to the View. The string constants that represent each type of GameComponent are stored in a static class Constants with the following structure : class Constants { static const std::string RED; static const std::string BLUE; static const std::string GREEN; static const std::string YELLOW; static const std::string PURPLE; static const std::string ORANGE; static const std::string WALL; static const std::string BOMB; static const std::array< std::string, 6 > candies; public: static const std::string getRED() {return RED;} static const std::string getBLUE() {return BLUE;} static const std::string getGREEN() {return GREEN;} static const std::string getYELLOW() {return YELLOW;} static const std::string getPURPLE() {return PURPLE;} static const std::string getORANGE() {return ORANGE;} static const std::string randomCandy() {return candies[rand() % 6];} static const std::string getWALL() {return WALL;} static const std::string getBOMB() {return BOMB;} }; Thus, when the view interprets packaged Model, it refers to the Constants class. Conclusion Would this be the correct way of abstracting the model? Or am I overthinking it?
Yes I think you may be overthinking things! Adhering to MVC in the most generic sense just means that your data and logic (the model) are independent of the user interface code, which has the view and controller components. Additionally, you could think of individual objects as models, to be rendered in individual views: a player can be a model, represented by a name and a score, the list of available moves can be a model, shown as clickable images, etc. So in your specific example, the GameBoard class would be what models the state of the game, presumably as part of some Game class that governs the updates to its cells. As long as these classes are only concerned with game logic and others deal with, for example, loading images and responding to mouse clicks, then you have a MVC application. No further abstractions are inherently necessary. A bare minimum implementation could have something like: #include <memory> #include <string> #include <vector> struct GameComponent { virtual ~GameComponent() = default; virtual std::string type() const = 0; }; struct Candy : public GameComponent { std::string type() const override { return "candy_" + m_colour; } private: std::string m_colour {"red"}; }; using GameBoard = std::vector<std::vector<std::unique_ptr<GameComponent>>>; Of course you may choose to keep the additional classes shown in your scheme, but this should be enough of an interface to allow a corresponding view class to show nothing for nullptr elements, or use the string representation provided by type() to load an image. A basic design for views and controllers could be: struct BoardView { // functions to draw the board given model data, highlight something // under the mouse cursor, etc. private: GameBoard* m_model; }; struct Game; struct GameController { // functions to convert mouse input in the view to actions on the game, // tell the view to notify the player of invalid input, update view // after valid input, etc. private: Game* m_model; BoardView* m_view; }; This is just to show one example of a MVC-like structure. Different interpretations exist, such as that views should not communicate directly with models, but strictly get their input from controllers, making them another separate layer. But unless you are tied to one of those, you're allowed to be pragmatic and do whatever suits you! The real implementation would depend on the library you choose for designing the GUI. For example, I'm most familiar with Qt, which is a model/view framework with no separate controller concept. Therefore, Qt views do interact directly with their models.
72,802,341
72,802,585
OpenCV for C++: Passing matrix using std::ref() gives a 0x0 dimension matrix
this is my code snippet: for(int i = 0; i < numT; i++) { cv::Mat m2 = m1(cv::Range(get<0>(offsets[i]), get<1>(offsets[i])), cv::Range::all()); cout << m2.rows << " " << m2.cols << endl; // start threads threadsVec.push_back( thread(myFunction, ref(m2))); } I want to apply myFunction to subparts of the matrix in parallel. I checked the offsets and they are correct. I found out that if i print m2's dimensions (rows and columns) within the for it gives me the right dimensions for the matrix, while if I print it in myFunction method it gaves me 0 rows and 0 cols, what did I do wrong? How can I reach the right result? Also, if I pass directly the entire m1 matrix it works correctly.
m2 is destroyed at the end of your loop. Keeping a reference on it is undefined behavior. Just pass m2 by value instead. cv::Mat already behaves like a shared_ptr: copying a cv::Mat (and sub-matrices count as copies) won't deep-copy its internal buffer. So there's no need to use a reference on top of that. Just in case, a reminder that cv::Mat::forEach() exists and allows you to apply an operation to each pixel in your matrix in parallel without having to bother about parallelization details. However it's limited to per-pixel operations only... so if you need to work on sub-image regions it won't do it.
72,802,415
72,802,534
Define a template function according to class member variable with typetraits
I'm having some difficulties understanding a piece of code that is using typetraits. Suppose I want to define a template function that works on some classes that has a member variable k of type uint32_t. (Other classes will have another template function). The piece of code I have found is the following: template <typename T> auto has_member_k(std::uint32_t) -> decltype(std::declval<T>().k, std::true_type{}); template <typename T> auto has_member_k(...) -> std::false_type; template <typename MyType> typename std::enable_if<decltype(has_member_k<MyType>(0UL))::value, MyType>::type MyFunction(/*some args*/) { /*some code*/ } Here is what I understood: Regarding auto has_member_k(std::uint32_t) -> decltype(std::declval<T>().k, std::true_type{}); decltype is used to verify that the first expression is valid, the second is used to specify that decltype should return in case the first expression is valid. auto has_member_k(...) -> std::false_type; returns always the equivalent of false type if enable_if's condition (first part) is true, its result is the second argument, otherwise function declaration is ignored The final result is that the function is declared only if the class has a member k. My questions are the following: (Why) do we need the std::uint32_t as input argument of has_member_k? I guess it relates to the type of k but I am not sure how. Is the second has_member_k defined only to return a false type? I guess uint_32 is excluded somehow from the case of variadic arguments Why do I need typename preceding enable_if?
(Why) do we need the std::uint32_t as input argument of has_member_k? I guess it relates to the type of k but I am not sure how. Its a trick to be able to call either has_member_k(std::uint32_t) or has_member_k(...) (in case enable_if discards the first). When SFINAE does not kick in then both templates could be used for the call has_member_k<MyType>(0UL), but the first is chosen by overload resolution and there is no ambiguity. Is the second has_member_k defined only to return a false type? Yes. has_member_k<MyType>(0UL))::value is used for the enable_if and it needs to be either true or false. Why do I need typename preceding enable_if? Because enable_if< .... >::type is a dependant type (it depends on the template parameter). In a nutshell, the typename is needed to ensure the compiler that enable_if< whatever >::type is really meant to be a type (consider that in principle there could be specializations where type is a member but not a type). In newer code you'll find the alias template std::enable_if_t which does not need the typename. Concerning the points you did understand... [...] decltype is used to verify that the first expression is valid, the second is used to specify that decltype should return in case the first expression is valid. Its an application of the comma operator. For more details I refer you to How does the Comma Operator work auto has_member_k(...) -> std::false_type; returns always the equivalent of false type Note that there is no definition of has_member_k. decltype is only used to deduce the return type and for that no definition is needed. The function is never actually called. Its not an "equivalent" but it is std::false_type. if enable_if's condition (first part) is true, its result is the second argument, otherwise function declaration is ignored Exactly. If the condition is false then enable_if has no member alias called type. This is a substitution failure but not an error and the function is discarded. This is SFINAE (substitution failure is not an error).
72,802,456
72,808,646
Store iterator inside a struct
I need to read data from multiple JSON files. The actual reading of data is performed later in the code, after some initialization stuffs. For reasons beyond the scope of this question, I believe that it would beneficial for my application to store somewhere an iterator set to the first element of each JSON file. In this way, I would be able to iterate over each JSON file and read the i-th element from each of them, at later time. The issue: if I create the iterator and use it to parse data right away everything works. If I create the iterator, store it inside a struct and use later on, I get a read access violation. Following are some pieces of code to better explain my issue. First of all, here is a partial declaration of the structure holding info about a single JSON file: typedef struct _struct { ... boost::property_tree::ptree json_struct; boost::property_tree::ptree::iterator it; ... } json_handler; Just FYI, later on, I declare a container for holding multiple handlers: std::map<std::string, json_handler> mjh; The following works: json_handler cms; boost::property_tree::read_json(full_path, cms.json_struct); boost::property_tree::ptree &data = cms.json_struct.get_child("frames"); // current_msg.it = data.begin(); // If I do iterate over the json content here, everything works. for (boost::property_tree::ptree::iterator element = data.begin(); element != data.end(); element++) double time = element->second.get<double>("ST"); // The following line just inserts the current json_handler inside the map mjh.insert(std::pair<std::string,json_handler>(name, cms)); The following does not work: ... This is later in the code when it's time to use the data std::map<std::string, json_handler>::iterator it; for (it = mjh.begin(); it != mjh.end(); it++) { double _st = it->second.it->second.get<double>("ST"); std::cout << "ST: " << std::to_string(_st ) << std::endl; ... } The question: can I store an iterator inside a struct. If no, why?
You're storing iterators, but using them after they were invalidated. Reasons for invalidation are when the corresponding ptree node moved, was erased or destructed. Just store the ptree inside the struct, which makes sure the ptree's lifetime extends long enough. Of course, you will still need to make sure the node pointed to by the iterator is not erased from the ptree. On a side note, don't use Property Tree for JSON parsing. It has serious limitations. Use Boost JSON instead: https://www.boost.org/doc/libs/1_79_0/libs/json/doc/html/index.html It understands JSON correctly, is much faster and has a more user-friendly interface.
72,802,894
72,804,926
Nested concept types in templates
Consider the following template, intended on declaring some State::Machine: enum Strategy { Breadth, Depth, Heuristic, }; template<class Map, Strategy Strategy = Depth> struct Machine; If we would like to enforce some constraints on the Map type, so that implementations satisfy necessary concepts, we have: template <Range::Type Source, Comparable Constraint, class Result, Transition<Source, Constraint, Result> Transition, Range::Of<Transition> Transitions, Map<Constraint, Transitions> Map, Strategy Strategy = Strategy::Depth> class Machine { }; Where Source is some container like std::vector, Constraint is some comparable struct == struct -> bool, Transition is some lambda(Source) -> Product and Transitions is some container of Transition. Declaring this type is now exhausting: auto transition = [](std::string source) { return State::Product<std::string, State, State> { .source = source, .state = State::Start, .product = State::Start, }; }; static_assert(Transition<decltype(transition), std::string, State, State>); std::map<State, std::set<decltype(transition)>> map = { {State::Start, {transition}} }; State::Machine<std::string, State, State, decltype(transition), std::set<decltype(transition)>, decltype(map)> machine; Is there a way to have all the concepts be required with only one type parameter State::Machine<decltype(map)> machine; Similar to how it was before any concepts were required?
Most types expose their "subtypes". std::map has key_type and mapped_type for example. (You can create traits to extract template parameter if needed BTW, if type doesn't provide such typedef). Then you might use constraint on those sub-types, something like: template <typename Map, Strategy Strategy = Strategy::Depth> requires(Comparable<typename Map::key_type> && IsATransition<typename Map::mapped_type>) class Machine { // ... };
72,802,995
72,803,864
What does it means this error?" In template: call to deleted constructor of 'std::unique_ptr<InventoryElements>"
this is the class with all the methods. #include "InventoryElements.h" class Inventory{ public: explicit Inventory(int max) : MaxElements(max){ myInventory.resize(max); NumElements=0; } void suf_insert(unique_ptr<InventoryElements> element); void generic_insert(unique_ptr<InventoryElements> element, vector< unique_ptr<InventoryElements>>::iterator pos); void remove(unique_ptr<InventoryElements> element,vector< unique_ptr<InventoryElements>>::iterator pos); private: int MaxElements; vector<unique_ptr<InventoryElements>> myInventory; int NumElements; }; void Inventory::suf_insert(std::unique_ptr<InventoryElements> element) { if (NumElements < MaxElements){ myInventory.push_back(element); // here the error else std::cout<<"Ops.. your Inventory is full, remove an element first"<< endl; } and this is the implementation of the first method, a suf_insert, the error call to deleted constructor of 'std::unique_ptr", how can i solve this?
Because a std::unique_ptr can not be copied, you will need to move your unique_ptr into your vector. myInventory.push_back( std::move(element) ); // no more error After this line, element will no longer point to your element, as your std::vector will now contain the unique pointer.
72,803,180
72,804,299
Angles of a Point with X, Y, Z using GLM
I have two points, one represents the cursor(a cube) and another one represents the position of the Camera. Now to find out which face the camera is facing I have done something like this glm::vec3 direction = glm::normalize(cursorPos - cameraPos); float angle_x, angle_y, angle_z; angle_x = glm::dot(direction, vec3(1.0f, 0.0f, 0.0f)); // in terms of cosine angle_x = glm::acos(angle_x); // in terms of radians angle_x = glm::degrees(angle_x); // in terms of degrees angle_y = glm::dot(direction, vec3(0.0f, 1.0f, 0.0f)); // in terms of cosine angle_y = glm::acos(angle_y); // in terms of radians angle_y = glm::degrees(angle_y); // in terms of degrees angle_z = glm::dot(direction, vec3(0.0f, 0.0f, 1.0f)); // in terms of cosine angle_z = glm::acos(angle_z); // in terms of radians angle_z = glm::degrees(angle_z); // in terms of degrees bool x_45 = angle_x <= 45; bool x_135 = angle_x > 135; bool y_45 = angle_y <= 45; bool y_135 = angle_y > 135; bool z_45 = angle_z <= 45; bool z_135 = angle_z > 135; if (x_45) { std::cout << "facing left face\n"; } else if (x_135) { std::cout << "facing right face\n"; } else if (y_45) { std::cout << "facing up face\n"; } else if (y_135) { std::cout << "facing down face\n"; } else if (z_45) { std::cout << "facing front face\n"; } else if (z_135) { std::cout << "facing back face\n"; } Why do angles that are getting calculated only in the range (0, 180) with the axis? It's leading to calculated angles as: "Angle with x: 62.9398 Angle with y: 47.5 Angle with z: 125.464" Which should only be possible if the calculated angle range is in (0, 360)? What is happening right now( I assume) is that it's getting calculated without the consideration of another axis, as shown in the below image. I am sure this is the most brute way to do this, if anyone has other solution please tell. --Maybe something like converting that normalized vector in its quaternion rotation represtation and getting euler angels out of it?
You made this code hard to understand and maintain. Here is method which do not need large mind power. Just 6 vectors defining directions and trying find one which is closest to direction: Facing findOrientation(glm::vec3 direction) { struct FacingNormalizations { Facing facing; glm::vec3 v; }; constexpr std::array facings { FacingNormalizations { Facing::back, { 0, 0, 1 } }, FacingNormalizations { Facing::right, { 1, 0, 0 } }, FacingNormalizations { Facing::up, { 0, 1, 0 } }, FacingNormalizations { Facing::front, { 0, 0, -1 } }, FacingNormalizations { Facing::left, { -1, 0, 0 } }, FacingNormalizations { Facing::down, { 0, -1, 0 } }, }; auto r = std::max_element(facings.begin(), facings.end(), [direction](const auto& a, const auto& b) { return dot(direction, a.v) < dot(direction, b.v); }); return r->facing; } https://godbolt.org/z/nqjGbMK54 Note if you need to add some extra direction it is easy. If you like to make some direction more privileged, you should just make respective vector longer. Using C++20 ranges makes this code nicer.
72,804,066
72,804,429
Problems with Makefile and compiling a cpp file marks error in a function declared in other file
I have problems with my Makefile. I used the following structure to generate the .o files of each cpp file, but does not work (using c works without problems, I cant find what is the problem) %.o : %.cpp %.h g++ -c -Wall $< -o $@ And the error while compiling is a function is declared in a separated h and cpp file and added to the main file. But when I try to generate de .o file of main.cpp marks error in the function. The command I used to compile the main.cpp -> g++ -c main.cpp -o main.o The error that gives me is: main.cpp: In function ‘int main(int, char)’: main.cpp:9:9: error: ‘number’ was not declared in this scope9 | number(); This is the compiler that I used for it: g++ (Ubuntu 11.2.0-19ubuntu1) 11.2.0 Linux 5.15.0-40-generic Please, anyone could explain me if I'm doing wrong of something is left /*main.cpp*/ #include <iostream> #include "numb.h" using namespace std; int main(int argc, char* argv[]) { cout<<"Run"<<endl; number(); cout<<"end Run"<<endl; return 0; } /*end main.cpp*/ /*numb.cpp*/ #include <iostream> #include "numb.h" using namespace std; int number() { cout<<"Function"<<endl; return 117; } /*end numb.cpp*/ /*numb.h*/ #include <iostream> #define NUMB_H #ifndef NUMB_H int number(); #endif /*end numb.h*/
You got the header guard in the wrong order. Instead of: #define NUMB_H #ifndef NUMB_H It is supposed to be: #ifndef NUMB_H #define NUMB_H
72,804,375
72,804,752
Cross-platform binary in C++
I have read that a binary is the same for Windows and Linux (I am not sure if it has a different format). What are the differences between binaries for Linux and binaries for Windows (when speaking about format)? And if there are none, what stops us from making a single binary for both operating systems (make sure that I mean the last file where you can run and not the source code)? Since there are differences in the binary format, how are the operating systems themselves compiled? If I'm not mistaken Microsoft uses Windows to compile the next Windows version/update. How are these binaries executable by the machine (even the kernel is one of those)? Aren't they in the same format? (For such a low-level program.)
I have read that a binary is the same for Windows and Linux (not sure if it has a different format) Then you have read wrong. They are completely different formats. What are the differences between binaries for Linux and binaries for Windows (when speaking about format)? Windows: Portable Executable (PE) Linux: Executable and Linkable Format (ELF) And if there are none There are many differences. What stops us from making a single binary for both operating systems? The fact that different OSes require different binary formats for their respective executable files. Since there are differences in the binary format, how are the operating systems themselves compiled? Ask the OS manufacturers for details. But basically, they are compiled like any other program (just very complex programs). Like any other program, their source code is compiled into appropriately-formatted executable files for each platform they are targeting, and even for each target CPU. For instance, Windows uses the PE format for all of its executables, but the underlying machine code inside each executable is different whether the executable is running on an x86 CPU vs an x64 CPU vs an ARM CPU. If I'm not mistaken Microsoft uses Windows to compile the next Windows version/update Yes. That is commonly known as "dog-fooding" or "bootstrapping". For instance, VC++ running on Windows is used to develop new versions of VC++, Windows, etc. How are these binaries executable by the machine (even the kernel is one of those)? When an executable file is run (by the user, by a program, etc.), a request goes to the OS, and the OS's executable loader then parses the file's format as needed to locate the file's machine code, and then runs that code on the target CPU(s) as needed. As for running the user's OS itself, there is an even more fundamental OS running on the machine (i.e., the BIOS) which (amongst other things) loads the user's OS at machine startup and starts it running on the available CPU(s). See Booting an Operating System for more details about that. Aren't they in the same format? (For such a low-level program.) No.
72,804,408
72,804,483
How check instantiation of one type by another with templates?
In my case there is func: // msg can be std::string, std::wstring, const char*, const wchar_t*, ... template<typename StrType> void Log(StrType msg) { if std::string(msg) can be created from msg { // do smth } if std::wstring(msg) can be created from msg { // do smth } else { // wrong argument } } and i have to check if the std::string(wstring) can be created by 'msg' to do appropriate actions.
Since C++17, you may use a constexpr if to check whether std::string or std::wstring can be constructed from the argument you pass to Log: template <typename StrType> void Log(StrType msg) { if constexpr (std::is_constructible_v<std::string, StrType>) { // do smth } else if (std::is_constructible_v<std::wstring, StrType>) { // do smth } else { // wrong argument } }
72,805,295
72,805,586
Why does my python function run faster than the one in c++?
I have been writing a simple test to compare the speed improvements of c++ over python. My results were unexpected with c++ being almost trice as slow as the program written in python. I guess there is something in the loop inside the python function using iterators or something. C++ code #include <ctime> #include <chrono> using namespace std; using namespace chrono; void mult(int* a, int b) { for (size_t i = 0; i < 100000000; i++) { a[i] *= b; } } int main() { srand(time(0)); int* a = new int[100000000]; int l = 100000000; for (int i = 0; i < l; ++i) { a[i] = rand(); } auto start = high_resolution_clock::now(); mult(a, 5); auto stop = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>(stop - start); cout << duration.count() << endl; delete[] a; } Python code import time def mult(x, a): for i in [x]: i *= a x = np.random.random(100000000) start = time.time() mult(x, 5) elapsed = time.time() elapsed = elapsed - start print ("Time spent in (mult) is: ", elapsed) Results c++: 200 milliseconds Python: 65 milliseconds
There are many reasons why this performance test does not give useful results. Don't compare, or pay attention to, release timing. The entire point of using a language like C or C++ is to enable (static) compiler optimizations. So really, the results are the same. On the other hand, it is important to make sure that aggressive compiler optimizations don't optimize out your entire test (due to the result of computation going unused, or due to undefined behaviour anywhere in your program, or due to the compiler assuming that part of the code can't actually be reached because it there would be undefined behaviour if it were reached). for i in [x]: is a pointless loop: it creates a Python list of one element, and iterates once. That one iteration does i *= a, i.e., it multiplies i, which is the Numpy array. The code only works accidentally; it happens that Numpy arrays specially define * to do a loop and multiply each element. Which brings us to... The entire point of using Numpy is that it optimizes number-crunching by using code written in C behind the scenes to implement algorithms and data structures. i simply contains a pointer to a memory allocation that looks essentially the same as the one the C program uses, and i *= a does a few O(1) checks and then sets up and executes a loop that looks essentially the same as the one in the C code. This is not reliable timing methodology, in general. That is a whole other kettle of fish. The Python standard library includes a timeit module intended to make timing easier and help avoid some of the more basic traps. But doing this properly in general is a research topic beyond the scope of a Stack Overflow question. "But I want to see the slow performance of native Python, rather than Numpy's optimized stuff - " If you just want to see the slow performance of Python iteration, then you need for the loop to actually iterate over the elements of the array (and write them back): def mult(x, a): for i in range(len(x)): x[i] *= a Except that experienced Pythonistas won't write the code that way, because range(len( is ugly. The Pythonic approach is to create a new list: def mult(x, a): return [i*a for i in x] That will also show you the inefficiency of native Python data structures (we need to create a new list, which contains pointers to int objects). On my machine, it is actually even slower to process the Numpy array this way than a native Python list. This is presumably because of the extra work that has to be done to interface the Numpy code with native Python, and "box" the raw integer data into int objects.
72,805,585
72,805,672
Why doesn't the .exe file generated by Visual Studio Code show program output?
enter image description hereThe program outputs the number of the leftmost column with only positive numbers. Everything works fine in the Visual Studio Code terminal. I think double-clicking on the automatically generated .exe file in a separate window should launch a full-fledged program that reads the input, processes it and displays the output (the number of the desired column or a message that there is none). In fact, when running this .exe file, a window appears, I can enter 12 numbers through Enter, but the window disappears after entering the 12th number. Am I correct in my assumption, and if so, what could be causing the problem? If not, why is this file needed at all? #include <iostream> #include <cstdio> using namespace std; int main() { int n = 3, m = 4; int matrix[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> matrix[i][j]; } }; int col1[4]; int col2[4]; int col3[4]; int col4[4]; //создание 4 массивов-столбцов (creating 4 column arrays) for (int l = 0; l < n; l++) { for (int k = 0; k < m; k++) { if ((k % 4) == 0) { col1[l] = matrix[l][k]; } else if (((k - 1) % 4) == 0) { col2[l] = matrix[l][k]; } else if (((k - 2) % 4) == 0) { col3[l] = matrix[l][k]; } else if (((k - 3) % 4) == 0) { col4[l] = matrix[l][k]; } }; }; //поиск крайнего левого столбца только положительных чисел (finding the leftmost column of only positive numbers) int c = 0, s = 0; for (int g = 0; g < m; g++) { if (g == 0) { for (int d = 0; d < n; d++) { if (col1[d] <= 0) { c++; } }; if (c == 0) { s++; cout << "col 1"; break; }; c = 0; } else if (g == 1) { for (int d = 0; d < n; d++) { if (col2[d] <= 0) { c++; } }; if (c == 0) { s++; cout << "col 2"; break; }; c = 0; } else if (g == 2) { for (int d = 0; d < n; d++) { if (col3[d] <= 0) { c++; } }; if (c == 0) { s++; cout << "col 3"; break; }; c = 0; } else if (g == 3) { for (int d = 0; d < n; d++) { if (col4[d] <= 0) { c++; } }; if (c == 0) { s++; cout << "col 4"; break; }; c = 0; } }; if (s == 0) { cout << "No positive columns"; }; return 0; } enter image description here
If you are using Microsoft Windows, then the console window will disappear as soon as your program ends. If you don't want this to happen, then you can run your program from the Windows command prompt cmd.exe instead of double-clicking it, or add something to the end of your program that prevents it from closing immediately, such as the following code statement: std::system( "pause" ); Note that you will have to #include <cstdlib> in order to use std::system.
72,805,813
72,886,872
Get the smallest Euler angle from a rotation matrix
I have a 3D rotation matrix with small XYZ angles. Angles are between -20° < angle < 20°. Rotation matrix is constructed with : I want to get angles back from the rotation matrix, but several angles are possible. How to recover the smallest angles allowing to build this rotation matrix in C++? For the moment I use Eigen::eulerAngles() in C++ to get this angles, but Eigen return angle in the ranges x[0:pi] y[-pi:pi] z[-pi:pi]. So no negative X angles are returned. We can see that a rotation matrix constructed with a X angle of -0.2 return an angle of 2.94159 Here is a test code: void eigen_test(float x, float y, float z) { auto mat = AngleAxisf(x, Vector3f::UnitX()) * AngleAxisf(y, Vector3f::UnitY()) * AngleAxisf(z, Vector3f::UnitZ()); auto angle = mat.toRotationMatrix().eulerAngles(0,1,2); cout << "(" << x << ", " << y << ", " << z << ") -> (" << angle[2] << ", " << angle[1] << ", " << angle[0] << ")" << endl; } int main() { std::vector<float> num = { -0.2,0.,0.2 }; for (auto x : num) { for (auto y : num) { for (auto z : num) { eigen_test(x, y, z); } } } return 0; } Full result : X , Y , Z -> X' , Y' , Z' __________________________________________________ (-0.2, -0.2, -0.2) -> (2.94159, -2.94159, 2.94159) (-0.2, -0.2, 0 ) -> (2.94159, -2.94159, -3.14159) (-0.2, -0.2, 0.2 ) -> (2.94159, -2.94159, -2.94159) (-0.2, 0, -0.2) -> (2.94159, -3.14159, 2.94159) (-0.2, 0, 0 ) -> (2.94159, 3.14159, -3.14159) (-0.2, 0, 0.2 ) -> (2.94159, 3.14159, -2.94159) (-0.2, 0.2, -0.2) -> (2.94159, 2.94159, 2.94159) (-0.2, 0.2, 0 ) -> (2.94159, 2.94159, 3.14159) (-0.2, 0.2, 0.2 ) -> (2.94159, 2.94159, -2.94159) (0, -0.2, -0.2) -> (0, -0.2, -0.2) (0, -0.2, 0 ) -> (0, -0.2, 0) (0, -0.2, 0.2 ) -> (3.14159, -2.94159, -2.94159) (0, 0, -0.2) -> (0, 0, -0.2) (0, 0, 0 ) -> (-0, 0, -0) (0, 0, 0.2 ) -> (-0, 0, 0.2) (0, 0.2, -0.2) -> (3.14159, 2.94159, 2.94159) (0, 0.2, 0 ) -> (-0, 0.2, 0) (0, 0.2, 0.2 ) -> (0, 0.2, 0.2) (0.2, -0.2, -0.2) -> (0.2, -0.2, -0.2) (0.2, -0.2, 0 ) -> (0.2, -0.2, -0) (0.2, -0.2, 0.2 ) -> (0.2, -0.2, 0.2) (0.2, 0, -0.2) -> (0.2, 0, -0.2) (0.2, 0, 0 ) -> (0.2, 0, 0) (0.2, 0, 0.2 ) -> (0.2, 0, 0.2) (0.2, 0.2, -0.2) -> (0.2, 0.2, -0.2) (0.2, 0.2, 0 ) -> (0.2, 0.2, -0) (0.2, 0.2, 0.2 ) -> (0.2, 0.2, 0.2)
I have found how to do for angles between pi/2 and -pi/2 (so work with small angles). For a rotation ordering of xyz, you can do: //mat is the 3*3 rotation matrix double rx = atan2(-mat(1, 2), mat(2, 2)); double ry = asin(mat(0, 2)); double rz = atan2(-mat(0, 1), mat(0, 0)); Found more info on https://www.geometrictools.com/Documentation/EulerAngles.pdf
72,806,079
72,806,134
Getting random numbers on vector operation c++
I'm getting weird numbers as output in this code : #include <iostream> #include <vector> int main(){ std::vector<std::vector<int>> vec = {{0,1},{2,3}}; vec.push_back({4,5}); vec.push_back({5,6}); for (int i = 0; i < vec.size(); i++){ for (int i2 = 0; i2 < vec.size(); i2++){ std::cout << vec[i][i2] << std::endl; } } return 0; } It's returning to me: 0 1 1280136264 0 2 3 347673833 38962 4 5 297276653 134256690 5 6 280499436 268474418 I just want to know how to do it properly, and why I'm getting these numbers.
The output you are seeing is due to undefined behavior in your code. The outer vector object has 4 inner vector<int> objects added to it. Each of those inner vector<int> objects is holding 2 int values. Your inner for loop is going out of bounds of the inner vector<int> objects, by trying to access 4 int values when there are only 2 int values available. In your inner for loop, you need to change vec.size() to vec[i].size() instead, eg: #include <iostream> #include <vector> int main(){ std::vector<std::vector<int>> vec = {{0,1},{2,3}}; vec.push_back({4,5}); vec.push_back({5,6}); for (size_t i = 0; i < vec.size(); ++i){ for (size_t i2 = 0; i2 < vec[i].size(); ++i2){ std::cout << vec[i][i2] << std::endl; } /* alternatively: auto &vec2 = vec[i]; for (size_t i2 = 0; i2 < vec2.size(); ++i2){ std::cout << vec2[i2] << std::endl; } */ } return 0; } Online Demo That being said, a safer way to code this is to use range-for loops instead, eg: #include <iostream> #include <vector> int main(){ std::vector<std::vector<int>> vec = {{0,1},{2,3}}; vec.push_back({4,5}); vec.push_back({5,6}); for (auto &vec2 : vec){ for (auto value : vec2){ std::cout << value << std::endl; } } return 0; } Online Demo
72,807,283
72,807,412
constexpr_assert on embedded (--fno-exceptions)
Is it possible to implement a thing such as "constexpr assert" on bare metal? I would normally use a throw statement as it is mentioned here for example. But the compiler rejects the code because of --fno-exceptions even though throw is used only in a constant evaluated context. My implementation: inline constexpr void constexpr_assert(bool condition) { if (std::is_constant_evaluated()) { if (!condition) { throw; // error: exception handling disabled, use '-fexceptions' to enable } } else { assert(condition); } } Potential usage: class EventMask { uint32_t mask; public: static constexpr auto MAX_ID = 31; constexpr EventMask(unsigned int event_id) : mask(static_cast<uint32_t>(1u) << event_id) { constexpr_assert(event_id <= MAX_ID); } }; int main(int argc, char** argv) { EventMask s_ev(55); // this should fail on compilation time EventMask d_ev(argc); // this could fail in the runtime } My compiler is (GNU Arm Embedded Toolchain 10.3-2021.10) 10.3.1
Since you know you're being constant evaluated, all you need to trigger a failure is to do something that's not valid to do during constant evaluation. The easiest of these is to invoke a non-constexpr function: void on_error(char const* msg) { // some code here... or not } Which you can then: if (std::is_constant_evaluated()) { if (!condition) { on_error("this is bad because of some reason that hopefully fits in a literal"); } } Obviously not the greatest solution, but at least you would get an error right here. gcc for instance gives a compile error like: <source>:8:21: error: call to non-'constexpr' function 'void on_error(const char*)' 8 | on_error("bad!"); | ~~~~~~~~^~~~~~~~ Though I guess in this context, the string literal would come from the caller, and so it'd still show up in the call stack. Maybe then on_error() should just take no parameters.
72,807,349
72,840,893
ImGui has no member RenderPlatformWindowsDefault error
When i try to build my old code i dont remember what version is imgui but i'm getting this error. i searched whole internet but i can't find nothing. ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); } Visual studio errors: Error (active) E0020 identifier "ImGuiConfigFlags_ViewportsEnable" is undefined Error (active) E0135 namespace "ImGui" has no member "UpdatePlatformWindows" Error (active) E0135 namespace "ImGui" has no member "RenderPlatformWindowsDefault" Imgui version : v1.88
That code uses the docking branch of imgui, and you're probably using the master branch. You could either switch to the docking branch, or remove those lines of code if you don't need it.
72,807,569
72,807,851
set default value of unordered map if key doesn't exist
In my program I want that the default value, if a key doesn't exist in my unordered map, is going to be std::numeric_limits<double>::max() Instead of just 0. my code looks like the following: class Pair { public: Graph::NodeId node; bitset<64> bits; Pair(Graph::NodeId node1, double bits1) { node = node1; bitset<64> temp(bits1); bits = temp; } }; bool operator==(const Pair &P1, const Pair &P2) { return P1.node == P2.node && P1.bits == P2.bits; } template <> struct std::hash<Pair> { std::size_t operator()(const Pair &pair) const noexcept { std::hash<decltype(pair.node)> ihash; std::hash<decltype(pair.bits)> bhash; return ihash(pair.node) * 31 + bhash(pair.bits); } }; unordered_map<Pair, double> lFunction; so if I want to access the element lFunction[Pair(3,3)] and the key doesn't exist, there should be the value std::numeric_limits<double>::max().
One possibility would be to create a tiny class for the value type: class dproxy { double value_; public: dproxy(double value = std::numeric_limits<double>::max()) : value_{value} {} operator double &() { return value_; } operator double const &() const { return value_; } }; std::unordered_map<Pair, dproxy> lFunction; A default-constructed dproxy will be initialized to std::numeric_limits<double>::max(), and a dproxy will implicitly convert to a (reference to a) double. This can impose limitations if you're doing a lot of implicit conversions otherwise though (e.g., if you had some other function foo that took some other type bar that could be implicitly constructed from a double, foo(lFunction[baz]); would work if lFunction contained doubles, but not if it contained dproxy objects, since an implicit conversion sequence can only use one user-defined conversion).
72,807,801
72,808,782
How to check if ball colides with edge of window in c++ with raylib
i am new to raylib and wanted to make a little 2d ball thing, and i don't know how to stop the sprite from going of the screen, it only works with 2 edges and not the others, would anybody please help? My C++ file: game.cpp: #include <raylib.h> int main() { InitWindow(800, 600, "My Game!"); // Vector2 ballPosition = {400.0f, 300.0f}; Vector2 ballPosition = { (float)800/2, (float)600/2 }; SetTargetFPS(60); while(!WindowShouldClose()) { if (IsKeyDown(KEY_RIGHT)) ballPosition.x += 2.0f; if (IsKeyDown(KEY_LEFT)) ballPosition.x -= 2.0f; if (IsKeyDown(KEY_UP)) ballPosition.y -= 2.0f; if (IsKeyDown(KEY_DOWN)) ballPosition.y += 2.0f; DrawText("move the ball with arrow keys", 10, 10, 20, DARKGRAY); Texture2D ball = LoadTexture("ball.png"); DrawTexture(ball, ballPosition.x - 50, ballPosition.y - 50, WHITE); if (ballPosition.x < 0) ballPosition.x = 0; if (ballPosition.x > 800) ballPosition.x = 800; if (ballPosition.y < 0) ballPosition.y = 0; if (ballPosition.y > 600) ballPosition.y = 600; BeginDrawing(); ClearBackground(RAYWHITE); // Vector2 mousePosition = GetMousePosition(); // ballPosition = mousePosition; // DrawCircleV(ballPosition, 20.0f, BLUE); EndDrawing(); } CloseWindow(); return 0; }
Took me a while but your problem is a combination of the offset for drawing the ball texture and how you check for the bounds of the screen (assuming the image is a 50x50, you didn't specify). Notice I've locally added a circle directly at the ballposition (right after the DrawTextureCall): DrawCircleV(ballPosition, 2.0f, MAROON); Since this is to the right and bottom of the image, your bounds check will only be correct for the right and bottom edges. For the left and top edges the entire image disappears before the ballposition hits the edge. In my opinion you should draw the image at the ballposition and adjust the bounds check to take the image size into account: const float ballHalfSize = ball.width / 2.0f; // assuming square image DrawTexture(ball, int(ballPosition.x - ballHalfSize), int(ballPosition.y - ballHalfSize), WHITE); if ((ballPosition.x - ballHalfSize) < 0) ballPosition.x = ballHalfSize; if ((ballPosition.x + ballHalfSize) > 800) ballPosition.x = 800 - ballHalfSize; if ((ballPosition.y - ballHalfSize) < 0) ballPosition.y = ballHalfSize; if ((ballPosition.y + ballHalfSize) > 600) ballPosition.y = 600 - ballHalfSize; With this new version I get correct collision behavior on all 4 edges of the screen.
72,808,881
72,809,029
C++ How to map string keys to class method invocations for a specific object?
In C++, I am trying to map a user-provided string to a class method invocation for a specific object. I was successful in mapping user-provided strings to function calls for another application, but I do not know how to extend this approach to work for class methods being invoked for a particular object. I would greatly appreciate any assistance in determining how to fix my attempted implementation that is flawed: void read_input(std::string& input_filename, Class_Name& my_object) { // Map string keys to object member invocation std::map<const std::string, std::function<void (const std::string&)>> argument_map = { {"input_one", my_object.method_one}, {"input_two", my_object.method_two}, {"input_three", my_object.method_three} }; std::ifstream input_file; input_file.open(input_filename); std::string line; while (input_file) { std::getline (input_file, line); std::stringstream argument_read(line); std::string command; std::string tmp; argument_read >> command; if (command[0] - '#' == 0) continue; while (argument_read >> tmp) { if (tmp[0] - '#' == 0) break; argument_map[command](tmp); } } return; }
Since all of the methods belong to the same class, and have the same signature, you can use Pointers to member functions, using the member access operator.* to call them (no std::function needed), eg: void read_input(std::string& input_filename, Class_Name& my_object) { // Map string keys to object member invocation using method_type = void (Class_Name::*)(const std::string&); static const std::map<std::string, method_type> argument_map = { {"input_one", &Class_Name::method_one}, {"input_two", &Class_Name::method_two}, {"input_three", &Class_Name::method_three} }; std::ifstream input_file(input_filename); std::string line; while (std::getline (input_file, line)) { std::istringstream argument_read(line); std::string command, param; if (argument_read >> command && command[0] != '#') { auto iter = argument_map.find(command); if (iter != argument_map.end()) { method_type method = iter->second; while (argument_read >> param && param[0] != '#') (my_object.*method)(param); } } } } Otherwise, you can use std::bind() with std::function, eg: void read_input(std::string& input_filename, Class_Name& my_object) { // Map string keys to object member invocation using std::placeholders::_1; using function_type = std::function<void (const std::string&)>; std::map<std::string, function_type> argument_map = { {"input_one", std::bind(&Class_Name::method_one, &my_object, _1) } {"input_two", std::bind(&Class_Name::method_two, &my_object, _1) }, {"input_three", std::bind(&Class_Name::method_three, &my_object, _1) } }; std::ifstream input_file(input_filename); std::string line; while (std::getline (input_file, line)) { std::istringstream argument_read(line); std::string command, param; if (argument_read >> command && command[0] != '#') { auto iter = argument_map.find(command); if (iter != argument_map.end()) { auto &func = iter->second; while (argument_read >> param && param[0] != '#') func(param); } } } } Or, you can use lambdas with std::function, eg: void read_input(std::string& input_filename, Class_Name& my_object) { // Map string keys to object member invocation using function_type = std::function<void (const std::string&)>; std::map<std::string, function_type> argument_map = { {"input_one", [&](const std::string& s){ my_object.method_one(s); } }, {"input_two", [&](const std::string& s){ my_object.method_two(s); } }, {"input_three", [&](const std::string& s){ my_object.method_three(s); } } }; std::ifstream input_file(input_filename); std::string line; while (std::getline (input_file, line)) { std::istringstream argument_read(line); std::string command, param; if (argument_read >> command && command[0] != '#') { auto iter = argument_map.find(command); if (iter != argument_map.end()) { auto &func = iter->second; while (argument_read >> param && param[0] != '#') func(param); } } } }
72,809,713
72,809,967
C++ output printed twice and error exit code: -1
I am learning and practicing with C++. I an error when I tried to run the program. I tried different things like changing the sign (<=,>=,<,>) but I don't think they are the problem. I was planning to create different classes for each range of bonus salary but I don't think it is needed to add different classes. I tried to combine 'bonus' and 'total' in one line of code but I need 'bonus' information to be displayed. The instructions are if your old salary is up to $14,999.99 raise 5%, $15,000.00 to $49,999.99 raise 7%, $50,000.00 to $99,999.99 raise 10% and $100,000.00 and higher raise 15% collect2.exe: error: ld returned 1 exit status The terminal process terminated with exit code: -1. This is the code // Salary Calculator Program // Intro C++, Lesson 6 // Written by Phong Dau, Jun 2022 #include <iostream> using namespace std; int main( ) { //Declare variables double oldSalary = 0.00; double bonus = 0.00; double total = 0.00; //Prompt the user for inputs cout << "Enter your old salary: "; cin >> oldSalary; //Decide salary bonus if (oldSalary < 15000.00) { bonus = oldSalary * 0.05; total = bonus + oldSalary; cout <<"You will receive a raise of $" <<bonus<<", for a new yearly salary of $"<<total<<endl; } else if (oldSalary >= 15000.00 < 50000.00) { bonus = oldSalary * 0.7; total = bonus + oldSalary; cout <<"You will receive a raise of $" <<bonus<<", for a new yearly salary of $"<<total<<endl; } else if (oldSalary >= 50000.00 < 100000.00) { bonus = oldSalary * 0.1; total = bonus + oldSalary; cout <<"You will receive a raise of $" <<bonus<<", for a new yearly salary of $"<<total<<endl; } else { bonus = oldSalary * 0.15; total = bonus + oldSalary; cout <<"You will receive a raise of $" <<bonus<<", for a new yearly salary of $"<<total<<endl; } //end if system("pause"); return 0; } //end of main When I enter few numbers to test the program, the output printed twice except for over $100,000.00. I only want it to be printed once. Enter your old salary:10000 You will receive a raise of $500,for a new yearly salary of $10500 You will receive a raise of $500,for a new yearly salary of $10500 Press any key to continue . . . Enter your old salary:20000 You will receive a raise of $1400,for a new yearly salary of $21400 You will receive a raise of $1400,for a new yearly salary of $21400 Press any key to continue . . . Enter your old salary:80000 You will receive a raise of $8000,for a new yearly salary of $88000 You will receive a raise of $8000,for a new yearly salary of $88000 Press any key to continue . . . Enter your old salary:150000 You will receive a raise of $22500,for a new yearly salary of $172500 Press any key to continue . . .
As identified already in the comments, you have a few issues. I'm going to spell them out for you as an answer. The first issue is that your final else is only controlling a single line because it does not enclose the multiple statements in brackets. else bonus = oldSalary * 0.05; total = bonus + oldSalary; cout <<"You will receive a raise of $" <<bonus<<", for a new yearly salary of $"<<total<<endl; The above is equivalent to: else { bonus = oldSalary * 0.05; } total = bonus + oldSalary; cout <<"You will receive a raise of $" <<bonus<<", for a new yearly salary of $"<<total<<endl; To fix that, put those statements in a block: else { bonus = oldSalary * 0.05; total = bonus + oldSalary; cout <<"You will receive a raise of $" <<bonus<<", for a new yearly salary of $"<<total<<endl; } The second issue is multiple issus actually. To start, this kind of thing is totally bogus: if (oldSalary >= 15000.00 < 50000.00) This does not do what you think. You probably wanted: if (oldSalary >= 15000.00 && oldSalary < 50000.00) But that's still incorrect because it's never reached due to your logic being backwards: if (oldSalary > 14999.99) { // All salaries above 14999.99 } else if (oldSalary > 49999.99) { // Not reachable } else if (oldSalary > 99999.99) { // Not reachable } else { // All salaries less than or equal to 14999.99 } One approach is to reverse the tests such that the things being tested by the "else" are logical possibilities. if (oldSalary > 99999.99) { // (99999.99, +inf) -> 15% } else if (oldSalary > 49999.99) { // (49999.99, 99999.99] -> 10% } else if (oldSalary > 14999.99) { // (14999.99, 49999.99] -> 7% } else { // (-inf, 14999.99] -> 5% } Also, in this instance you have a very minor boundary issue. You say that it's 5% for anything below 15000.00. However, 14999.99999 is below that but you wrongly assume 14999.99 is the highest possible value below 15000. So instead of reversing the order of the statements, let's reverse the comparisons. While we're at it, check out in every possible scenario you are performing the same salary calculation and the same output. So those do not have to be repeated. The only thing different is the bonus calculation. Let's put all that together and roll the bonus multiplier in there too... Look how simple (and readable) it becomes: if (oldSalary < 15000.0) bonus = 0.05; else if (oldSalary < 50000.0) bonus = 0.07; else if (oldSalary < 100000.0) bonus = 0.10; else bonus = 0.15; bonus *= oldSalary; total = oldSalary + bonus; cout << "You will receive a raise of $" << bonus << ", for a new yearly salary of $" << total << endl;
72,810,401
72,810,504
Do while loops execute all lines of code if their conditional is no longer met in the middle of a block?
I'm new to programming and I had a question for a project I'm working on. So if I run this code, does the while loop exit after sending the string "world" to the terminal? Or would it exit before that code is ran? while (conditionalStatement == false) { std::cout << "hello "; conditionalStatement = true; std::cout << "world\n"; } Edit: When I run the code above it sends hello world to terminal. However, I have another few lines of code that are giving me some different results. Not sure why. My project is setup basically like this and when I run it, the string "we broke the loop!" Isn't being sent to the terminal when the user inputs 2. bool something = false; while (something == false) { std::cout << "choose 2 to break loop.\n"; int loopbreak; std::cin >> loopbreak; if (loopbreak == 1) { std::cout << "were looping!\n"; } else if (loopbreak == 2) { something = true; std::cout << "we broke the loop!\n"; } } //continue code
The answer is yes. The condition is only checked at the start of each loop iteration. If you want to end loop execution early, you must execute a break statement.
72,810,480
72,824,237
How to update assembly version of c++ project in Azure Devops Pipeline?
I have a c++ project solution which i am building using azure devops pipeline and i want to update the file version everytime my build is sucessful. I have found different extensions but none is working for me. BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "xxxxx" BEGIN VALUE "CompanyName", "xxxx" VALUE "FileDescription", "xxxx" VALUE "FileVersion", "1.1.0.0" VALUE "InternalName", "xxxxx" VALUE "LegalCopyright", "xxxxx" VALUE "OriginalFilename", "xxxx" VALUE "ProductName", "xxxxx" VALUE "ProductVersion", "1.1.0.0" END END this is how my .rc file looks where i set my default version and other things. I am looking for a way on how i can update fileversion and product version eveytime i build.
Try using the Replace Text in Source Files extension. Just add two Replace In Files Text By Text tasks to replace the FileVersion and ProductVersion separately. You can set your file and product version variables for the update. Also search the *.rc file by a pattern or specify the particular *.rc file in the Advance option. Below YAML for your reference: variables: FileVersion : 2.2.0.1 #This is just a sample, you can set and use the value dynamically like the build number. ProductVersion : 2.3.0.2 pool: vmImage: windows-latest steps: - task: ReplaceInFilesTextByText@2 displayName: Replace-FileVersion inputs: parameterSearchDirectory: '$(Build.SourcesDirectory)' parameterSearchText: '"FileVersion", "1.1.0.0"' parameterReplaceText: '"FileVersion", "$(FileVersion)"' parameterTypeOfSearch: 'filesSearchPattern' parameterFilesPattern: '*.rc' - task: ReplaceInFilesTextByText@2 displayName: Replace-ProductVersion inputs: parameterSearchDirectory: '$(Build.SourcesDirectory)' parameterSearchText: '"ProductVersion", "1.1.0.0"' parameterReplaceText: '"ProductVersion", "$(ProductVersion)"' parameterTypeOfSearch: 'filesSearchPattern' parameterFilesPattern: '*.rc' - task: PowerShell@2 displayName: Check-Modified-rc-file inputs: targetType: 'inline' script: 'cat $(Build.SourcesDirectory)\test.rc' As we can see the versions can be updated successfully:
72,810,620
72,810,651
Creating serial text output with a text
Hello I want to know how can I make a code like i want to input a number XXX it will output ChinaXXX BeijingXXX-CHINA-XXX +180243189(XXX) Like this. Advance thanks Sorry for the title. I dont how can i said about on title.
#include <iostream> #include <string> int main() { std::string number; std::cin >> number; std::cout << "China" << number << " Beijing" << number << "-CHINA-" << number << " +180243189(" << number << ")" << std::endl; }
72,811,201
72,811,239
How can I use a string read from `std::cin` to look up an existing variable by name?
I'm currently trying to make a sort of a shopping cart. When the program asks for items, i type them in; but it needs to remember the values so it can use them later in the code. I have this code so far: #include <iostream> int main() { int item{}; int apple = 5; std::cout << "what item do you want to buy?"; std::cin >> item; std::cout << item; return 0; } Can I make it so that when i type apple as input, item actually gets the value 5, from the variable named apple? With this code, I get 0 as the result.
You could create a map with string keys and int values, store the necessary data in that map (instead of separate variables), and use the value read from std::cin as an index. The code looks like: std::map<std::string, int> fruits; fruits["apple"] = 5; std::string choice; std::cin >> choice; std::cout << fruits[choice] << std::endl;
72,812,148
72,816,735
Integer to byte array arduino BLE
I want to convert an interger to bytes array and send it via BLE using the writeValue() function: int x; String strx; x=accel.x(); strx=String(x); byte bytes[4]; strx.getBytes(bytes,2) Serial.print(sizeof(bytes)); accelxCharacteristic.writeValue(bytes,4); but I am having this error: no matching function for call to 'BLEIntCharacteristic::writeValue(byte [4], int)
I found out that I have to be careful on how I declare the characteristic there are these options in the documentation: BLECharacteristic(uuid, properties, value, valueSize) BLECharacteristic(uuid, properties, stringValue) BLEBoolCharacteristic(uuid, properties) BLEBooleanCharacteristic(uuid, properties) BLECharCharacteristic(uuid, properties) BLEUnsignedCharCharacteristic(uuid, properties) BLEByteCharacteristic(uuid, properties) BLEShortCharacteristic(uuid, properties) BLEUnsignedShortCharacteristic(uuid, properties) BLEWordCharacteristic(uuid, properties) BLEIntCharacteristic(uuid, properties) BLEUnsignedIntCharacteristic(uuid, properties) BLELongCharacteristic(uuid, properties) BLEUnsignedLongCharacteristic(uuid, properties) BLEFloatCharacteristic(uuid, properties) BLEDoubleCharacteristic(uuid, properties) Make sure if you are sending a buffer to use: BLECharacteristic(uuid, properties, value, valueSize)
72,812,328
72,901,817
ICC compile options for evaluating macros in GDB while debugging
I would like to evaluate and print the macro while debugging using GDB. While the GDB documentation has steps to do that by compiling using -g3 flag in gcc compiler, I am using Intel Icc compiler. Their debugging compilation options seem to have no information about macros. Is it possible to do that using icc? If yes what are the compilation options.
icc --help prints almost 2000 lines of output, among which there's -debug [keyword] Control the emission of debug information. Valid [keyword] values: [snip] [no]macros Controls output of debug information for preprocessor macros. but passing -debug macros results in an error: icc: command line error: Unrecognized keyword 'macros' for option '-debug' It's unclear what happened here, perhaps the option was available in the past, and removed since then. You can report this to Intel. The new LLVM-based Intel compiler, ICX, can emit macro definitions to debug info under the same option as Clang, -fdebug-macro.
72,812,520
72,812,655
C++ unordered_map implementation problem previous values in map get forgotten
In the below code why map size is always 1, it is not saving previous values of root->val in the map as I can see in stdout. I was expecting that it should remember all the values put in the map. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class FindElements { public: unordered_map<int,int>mp; FindElements(TreeNode* root) { if(!root) return; if(root->val==-1){ root->val=0; } mp[root->val]=1; // output cout<<root->val<<" "<<mp[root->val]<<" "<<mp.size()<<endl; if(root->left){ root->left->val=2*(root->val)+1; FindElements(root->left); } if(root->right){ root->right->val=2*(root->val)+2; FindElements(root->right); } } bool find(int target) { return mp[target]; } }; /** * Your FindElements object will be instantiated and called as such: * FindElements* obj = new FindElements(root); * bool param_1 = obj->find(target); */ Input: ["FindElements","find","find","find"] [[[-1,-1,-1,-1,-1]] , [1] , [3] , [5]] Output: [null,false,false,false] Expected: [null,true,true,false] stdout: 0 1 1 1 1 1 3 1 1 4 1 1 2 1 1 key,value,map-size I was expecting that in each row map size values get increased. leetcode problem link
Your code looks like you make an recursive call, to make a depth first search on the tree, but in fact it does not. Because you are not using a normal member function, but the constructor, and a constructor can not be called recursive. The syntax that look like recursion is instead the creation of additional temporary objects which will be destroyed after tge line ends.
72,812,599
72,812,720
Iterating over std::optional
I tried to iterate over an std::optional: for (auto x : optionalValue) { ... } With the expectation of it doing nothing if optionalValue is empty but doing one iteration if there is a value within, like it would work in Haskell (which arguably made std::optional trendy): forM optionalValue ( \x -> ... ) Why can't I iterate an optional? Is there another more standard C++ method to do this?
std::optional does not have a begin() and end() pair. So you cannot range-based-for over it. Instead just use an if conditional. See Alternative 2 for the closest thing to what you want to do. Edit: If you have a temporary from a call result you don't have to check it explicitly: if (auto const opt = function_call()) { do_smth(*opt); } The check for static_cast<bool>(opt) is done implicitly by if. Alternative 1 Another alternative is to not use an std::optional<T> but std::variant<std::monostate, T>. You can then either use the overloaded idiom or create a custom type to handle the monostate: template <typename F> struct MaybeDo { F f; void operator()(std::monostate) const {} template <typename T> void operator()(T const& t) const { f(t); } }; which will allow you to visit the value with some function: std::variant<std::monostate, int> const opt = 7; std::visit(MaybeDo{[](int i) { std::cout << i << "\n"; }}, opt); Alternative 2 You can also wrap optional in a thing that allows you to iterate over it. Idea: template <typename T> struct IterateOpt { std::optional<T> const& opt; struct It { std::optional<T> const* p; It& operator++() { p = nullptr; return *this; } It operator++(int) { return It{nullptr}; } auto const& operator*() const { **p; } }; auto begin() const { if (opt) return It{&opt}; else end(); } auto end() const { return It{nullptr}; } }; This is a crude sketch of how to do this and probably requires some love to work on different situations (like a non-const optional). You can use this to "iterate" over the optional: for (auto const& v: IterateOpt{function_call()}) { do_smth(v); )
72,813,046
72,813,148
getLine() does't seem to work after first input - C++
I'm currently new to C++ and learning the basic syntax. I'm exploring how getLine() works and I'm trying to compare the standard input and a getline(). #include <iostream> #include <string> using namespace std; int main(){ string name1; string name2; cout << "Type your name please: "; cin >> name1; cout << "Your name is: " << name1 << endl; cout << endl; cout << "Type your name again please: "; cin.ignore(); getline(cin, name2); cout << "Your name is: " << name2 << endl; return 0; } Expected Output: Type your name please: John Doe Your name is: John Type your name again please: John Doe Your name is: John Doe Current Output: Type your name please: John Doe Your name is: John Type your name again please: Your name is: Doe What may be the issue causing this? Any help would be greatly appreciated.
As you can see cin >> name1; reads only up to the first whitespace. What remains in the input buffer is Doe\n. (Notice the first character is a space). Now cin.ignore(); will ignore 1 character (the white space in this case). The input buffer now contains Doe\n. See here for more details: https://en.cppreference.com/w/cpp/io/basic_istream/ignore Next getline(cin, name2); will read all the data up to the next new line. That is Doe, which you get as second output. I think you wanted to discard the complete input, instead of just one character. This should do it: cin.ignore(std::numeric_limits<std::streamsize>::max());
72,813,066
72,813,067
How to parse a .yml file without %YAML:1.0 header [C++]
I need to parse a .yml file which doesn't have a header, which on the other hand is required by OpenCV. How OpenCV wants a .yml file to look like: %YAML:1.0 --- data: - coordinates: [....] filename: "..." - coordinates: [....] filename: "..." How our files look like: data: - coordinates: [....] filename: "..." - coordinates: [....] filename: "..."
Update - I prepared a ready to use function to read OpenCV Yaml without %YAML:1.0 header cv::FileStorage readFileStorage(const std::filesystem::path path) { std::ifstream file(path, std::iostream::binary | std::ios::ate); if (!file.good()) { return ""; } file.exceptions(std::ifstream::badbit | std::ifstream::failbit | std::ifstream::eofbit); auto length(file.tellg()); std::string buffer(length, '\0'); file.seekg(0); file.read(&buffer[0], length); if(buffer.empty()) { return cv::FileStorage(); } cv::String dataString = "%YAML:1.0\n" + buffer; return cv::FileStorage(dataString, cv::FileStorage::READ | cv::FileStorage::MEMORY); } What I did was pushing the header into the filestream just before it reads it: std::vector<char> buffer; // make buffer read the file buffer.push_back(0) // add 0 so OpenCV can treat this buffer as char* string cv::String dataString = "%YAML:1.0\n" + cv::String(&buffer[0], buffer.size()); cv::FileStorage fs(dataString, cv::FileStorage::READ | cv::FileStorage::MEMORY); Having this, I was able to parse .yml file without a header fs["data"] >> data;
72,813,269
72,820,960
Get link of the page that createWindow() opens
Im trying to make a tab system This code gives me the link of the page that i am currently on, i would like to get the link of the page i clicked on. In this code if i change return nullptr; to return this;, the clicked page will open in the same tab. QWebEngineView* createWindow(QWebEnginePage::WebWindowType type) { if(type == QWebEnginePage::WebBrowserTab) { emit new_url(this->url()); return nullptr; } return nullptr; } What does return mean in the QWebEngineView::createWindow() function? How could i get the link i clicked on?
This little change worked for me: QWebEngineView* createWindow(QWebEnginePage::WebWindowType type) { if(type == QWebEnginePage::WebBrowserTab) { MyWebView *webView = new MyWebView(); emit new_tab(webView); return webView; } return nullptr; } this code creates a new MyWebView object and send it to another function i implemented to create tabs and finally, return webView opens the new link in the webView object
72,813,551
72,813,821
Choose class specialization using default template parameter
Can someone please explain why in the following code C choses the specialization but A does not? They look the same to me #include <iostream> template <typename T=int> struct C { int i=3; }; template<> struct C<int> { int i=4; }; template <typename T=int> struct A { A(int, int) {} }; template <> struct A<int> { A(int) {} }; int main() { C c; std::cout << c.i << '\n'; // prints 4 // A a(5); // does not compile } I tested using GCC
Without an explicit template argument list (as in A a instead of A<> a) class template argument deduction (CTAD) will be performed. CTAD basically tries to find a matching constructor for the declaration from which it can deduce the template arguments. But it always considers only constructors in the primary template, not in specializations. A(int, int) {} is not a constructor that would be viable for A a(5); and so it fails. You need to add deduction guides for your specializations manually to inform CTAD how to decide the template arguments. For example here add the following declaration at namespace scope, for readability probably after your explicit specialization: A(int) -> A<int>; or alternatively, making use of the default argument: A(int) -> A<>; C c; is correct, since the implicit default constructor of C is viable for this declaration and it doesn't need to deduce the template argument since it is defaulted. I could not reproduce Clang or MSVC failing to compile it. Note however that in general CTAD requires C++17 or later. Before that leaving out the template argument list on a type was simply never allowed.
72,813,805
72,820,405
C++ warn when storing 32 bit value in a 64 bit variable
I recently discovered a hard to find bug in a project I am working on. The problem was that we did a calculation that had a uint32_t result and stored that in a uint64_t variable. We expected the result to be a uint64_t because we knew that the result can be too big for a 32 bit unsigned integer. My question is: is there a way to make the compiler (or a static analysis tool like clang-tidy) warn me when something like this happens? An example: #include <iostream> constexpr uint64_t MUL64 { 0x00000000ffffffff }; constexpr uint32_t MUL32 { 0xffffffff }; int main() { const uint32_t value { 0xabababab }; const uint64_t value1 { MUL64 * value }; // the result is a uint64_t because // MUL64 is a uint64_t const uint64_t value2 { MUL32 * value }; // i'd like to have a warning here if (value1 == value2) { std::cout << "Looks good!\n"; return EXIT_SUCCESS; } std::cout << "Whoopsie\n"; return EXIT_FAILURE; } Edit: The overflow was expected, i.e. we knew that we would need an uint64_t to store the calculated value. We also know how to fix the problem and we changed it later to something like: const uint64_t value2 { static_cast<uint64_t>(MUL32) * value }; That way the upper 32 bits aren't cut off during the calculation. But things like that may still happen from time to time, and I just want to know whether there is way to detect this kind of mistakes. Thanks in advance! Greetings, Sebastian
The multiplication behavior for unsigned integral types is well-defined to wrap around modulo 2 to the power of the width of the integer type. Therefore there isn't anything here that the compiler could be warning about. The behavior is expected and may be intentional. Warning about it would give too many false positives. Also, in general the compiler cannot test for overflow at compile-time outside a constant expression evaluation. In this specific case the values are obvious enough that it could do that though. Warning about any widening conversion after arithmetic would very likely also be very noisy. I am not aware of any compiler flag that would add warnings for the reasons given above. Clang-tidy does have a check named bugprone-implicit-widening-of-multiplication-result specifically for this case of performing a multiplication in a narrower type which is then implicitly widened. It seems the check is present since LLVM 13. I don't think there is an equivalent for addition though. This check works here as expected: <source>:11:29: warning: performing an implicit widening conversion to type 'const uint64_t' (aka 'const unsigned long') of a multiplication performed in type 'unsigned int' [bugprone-implicit-widening-of-multiplication-result] const uint64_t value2 { MUL32 * value }; // i'd like to have a warning here ^ <source>:11:29: note: make conversion explicit to silence this warning const uint64_t value2 { MUL32 * value }; // i'd like to have a warning here ^~~~~~~~~~~~~ static_cast<const uint64_t>( ) <source>:11:29: note: perform multiplication in a wider type const uint64_t value2 { MUL32 * value }; // i'd like to have a warning here ^~~~~ static_cast<const uint64_t>() Clang's undefined behavior sanitizer also has a check that flags all unsigned integer overflows at runtime, which is not normally included in -fsanitize=undefined. It can be included with -fsanitize=unsigned-integer-overflow. That will very likely require adding suppressions for intended wrap-around behavior. See https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html for details. It seems however that this check isn't applied here since the arithmetic is performed by the compiler at compile-time. If you remove the const on value2, UBSan does catch it: /app/example.cpp:11:29: runtime error: unsigned integer overflow: 4294967295 * 2880154539 cannot be represented in type 'unsigned int' SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /app/example.cpp:11:29 in Whoopsie GCC does not seem to have an equivalent option. If you want consistent warnings for overflow in unsigned arithmetic, you need to define your own wrapper classes around the integer types that perform the overflow check and e.g. throw an exception if it fails or alternatively you can implement functions for overflow-safe addition/multiplication which you would then have to use instead of the + and * operators.
72,814,644
72,814,709
How can I check if template type is any type of std::vector<>
I have a template function like this: template <typename T> void MyClass::setData(const std::string& name, const T& value) { ... // if the template type is a vector of strings, add instead of overwrite if constexpr (std::is_same_v<T, std::vector<std::string>>) { auto temp = someData.get<T>(name); temp.insert(temp.end(), value.begin(), value.end()); someData.set(name, temp); } // otherwise just set data else { someData.set(name, value); } ... } What I want now is to check if T is any std::vector<>, not just for strings. How do I do that?
You can use partial specialization: #include <type_traits> #include <iostream> #include <vector> template <typename C> struct is_vector : std::false_type {}; template <typename T,typename A> struct is_vector< std::vector<T,A> > : std::true_type {}; template <typename C> inline constexpr bool is_vector_v = is_vector<C>::value; int main() { std::cout << is_vector_v< std::vector<int> > << "\n"; std::cout << is_vector_v< int > << "\n"; }
72,815,476
72,838,168
Nodejs/c++ addon - getting error "undefined symbol: speech_config_from_subscription" from Microsoft speech SDK on ubuntu 18.4 server
Actually, I want to do speech transcription with passing MULAW (g711) audio format to microsoft-speech-sdk (Nodejs), but MULAW streaming audio format is not supported to microsoft-speech-sdk (Nodejs). So, for this required GStreamer with C++. So, I'm going to create node/c++ addon for this. but I am facing below error. 1|server | node /home/*****Transation/server.js: symbol lookup error: /home/*****Transation/stream-translation/cpp_asr/build/Release/accumulate.node: undefined symbol: speech_config_from_subscription Installed the Speech SDK using this link. Using reference for addon link.
I got the solution, Just coped this libMicrosoft.CognitiveServices.Speech.core.so library into /usr/lib folder and modified binding.gyp file. it is working fine. { "targets": [ { "target_name": "transcription", "sources": ["src/streamingAsr.cpp"], "cflags": ["-Wall", "-std=c++17"], "cflags!": ["-fno-exceptions"], "cflags_cc!": ["-fno-exceptions"], "include_dirs": [ "/home/delaplexTransation/speechsdk/include/cxx_api", "/home/delaplexTransation/speechsdk/include/c_api", "<!(node -e \"require('nan')\")", "<!(node -e \"require('streaming-worker-sdk')\")" ], "libraries": [ "/usr/lib/libMicrosoft.CognitiveServices.Speech.core.so" ] } ] }
72,815,993
72,823,331
C++ variadic templates pass modified arguments to function
I'm struggling with the following code. It's meant to be a very simple, hopefully constexpr, gradient-descent solver. My current code looks like this: typedef std::function<double(double, double, double)> residual_function_t; double gradient_descent(const residual_function_t& res_fun, double step_size, double& x, double& y, double& z, double epsilon = 0.01) { assert(step_size > 0.0); const auto residual = res_fun(x, y, z); const auto deriv_x = (res_fun(x + epsilon, y, z) - residual) / epsilon; const auto deriv_y = (res_fun(x, y + epsilon, z) - residual) / epsilon; const auto deriv_z = (res_fun(x, y, z + epsilon) - residual) / epsilon; x -= std::copysign(step_size, deriv_x); y -= std::copysign(step_size, deriv_y); z -= std::copysign(step_size, deriv_z); return residual; } I'd like to make the function more general, and accept any kind of function. That means I have to create variables like deriv_x for each of the arguments I want to pass to that function. I'd like my function signature to be something like this: template<typename residual_function_t, typename... Arg_types> double gradient_descent(const residual_function_t & res_fun, double step_size, Arg_types... arguments) { constexpr auto epsilon = 0.01; const auto residual res_fun(arguments...); // Here I want to calculate deriv_x/y/z/etc for every argument passed. // Here want to assign x/y/z, or return them if needed, for every argument passed. return residual; } I wonder if this is possible? If it makes life easier to assume all arguments are of type double, that would also work.
If you want all the arguments to be of type double, then you might consider using std::initializer_list as follows: double gradient_descent(const residual_function_t& res_fun, double step_size, std::initializer_list<double> args, double epsilon = 0.01) { // ... The downside is that you have to add an extra set of braces around the args when calling the function. Otherwise, while not strictly required, you may want to move epsilon before the variadic argument list to simplify your life. You have many options for handling a template parameter pack. One simple thing you can do in C++17 or later is to put the arguments into an array: double gradient_descent(const residual_function_t& res_fun, double step_size, double epsilon, auto ...argspack) { std::array<double, sizeof...(argspack)> args(double(argspack)...); // ... } If you want to modify the arguments, that's fine, too, though they have to be doubles at that point: double gradient_descent(const residual_function_t& res_fun, double step_size, double epsilon, std::same_as<double> auto &...argspack) { std::array<std::reference_wrapper<double>, sizeof...(argspack)> args(std::as_ref(argspack)...); // ... }
72,816,593
72,827,414
template std::boost function given to a thread invalid static_cast
I am writing an util class to facilitate thread management into ROS environment. I would like to pass a callback ROS function coded with the boost lib lambda expression style in argument to my thread handler object (TriggeredProcess class). Here is my code : my code #include <boost/function.hpp> #include <boost/thread.hpp> namespace alongside { class TriggeredProcess { public: template<typename Message> TriggeredProcess( const boost::function<void (Message const&)>& callback ) { boost::thread triggred_process( static_cast<void(*)( const boost::function<void (Message const&)>&s )>(&run), callback ); } private: template<typename Message> void run( const boost::function<void (Message const&)>& callback ) { //placeholder } }; } int main(int argc, char** argv) { /** * @brief Originally roscpp @p std_msg::Bool type is used, * but can be any kind of msg type. * Here to avoid ros deps I use SL @p bool type, * with the same kind of error */ boost::function<void (const bool&)> callback = [&] (const bool& msg) { //placeholder }; alongside::TriggeredProcess a(callback); } my error message error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘void (*)(const boost::function<void(const bool&)>&)’ 14 | static_cast<void(*)( | ^~~~~~~~~~~~~~~~~~~~ 15 | const boost::function<void (Message const&)>&s | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 16 | )>(&run), | ~~~~~~~~ my dev env specs Thread model: posix gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) In the constructor of TriggeredProcess, it seems to dislike boost functions with template parameters passed in a static_cast used as suggested here. Did you have any idea of another implementation to pass template argumented functions to a boost::thread ? Or what is wrong in my implementation please ? Thanks in advance !!
I think the issue is caused by two core mistakes: &run, which takes the address of a template calling a nonstatic memberfunction without this You static_cast the address of the template to a different type (probably in order to resolve the type ambiguity), but that is what you'd do with an actually overloaded function. Instead, use &run<MessageType>. Note that the compiler can determine the template parameters automatically in most cases, in particular when they are the same as the passed arguments, but you can always specify them explicitly. In this case, I'd even say it is cleaner. The second thing is that you pass the memberfunction address and parameters for its call to the thread constructor. A memberfunction in C++ is not bound to an object though, but it absolutely needs an object for being called. The object is most probably this, but if you don't need an instance data, you can also make the memberfunction static. However, all this is way too complicated IMHO. Instead, just use a lambda. Fixed class code: class TriggeredProcess { public: template<typename Message> TriggeredProcess( const boost::function<void (Message const&)>& callback ) { boost::thread triggred_process([&] { this->run(callback); }); } private: template<typename Message> void run( const boost::function<void (Message const&)>& callback ) { //placeholder } }; Just one final note: I think you're reinventing https://en.cppreference.com/w/cpp/thread/async a bit here, maybe scrapping that approach and using something from the shelf would make your life (and that of the next dev reading the code) more productive.
72,816,624
72,816,993
Is there a stratified enum, or base class for enum in C++?
I encountered a situation where I need to write many enums, but wish to separate, or stratify all the enums into groups of enums of smaller length, as the following shows: enum class health {HP,Shield}; enum class battle {STR,AGL,INT}; // such struct DOESN'T WORK, either with instantiated object or direct struct referencing struct hero_num{ enum class health {HP,Shield}; enum class battle {STR,AGL,INT}; }; The reason I am writing a struct to hold all enums is that I want to use all those enums by only referencing the hero_num type, so as to utilize functions as such: // A class definition scope { ... int get_stats(hero_num stats_type); void add_stats(hero_num stats_type, int value); ... }; // I wish to call all the enum with ONE definition void add_stats(health::HP,100); void add_stats(battle::STR,10); I am not sure whether aggregating declared enum into struct, or create a base class enum for all enum would work as intended. How should I design my structure to make such a function call? Or, in general, how could I break a lengthy enum into smaller enums, and make the right type reference?
You may want to ask yourself if you need enums, particularly, or if you actually just want some kind of tag. Enums allow runtime switching based on an object of the enum type, whereas for the use case you've shown (health::HP, battle::STR) the property type is known at compile time, and a type-based tag approach may suffice. #include <type_traits> struct health { struct HP{}; struct Shield{}; }; struct battle { struct STR{}; struct AGL{}; struct INT{}; }; struct hero_num : health, battle {}; // hero_num::HP // hero_num::Shield // hero_num::STR // hero_num::AGL // hero_num::INT struct hero { template<typename property> void add_stats(int value) { if constexpr (std::is_same_v<property, hero_num::HP>) { hp += value; } else if constexpr (std::is_same_v<property, hero_num::Shield>) { shield += value; } // ... and so on } private: int hp{}; int shield{}; int strenght{}; int agility{}; int intelligence{}; }; int main() { hero my_hero{}; my_hero.add_stats<hero_num::HP>(12); }
72,817,191
72,825,277
In OpenGL is it possible to select from multiple indices with the same vao? Or share a vbo across vaos?
Suppose we are drawing a cube in 3 ways: points, wireframe and shaded. The same 8 points are used for both drawing commands, but the points can just be drawn from the vbo, the wireframe is connecting pairs of points, and the shaded version needs triangles. This can be achieved using two index arrays. For wireframe: uint32_t lineIndices[] = { 0,1, 1,2, 2,3, 3,0, 4,5, 5,6, 6,7, 7,4, 0,4, 1,5, 2,6, 3,7 }; suppose these numbers are bound into an index array lbo. To draw the lines would be: drawElements(GL_LINES, 24, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); If instead I want to draw triangles, I need a different index. If I have two indices, lbo and sbo, can both be in the same vao? Can I just bind the one that I want currently so it is used? If not, is it possible to share the same vbo across multiple vaos and have each index in a different vao?
Yes, you can put multiple sequences of indices within one index buffer. The last argument of glDrawElements() (void* indices) is actually not a pointer to memory but rather a starting byte offset into your index buffer. You can draw a subset of your indices by simply specifying the byte offset of the first index you want to draw, and specifying the number of indices to draw with the count argument as usual. For example, your index buffer could contain the 8 indices required to draw the cube as points, then the 24 indices required to draw the cube as lines, then the 36 indices required to draw the cube as triangles. If you want to draw the cube as lines, you could compute the byte offset of the first index (8 * sizeof(uint32_t)), and then simply call glDrawElements() as you have already, but passing this offset as the last argument. Side note: the index buffer is usually abbreviated as EBO for "element buffer object," rather than IBO.
72,817,192
72,840,916
Problem with linking Class into specific memory region using Linker Script
I have a problem with linking class to specific memory region via Linker Script I've figure out how to link variables and functions that are out of the class but I have no idea how to link the class into the memory region specified in the linker script My linker script is very simple: SECTIONS { . = 0x1000000; .text : { *(.text) } . = 0x8000000; .data : { *(.data) } .bss : { *(.bss) } } And the main code: #include <iostream> // system #include "mem.h" using namespace std; unsigned int A = 0xFFFF1234; unsigned int B = 0x00001234; void Function_A(void) { printf("This is execution of the void Function A \n"); } void Function_B(int x) { x = x + 1; printf("This is execution of the void Function B with variable x:%d \n",x); } int main(int argc, char* argv[]) { system("clear"); unsigned int * pA = &A; unsigned int * pB = &B; printf("Original Data A ---> 0x%08x\n",A); printf("Original Data B ---> 0x%08x\n\n",B); printf("Pointer to A variable ---> %p\n",pA); printf("Pointer to B variable ---> %p\n\n",pB); void (*pFunction_A)(void) = &Function_A; void (*pFunction_B)(int) = &Function_B; MemAssembly * pMemAssembly; pMemAssembly->MemDump(); // Testing function pointers pFunction_A(); pFunction_B(100); (*pFunction_B)(200); printf("Pointer to Function_A ---> %p\n",pFunction_A); printf("Pointer to Function_B ---> %p\n\n",pFunction_B); // Address is not linked !!!???? printf("Pointer to MemAssembly Class ---> %p\n\n",pMemAssembly); return 0; } Now, when I execute I get this: Original Data A ---> 0xffff1234 Original Data B ---> 0x00001234 Pointer to A variable ---> 0x8000004 Pointer to B variable ---> 0x8000008 RAX_Accumulator ---> Read A : 0x00000000ffff1234 RAX_Accumulator ---> Read B : 0x0000000000001234 This is execution of the void Function A This is execution of the void Function B with variable x:101 This is execution of the void Function B with variable x:201 Pointer to Function_A ---> 0x10000e9 Pointer to Function_B ---> 0x1000103 Pointer to MemAssembly Class ---> 0x7f282ab46764 The mem.h looks as follows: #ifndef MEM_H #define MEM_H #include <inttypes.h> extern "C" unsigned long _MEMORY_READ_A(void); extern "C" unsigned long _MEMORY_READ_B(void); class MemAssembly{ public: MemAssembly(); ~MemAssembly(); int AssemblyMemoryDump(void); void MemDump(void) { printf("RAX_Accumulator ---> Read A : %#018" PRIx64 " \n",_MEMORY_READ_A()); printf("RAX_Accumulator ---> Read B : %#018" PRIx64 " \n\n",_MEMORY_READ_B()); } }; #endif /* MEM_H */ And the assemblies section .text global _MEMORY_READ_A _MEMORY_READ_A: mov eax, [0x08000000 + 4] ret global _MEMORY_READ_B _MEMORY_READ_B: mov eax, [0x08000000 + 8] ret So my question is: How should I modify linker script, mem.h or the assemblies in order to load my class into specific memory region rather than using dynamic allocation ??? Instead of this one: Pointer to MemAssembly Class ---> 0x7f282ab46764 Read address specified in the linker script ???
Thanks Peter for the help Here what I did: Added MemAssembly section in ASM section .MemAssembly global global_MemAssembly global_MemAssembly: Link it with 0xb000000 SECTIONS { . = 0x1000000; .text : { *(.text) } . = 0x8000000; .data : { *(.data) } .bss : { *(.bss) } . = 0xB000000; .MemAssembly : { *(MemAssembly)} } Using Test class class MemAssembly{ public: MemAssembly(); ~MemAssembly(); int x,y,z,t; long a,b,c,d; long long dx,dy,dz,dt; void MemDump(void) { printf("x ---> %p y ---> %p z ---> %p t ---> %p\n", &x, &y, &z, &t); printf("a ---> %p b ---> %p c ---> %p d ---> %p\n", &a, &b, &c, &d); printf("dx ---> %p dy ---> %p dz ---> %p dt ---> %p\n\n", &dx, &dy, &dz, &dt); } }; When I call MemDump() using usign dynamic: MemAssembly * pMemAssembly I get: x ---> 0x7ffd7cc36040 y ---> 0x7ffd7cc36044 z ---> 0x7ffd7cc36048 t ---> 0x7ffd7cc3604c a ---> 0x7ffd7cc36050 b ---> 0x7ffd7cc36058 c ---> 0x7ffd7cc36060 d ---> 0x7ffd7cc36068 dx ---> 0x7ffd7cc36070 dy ---> 0x7ffd7cc36078 dz ---> 0x7ffd7cc36080 dt ---> 0x7ffd7cc36088 But when I've used: extern MemAssembly global_MemAssembly; MemAssembly * pMemAssembly = &global_MemAssembly; I get: x ---> 0xb000000 y ---> 0xb000004 z ---> 0xb000008 t ---> 0xb00000c a ---> 0xb000010 b ---> 0xb000018 c ---> 0xb000020 d ---> 0xb000028 dx ---> 0xb000030 dy ---> 0xb000038 dz ---> 0xb000040 dt ---> 0xb000048 Which is what I've expected
72,817,516
72,876,509
Properly using QMAKE_POST_LINK in Qt project file
When adding commands to QMAKE_POST_LINK using += operator should I need to add a semicolon? For example, QMAKE_POST_LINK += mv somefile1.dat /some_location1; # semicolon QMAKE_POST_LINK += mv somefile2.dat /some_location2 ... Without the semicolon Qt doesn't separate the commands. Is this proper functionality?
You should add $$escape_expand(\n\t) at the end of the each command. Some examples (just took from my real app): QMAKE_POST_LINK += "cp -f $$OUT_PWD/$$DESTDIR/crashreporter.app/Contents/MacOS/crashreporter $$MACX_APP_MACOS_DIR" $$escape_expand(\n\t) QMAKE_POST_LINK += "cp -R" $$VMSCLSHARED_DYLIBS $$MACX_APP_FW_DIR/ $$escape_expand(\n\t) Here is one yet example: https://gist.github.com/Wohlstand/3d9455c4baddc057de60e511f7280b87
72,817,641
72,817,685
float vector and pointer returns different values even though they have same adress
I have a class which returns vector<vector<float>> with its getTemplates() function. My code is as follows for this case: cout << "Get [0][0] " << s.getTemplates()[0][0] << endl; cout << "vec addr " << &(s.getTemplates()[0][0]) << endl; float *embFloat = s.getTemplates()[0].data(); cout << "embFloat: " << embFloat << endl; cout << "*embFloat " << *embFloat << endl; cout << "embFloat[0] " << embFloat[0] << endl; and the output is as follows: Get [0][0] 0.00191223 vec addr 0x555557973280 embFloat: 0x555557973280 *embFloat -8.71571e+33 embFloat[0] -8.71571e+33 I expect embFloat[0] and s.getTemplates()[0][0] to return exactly same value. What am I missing here?
s.getTemplates() returns a temporary which (in this particular instance) goes out of scope at the end of the statement that contains it. float *embFloat is therefore a dangling pointer - i.e. it's pointing to an object that no longer exists.
72,818,501
72,818,858
Cannot convert argument 1 from 'int' to 'int [][8]
I'm trying to make chess in the c++ console and I have a function that searches for the piece you want to move. The first parameter is the 2d array that stores the board's state. But when I call the function in the move function it gives me this error: cannot convert argument 1 from 'int' to 'int [][8] It also tells me that argument of type "int" is incompatible of type "int (*)[8] I don't understand why that is since the argument is the same 2d array pair<int, int> search_piece(int v[8][8], int col, int piece, bool colour) { for (int row = 0; row < 8; row++) if (!colour) { if (v[row][col] == piece && v[row][col] < 7) return make_pair(row, col); } else if (v[row][col] == piece && v[row][col] > 6) return make_pair(row, col); return make_pair(-1, -1); } void move(int v[8][8], int row, int col, int piece, bool colour) { pair<int, int> pos = search_piece(v[8][8], col, piece, colour); int irow = pos.first; int icol = pos.second; if (irow >= 0 && icol >= 0) swap(v[irow][icol], v[row][col]); else cout << "Invalid move!\n"; }
search_piece function gets a two-dimensional array as its first argument, but in the move function where you call it, you just pass a single integer not an array. v[8][8] in pair<int, int> pos = search_piece(v[8][8], col, piece, colour); is a single element of v array. if you want to pass hole array simply pass v. pair<int, int> pos = search_piece(v, col, piece, colour);
72,818,540
72,818,710
C++ Template - passing const value of type T by reference
I have a function with a template parameter T and would like to pass a value of type const T by reference. The C++ compiler throws an error, (kind of) understandably so. Hence I was wondering if there exists a way to do this in a safe and concise way? I created a very small example that reflects the issue I am having in my project. (in my project the issue appears in a constant member function of some class, but from my experiments the issue should be "faithfully" reflected in the example below by use of a constant variable of int instead for simplicity's sake). I am aware that I could theoretically use a separate template parameter "cT", but that would be horribly unsafe, as the caller of this function need not pass an object of "const T" as second argument ... I also understand that I could simply refrain from using templates at all and just specify this for every type. I was just wondering if what I am trying to achieve below can be done with templates. Thanks and have a nice day! :) template<typename T> bool ContainsElement(std::list<T>& findList, const T& elem) { for (auto& entry : findList) { if (entry == elem) return true; } return false; } int main() { std::list<int*> myList; const int testConst = 6; auto pointerToTestConst = &testConst; ContainsElement(myList, pointerToTestConst); // compiler screams }
The issue is in incompatibility between pointers: pointerToTestConst is of type const int* - non-const pointer to const integer. Therefore T=const int* myList is of type list<int*>, deducing T=int*. Since those types are not the same, compilation fails. Rightfully so, because elem would allow changing testConst if T=int*. The issue manifests regardles you passing elem by (const) reference or value. horribly unsafe, as the caller of this function need not pass an object of "const T" as second argument So what? They get a compiler error about the comparison. It is no more unsafe than your code right now. I would argue that a generic ContainsElement should not care what you pass to is as long as it compares equal to some element in the list, it is a match. Of course STL already offers this for std::find and std::ranges::find which also does not care and it is not called unsafe because of it.
72,818,787
72,825,935
OpenCV imshow fails with src_depth != CV_16F && src_depth != CV_32S in function 'convertToShow'
Code for operating my camera is giving me images as signed 32-bit integers, and I would like to turn this into an openCV Mat. When I have 16-bit signed integers, I do the following: int16_t x[100][100]; Mat A(100, 100, CV_16SC1, x); imshow("BLAH", A); This works. Similarly, when I have 8-bit unsigned integers I use uint8_t and CV_8UC1 and it works. I can also use double and CV_64FC1 and it works. Sadly, the following does not work: int32_t x[100][100]; Mat A(100, 100, CV_32SC1, x); imshow("BLAH", A); OpenCV throws a -215:Assertion failed exception on the imshow line, indicating the Mat was not properly loaded in the first place (I think). I have also tried using int instead of int32_t, but to no avail.
I added your error message for you. It says: /opencv/modules/highgui/src/precomp.hpp:155: error: (-215:Assertion failed) src_depth != CV_16F && src_depth != CV_32S in function 'convertToShow' That means imshow does not accept 32 bit signed integers (nor does it accept half floats). You need to give it anything but that. Convert your data to one of the supported types, which are currently: uint8, uint16, float, double. Mind the value range. For the accepted integers, it's the entire range. For floats, it's 0.0 to 1.0, that are mapped to black/white. If your values don't use the expected range, you might see an entirely black image (underexposed) or one that is mostly white (overexposed).
72,818,990
72,837,636
Qt retrieving reference out of a struct inside a QList
i have a struct "Material" which has a referencetype of Item& Item is a baseclass for many different Materials who can appear in a list. The struct also has an integer variable and also a QString variable. Those two are just give the amount to be used and a String of what type item must be casted back. struct Material { int amount; Item& item; QString itemtype; Material(int myamount,Item& myitem,QString myitemtype) : amount(myamount),item(myitem),itemtype(myitemtype){} }; As i have read here: initialize struct contain references to structs to have a reference sitting inside of a struct one need to define a constructor within the struct. as you can see in the upper Material struct. Now when i try to retrive the reference of that, like here: QList<Material> Mats = bp.Materials(); for(int i=0;i<Mats.count();i++) { Item& item = Mats[i].item; } i allways get an error like "use of deleted function 'Material& Material::operator=(const Material&)" I also tried already to define such a operator= but obviously if i try to return the rvalue which is const i can't do this because the lvalue is not const. and if i make a new instance of Material it is going to be an implicit copy constructor. My Question: What do i miss here? On the wish to make a reproduceable example, i may got to the problem. I have no solution for my one just yet but an idea what may have caused this: #include <QCoreApplication> #include <QList> struct Kram { QString& text; Kram(QString& s): text(s) {} }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString mytext= "Hello, World!"; Kram k(mytext); QList<Kram> liste; liste.append(k); for(int i=0; i<liste.count();i++) { QString& anothertext = liste[i].text; } return a.exec(); } When i compile this he tells me the exact same error message about the "Kram" struct. But this only appears if you do the struct in a Qlist and then try to get the reference inside of the struct out. just to mention the second error message is in both cases thisone: C:\Users\Rolf\Documents\Testprojekt\main.cpp:4: Fehler: non-static reference member 'QString& Kram::text', can't use default assignment operator
For all who stumble on this, i will post my fixed example code. But i highly recommend to read the comments from Scheff's Cat and sigma below my question. Because they give you some really important infos why this is happening. I my self will consider the idea of sigma to use the std::unique_ptr for my code. eyeball in the following code that now the struct holds a pointer but the constructer gets a reference so that there is no nullpointer. but still the object here in the main code can be assigned normaly meaning no pointer involved there. here is the code: #include <QCoreApplication> #include <QList> struct Kram { QString* text; Kram(QString& s): text(&s) {} }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString mytext= "Hello, World!"; Kram k(mytext); QList<Kram> liste; liste.append(k); for(int i=0; i<liste.count();i++) { QString* anothertext = liste[i].text; } return a.exec(); } thank you all for helping me finding out of this maze
72,819,590
72,823,104
How can I determine the index of the top item displayed in the drop-down list of a TComboBox?
How can I find the index of the top item in the drop-down list of a TComboBox? I know that a TListBox has a TopIndex property, but I can't find anything similar to this for a TComboBox. I'm using C++Builder in RAD Studio 10.4 Update 2.
Since FMX's TListBox does not have a TopIndex property, I'm going to assume you are referring to VCL instead. In the VCL, you can access the HWND of the TComboBox's drop-down ListBox by calling the Win32 GetComboBoxInfo() function on (or sending a CB_GETCOMBOBOXINFO message to) the HWND returned by the TComboBox::Handle property. And then you can send an LB_GETTOPINDEX message to the ListBox HWND. COMBOBOXINFO info = { sizeof(COMBOBOXINFO) }; GetComboBoxInfo(ComboBox1->Handle, &info); // or: SendMessage(ComboBox1->Handle, CB_GETCOMBOBOXINFO, 0, (LPARAM)&info); int index = SendMessage(info.hwndList, LB_GETTOPINDEX, 0, 0);
72,819,843
72,820,224
Optional argument after template parameter pack of supposedly known length
I am trying to have a kind of "invoke" function with an optional argument at the end: template <typename... T> void foo(void func(T...), T... args, int opt = 0) { func(args...); } void bar(int, int); int main() { foo(&bar, 1, 2, 3); } I would have expected this to work, since the parameter pack can be deduced from the first argument, but clearly the compilers have different ideas: Clang for example gives: <source>:11:5: error: no matching function for call to 'foo' foo(&bar, 1, 2, 3); ^~~ <source>:2:6: note: candidate template ignored: deduced packs of different lengths for parameter 'T' (<int, int> vs. <>) void foo(void func(T...), T... args, int opt = 0) ^ 1 errors generated. Compiler returned: 1 Why is it deducing a list of length 0? Can I force it to ignore args for the purposes of deduction? Or more generally, how can I make this work?
You could make it overloaded instead of having an optional argument. You'd need to move the "optional" to before the parameter pack though. The second overload would then just forward the arguments to the first, with the "default" parameter set. #include <iostream> template <typename... T> void foo(void(func)(T...), int opt, T... args) { std::cout << opt << '\n'; func(args...); } template <typename... T> void foo(void(func)(T...), T... args) { return foo(func, 0, args...); // forwards with the default set } void bar(int, int) {} int main() { foo(&bar, 1, 2); // prints 0 foo(&bar, 3, 1, 2); // prints 3 } You might want to move the optional all the way to the first position to let the function and its parameters be together. It's a matter of taste. Another option could be to exclude the optional parameter and only have the parameter pack and to extract the optional if it's present or use the default value if it's not. This requires that you restrict the signature of func to match the function you aim to call. #include <iostream> #include <tuple> template <class... T> void foo(void func(int, int), T&&... args) { int opt = [](T... args) { if constexpr (sizeof...(T) > 2) return std::get<2>(std::tuple{args...}); else return 0; // use the default }(args...); std::cout << opt << '\n'; [&func](int a, int b, auto&&...) { func(a, b); }(args...); } void bar(int, int) {} int main() { foo(&bar, 1, 2); // prints 0 foo(&bar, 1, 2, 3); // prints 3 } Building on the second version but giving a lot more freedom, you could introduce a separate parameter pack for func. If that pack has the same size as pack of arguments supplied, you need to pick a default value for opt. If it on the other hand contains more arguments than needed for the function, you can select which one of the extra arguments that should be used for opt. In the example below, I just picked the first extra parameter. #include <iostream> #include <tuple> #include <type_traits> #include <utility> // a helper to split a tuple in two: template <class... T, size_t... L, size_t... R> auto split_tuple(std::tuple<T...> t, std::index_sequence<L...>, std::index_sequence<R...>) { return std::pair{ std::forward_as_tuple(std::get<L>(t)...), std::forward_as_tuple(std::get<R+sizeof...(L)>(t)...) }; } template <class... A, class... T> void foo(void func(A...), T&&... args) { static_assert(sizeof...(T) >= sizeof...(A)); // separate the needed function arguments from the rest: auto[func_args, rest] = split_tuple(std::forward_as_tuple(std::forward<T>(args)...), std::make_index_sequence<sizeof...(A)>{}, std::make_index_sequence<sizeof...(T)-sizeof...(A)>{}); int opt = [](auto&& rest) { // if `rest` contains anything, pick the first one for `opt` if constexpr(sizeof...(T) > sizeof...(A)) return std::get<0>(rest); else return 0; // otherwise return a default value }(rest); std::cout << opt << '\n'; std::apply(func, func_args); } void bar(int a, int b) { std::cout << a << ',' << b << '\n'; } int main() { foo(&bar, 1, 2); // prints 0 then 1,2 foo(&bar, 1, 2, 3, 4); // prints 3 then 1,2 }
72,820,017
72,820,652
Ant/Make Compilation Error with File Path Having Spaces
Unable to produce some MVC to reproduce the issue. So trying to be clear & concise. We utilize ant/make The include path to building the C++ portion utilizes a header (jni.h) from the java installed directory Example Error (During Build Process) 3) *File.h(2): fatal error C1083: Cannot open include file: 'jni.h': No such file or directory make: *** [File.obj] Error 2* Another error also shown is: cl : Command line warning D9024 : unrecognized source file type 'Files\Java\jdk1.8.0_281\include', object file assumed cl : Command line warning D9027 : source file 'Files\Java\jdk1.8.0_281\include' ignored cl : Command line warning D9024 : unrecognized source file type 'Files\Java\jdk1.8.0_281\include\win32', object file assumed cl : Command line warning D9027 : source file 'Files\Java\jdk1.8.0_281\include\win32' ignored This is the include path as part of the compilation step (Yes this path exists) -IC:\Program Files\Java\jdk1.8.0_281\include Now when I copy the files necessary to a path that's called ProgramFiles\Java... (No spaces in ProgramFiles) it works fine. I have a variable retrieved from a .platform file which is utilized for the build, which defines JDK_HOME. I believe this file is utilized for ant/make builds and uses these defined variables in this file. Any ideas/paths as to ant or make not liking spaces in the include paths, or anything along those lines? I've looked at many resources online, but very hard to describe the issue. Problem clearly is the space in Program Files. Not sure what is so significant about this. Hoping the bullet points help in any information needed with anyone who could be familiar with this issue or might have leads. Thank you.
I'm not sure what ant has to do with this. But make recipes are just shell scripts (or, if you use Windows cmd.exe instead of a POSIX shell, batch files). Just like commands you'd write in a batch file or on the command line directly, you have to add quoting to paths that contain whitespace. You don't actually show us either the make recipe or even the complete compile (cl) command line that make invokes so we can't give you precise advice, but basically if you cut and paste the command line make invoked into your terminal prompt you'd get exactly the same errors about whitespace. Make is not magic: it only runs the commands you tell it to run. Just like you have to add quotes around paths containing whitespace when you run them from the terminal prompt, so too you need to add quotes to these paths when you run them from a makefile recipe.
72,820,497
73,077,225
Why have .a files been installed in Windows with Qt online installer?
I installed Qt 6.3.1 libraries pre-built with MinGW 11.2.0 64-bit using the online installer. The application crashes without entering the main function when I use any of Qt libraries in the Qt Creator while there is no problem if I use only C++ standart library. I guess the problem is in linking. Because I realized that there are .a files in the folder C:\Qt-mingw\6.3.1\mingw_64\lib, even though I am using Windows 10. Why are .a files installed instead of .lib files? How to solve this issue? Here are the the selections that I made when installing Qt libraries using the online installer:
After learning that the problem may be due to duplication of some library from here, I saw using dependency walker that my program uses libstdc++-6.dll in system32 instead of qt-mingw installation. So the problem solved when I copied that dll into my app's folder. But I wonder how to solve this by changing the path without copying libstdc++-6.dll into app's folder. Because even though I put qt-mingw bin folder at the very beginning in system path, app uses still the one in system32.
72,821,106
72,821,224
Is calling a private function from a public function good coding practice?
I'm wondering if calling a private function from a public function to achieve a cleaner syntax could cause any type of problems. #include<iostream> class tree{ private: struct node { int data; int counter = 1; node* left; node* right; }; node* getnewnode(int x) { node* temp = new node(); temp -> data = x; temp -> left = NULL; temp -> right = NULL; return temp; } node* recursiveinsert(int x, node* rootPtr) {// recursively insert a new node if(rootPtr==NULL) { // if the tree is empty, append the new node rootPtr = getnewnode(x); } else if(x <= rootPtr->data){ // if x is lesser than the node value, make a recursive call with the left subtree as root rootPtr -> left = recursiveinsert(x, rootPtr -> left); } else { //if x is greater than the node value, make a recursive call with the right subtree as root rootPtr -> right = recursiveinsert(x, rootPtr -> right); } return rootPtr; } public: //store address of root node node* root = NULL; void insert(int x) { root = recursiveinsert(x, root); } }; Using the tree class, instead of calling in main: int main(){ tree t; t.root = t.recursiveinsert(10, t.root); } I thought it'd be cleaner to call this instead: int main(){ tree t; t.insert(10); } Is this a good coding practice?
For starters the data member node* root = NULL; shall not be public. Secondly the function recursiveinsert should be declared at least as a static member function. It is better to declare and define it like static void recursiveinsert( node * &rootPtr, int x ) { if ( rootPtr == nullptr ) { rootPtr = getnewnode(x); } else if ( x < rootPtr->data ) { recursiveinsert( rootPtr -> left, x ); } else { recursiveinsert( rootPtr -> right, x ); } } There is nothing wrong to call a private member function from a public member function. For example it is not rare when a constructor of a class calls a private member function in its mem-initializer list. The function getnewnode can look simpler. For example node* getnewnode( int x) { return new node { x, 1, nullptr, nullptr }; }
72,821,847
72,821,905
How to merge different operators with the same logic in C++ class for not copypasting
Is it possible to merge some operators of class that have same logic but different operators to not copypasting. For example, I have class with operators +=, -=: class Matrix { public: Functor& operator+=(const Functor& rhs) { for (int i = 0; i < num; ++i) { v[i][j] += rhs.v[i][j]; } return *this; } Functor& operator-=(const Functor& rhs) { for (int i = 0; i < num; ++i) { v[i][j] -= rhs.v[i][j]; } return *this; } private: int rows_ {}; int columns_ {}; std::vector<std::vector<double>> matrix_; }; Does C++ has something like: Functor& operator(+=, -=)(const Functor& rhs) { for (int i = 0; i < num; ++i) { v[i][j] (+=, -=) rhs.v[i][j]; } return *this; }
You can do it by passing a lambda to a common implementation: class Matrix { private: template<typename Op> Functor& opImpl(const Functor& rhs, Op op) { for (int i = 0; i < rows_; ++i) { for (int j = 0; j < columns_; ++j) { Op(v[i][j], rhs.v[i][j]); } } return *this; } public: Functor& operator+=(const Functor& rhs) { return opImpl(rhs, [&](double& l, const double r) { r += l; }); } Functor& operator-=(const Functor& rhs) { return opImpl(rhs, [&](double& l, const double r) { r -= l; }); } private: int rows_ {}; int columns_ {}; std::vector<std::vector<double>> matrix_; }; Normally, you'd first implement operator+ and operator- and implement operator+= and operator-= in terms of the former. In that case, you can use std::plus<double>() and std::minus<double>() for the lambda if you're in c++14 or later (thx @StoryTeller). You can further save space by either having the operators in a base class, having it as using from a namespace or simply by a macro: #define IMPLEMENT_OP(RET, OP, ARG, T) \ RET operator ## OP ## (ARG rhs) { \ return opImpl(rhs, T::operator ## op); \ } Another way to solve this - still by delegating - is to use constexpr if: class Matrix { private: template<char op1, char op2 = ' '> Functor& opImpl(const Functor& rhs) { for (int i = 0; i < rows_; ++i) { for (int j = 0; j < columns_; ++j) { if constexpr (op1 == '+' && op2 == '=') { v[i][j] += rhs.v[i][j]; } if constexpr (op1 == '-' && op2 == '-') { v[i][j] -= rhs.v[i][j]; } // TODO: further ops, error handling here } } return *this; } public: Functor& operator+=(const Functor& rhs) { return opImpl<'+', '='>(rhs); } Functor& operator-=(const Functor& rhs) { return opImpl<'-', '='>(rhs); } private: int rows_ {}; int columns_ {}; std::vector<std::vector<double>> matrix_; };
72,821,884
72,821,927
Replace memcpy with memcpy_s with an unsigned char
Let's suppose we have a legacy code that performs this operation: unsigned char* dest = new unsigned char[length]; memcpy(dest, source, length); where the pointer source is passed as input parameter of that method. length is an unsigned long variable. Now I want to replace the memcpy call, considered not secure, with the secure version of it, so with memcpy_s. In base of its documentation, this method takes three parameters, destination Size of the destination buffer, in bytes for memcpy_s and wide characters (wchar_t) for wmemcpy_s. the source the number of characters to copy. I'have some concern regarding the fourth parameter. Shall it be something like that: err = memcpy_s(dest, sizeof(dest), a2, length * sizeof (unsigned char)); Is that correct? Thanks
memcpy_s() is not fundamentally "more secure". It just performs a few sanity checks. In your case, some of these are even redundant. So, if you want to "defend" your function implementation from invalid arguments, you could make sure source is not nullptr; all the other "security" checks are guaranteed to pass anyway: The amount copied is the same as the destination size, no larger. The destination is not nullptr - you just successfully allocated it. If you were able to allocate length, then it can't be more than RSIZE_MAX. That's it, no need to use memcpy_s(). Also, sizeof(unsigned char) is 1, necessarily.
72,821,999
72,822,874
auto-conversion from struct to long in liinux C++?
I'm converting a C++ Linux program (I don't know what compiler) to Visual C++ 2019. I'm seeing some strange code. Today's example is: long offset = timezone; I also see: offset = timezone - 3600; timezone appears to be defined as: struct timezone; It should be defined as: struct timezone { int tz_minutewest; int tz_dsttime; }; I don't see any evidence that it is. It appears that the code is using timezone as if it is timezone.tz_minutewest. Do some compilers do an automatic conversion?
The struct timezone you are showing is a Linux/glibc-specific type defined in <sys/time.h>. See man gettimeofday. There is also a variable named timezone in <time.h> which is specified by POSIX (X/Open). See man tzset for information about the Linux/glibc implementation of that feature. Of course it is not clear whether you are referring to either of these or something else entirely. However in context where the name is used in your example it cannot name a type. Even if you have both headers included, using timezone in an expression will refer to the variable, not the type. C++ allows collision between the name of a type and a non-type. In most contexts the non-type will be preferred if not explicitly prefixed with struct or similar keywords.
72,822,019
72,822,241
Incorrect results: mapping c++ array to Eigen Matrix
I have used the map feature before to map existing memory into Eigen matrices, however when trying to map an fftw c++ array, I am getting wrong results, almost if a portion (a slice?) of the array is being mapped into an Eigen matrix and not the entire memory block. This is the code I am using: static const int nx = 10; static const int ny = 10; static const int nyk = ny/2 + 1; static const int nxk = nx/2 + 1; static const int ncomp = 2; fftw_complex *uhk; // this is pert Te uhk= (fftw_complex*) fftw_malloc((((nx)*(ny+1))*nyk)* sizeof(fftw_complex)); memset(uhk, 42, (((nx))*nyk)* sizeof(fftw_complex)); for (int i = 0; i < nx; i++){ for (int j = 0; j < nyk; j++){ for (int k = 0; k < ncomp; k++){ uhk[i + nyk*j][k] = //taking fft of some expression } } Eigen::Map<Eigen::MatrixXcd, Eigen::Unaligned> uhOut(reinterpret_cast<std::complex<double>*>(uhkOut),nyk,nx); std::cout << uhOut<< '\n'; The results I am getting are, (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.58,-0.28) (0.95,-0.46) (0.95,-0.46) (0.58,-0.28) (0.00,-0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.59,-0.09) (0.95,-0.14) (0.95,-0.14) (0.59,-0.09) (0.00,-0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) (0.00,0.00) But, the correct result should be: (0.00,0.00) (5.14,0.00) (8.32,0.00) (8.32,0.00) (5.14,0.00) (0.00,0.00) (-5.14,0.00) (-8.32,0.00) (-8.32,0.00) (-5.14,0.00) (0.00,0.00) (2.43,-2.35) (3.93,-3.81) (3.93,-3.81) (2.43,-2.35) (0.00,-0.00) (-2.43,2.35) (-3.93,3.81) (-3.93,3.81) (-2.43,2.35) (0.00,0.00) (0.52,-1.04) (0.85,-1.68) (0.85,-1.68) (0.52,-1.04) (0.00,-0.00) (-0.52,1.04) (-0.85,1.68) (-0.85,1.68) (-0.52,1.04) (0.00,0.00) (0.57,-0.55) (0.93,-0.89) (0.93,-0.89) (0.57,-0.55) (0.00,-0.00) (-0.57,0.55) (-0.93,0.89) (-0.93,0.89) (-0.57,0.55) (0.00,0.00) (0.58,-0.28) (0.95,-0.46) (0.95,-0.46) (0.58,-0.28) (0.00,-0.00) (-0.58,0.28) (-0.95,0.46) (-0.95,0.46) (-0.58,0.28) (0.00,0.00) (0.59,-0.09) (0.95,-0.14) (0.95,-0.14) (0.59,-0.09) (0.00,-0.00) (-0.59,0.09) (-0.95,0.14) (-0.95,0.14) (-0.59,0.09) Am I misunderstanding the point of map here? Why are my results sliced like that?
You're computing your offsets wrong. [i+nyk*j] is not correct. The largest value of j is (nyk-1). I think you meant for it to be [i*njk+j]. To diagnose this sort of problem, I suggest doing uhk[j + nyk*i][k] = (k==0)?i:j; // Note I swapped i/j in the offsets This will create a matrix where the real portions match the column number, and the imaginary portions are the row number. A simple pattern like this makes it obvious the values aren't being correctly written the expected memory locations.
72,822,061
72,822,733
How to replace decltype(f()) with std::invoke_result_t, where f is a lambda with non-type template parameter?
How to replace the following with std::invoke_result_t? decltype(f.template operator()<0>()) Here's more context: template <size_t I, typename Functor> consteval void apply(Functor&& f) { using ResultType = decltype(f.template operator()<0>())>); // ... More stuff ... f.template operator()<I>()); } void test() { apply<5>([]<auto I>() { }); }
You still need decltype, because invoke_result_t requires the type of the method followed by the type of the class. But here you go: #include <cstddef> #include <type_traits> template <size_t I, typename Functor> consteval auto apply(Functor&& f) { // using ResultType = decltype(f.template operator()<0>()); using ResultType = std::invoke_result_t< decltype(&std::remove_cvref_t<Functor>::template operator()<0>), Functor>; // ... More stuff ... return ResultType(f.template operator()<I>()); } void test() { apply<5>([]<auto I>() { }); }