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
74,081,089
74,116,547
How can I pass data in the JVM between the agent dll and a debugger GUI executable?
I want to design a native agent for the JVM via the Java Virtual Machine Tool Interface for C++. I want to also design a executable for the user to see what is going on within the JVM and this will be a GUI designed in C++ Qt. I setup a solution in Visual Studio with 2 projects: agent project JVMTI dll Qt EXE GUI proj...
In your scenario, there are two different processes: JVM with the agent library GUI executable To make them talk to each other, you need an IPC (inter-process communication) mechanism. The linked article lists all typical IPC approaches. Sockets, pipes or shared memory are the most common for a purpose like yours. Fo...
74,081,768
74,082,223
How to merge two structs with same structure but different content?
I have two structs: struct DEF { DEF(std::string,double foo,double); ~DEF(); //---- theory's functions ----// double V_of_phi(double,double); double dV_of_phi(double, double); ... double metricStartingPoint; double scalarStartingPoint; ...} struct R2 { R2(std::string,double...
This cries for applying "strategy design pattern". Please read about it here, or in many available books about "design patterns". You would basically implement an abstract base class for the strategy and then derive the specific strategies from that. In your terminology this would be the equivalent of "theory". In the ...
74,081,795
74,082,553
Why does my boost::interprocess shared memory string vector code trigger segfault?
I have the following minimally reproducible code of using several child processes to append strings to a shared vector. But at some executions, my prorgam either freezes or goes into segmentation fault when all the child process finish. At other times, it works with no issues. When the segfault does happen, it seems to...
The problem is with the mutex. You are creating a new mutex for every process. You have to make sure there is a single mutex that is shared by all processes. Just moving the declaration of mutex outside the for-loop isn't enough though; the mutex has to be stored inside the shared memory segment for this to work, see t...
74,081,887
74,082,011
Finding the most divisible number in a 100,000 range
I'm a student in the 10th grade and our teacher assigned some exercises. I'm pretty advanced in my class but one exercise is just isn't coming together as I want. The exercise is as follows: Given the numbers between 100,000 and 200,000, find the number with the most divisors (as in which number can be divided with th...
Using @AhmedAEK 's response: replace j<=i/2 with j<=sqrt(i), you only need to loop up to that, also #include <math.h> at the top, you also need to multiply the total divisors by 2, since there is a number above the sqrt that reflects the number below the sqrt. ie: 1000 is 10 x 100. void f3() { int mostcount = 0, ...
74,081,911
74,082,065
swap 2 node in doubly linked list without swapping the data C++
Im trying to swap position of two node in doubly linked list without swapping the data, this is my code, it came up with wrong answer when run through this testcase: the list length: 20 the list: 2158 2398 300 2268 3655 765 3792 4038 1761 4762 1292 3200 3882 962 488 1938 3757 3122 302 640 positions to swap: 9 12 the ri...
The right answer, as well as the name of the function you are supposed to write, suggest that you should reverse a sublist. Your code doesn't attempt to do that. It swaps positions of the first and the last nodes of the sublist. These are two different operations. The reverse operation generally needs a loop to iterate...
74,082,118
74,082,148
What if template argument explicitly specified to be function type
I tried the code below (https://godbolt.org/z/rcfPK451M) bool cmp1(int &a, int &b) { return a < b; } template<typename T> struct S; template<typename T> void test(T cmp) { S<T> t; S<decltype(cmp)> s; } void foo() { test<decltype(cmp1)>(cmp1); } And got the following compile error <source>:5:10: error: ...
You are declaring a variable with that function type (the argument cmp), so the type decays into a function pointer type. You cannot have a variable with a function type, only a pointer to a function. The standard says [temp.deduct]/3: After this substitution is performed, the function parameter type adjustments descr...
74,082,122
74,082,245
С++ how to make a gif from bmp
I need to implement gif from bmp to animate Abelian sandpile model using only c++ standard library.
Ideally, your starting points would be specifications for GIF and BMP. The GIF Specification, is a pretty easy thing to find. Unfortunately, (at least to the best of my knowledge) Microsoft has never brought all the information about BMP format into a single document to act as a specification. There's a lot of documen...
74,082,584
74,082,645
When insert()ing into a std::map why is the copy-contructor called twice?
Why is the copy-constructor called twice in this code? // main.cpp #include <iostream> #include <map> #include <string> using namespace std; class C { private: int i_; char c_; public: C(int i, char c) : i_(i), c_(c) { cout << "ctor" << endl; } C(const C& other) { cout << "copy-ctor" << endl; } }; int main(...
The map value type is std::pair<const int, C>. C is not movable, thus std::pair<const int, C> is not movable. m.insert({"hello", C(42, 'c')}); Creates C and copies it to a pair, local variable value in insert, then copies a pair to a map bucket. m.emplace("hello", C(42, 'c')); will copy C only once to a bucket. Compile...
74,082,811
74,101,910
What is the best way to store authentication (login) in a system when a user has been authenticated using shadow in Linux with C++
I have a project called kos and it's a simple SUID tool, recently as a lot of people in private have been asking me I added authentication storing/remembering, but it's not that good So what happens basically is: Verify that the user has entered the correct password If the password is correct set the temp_validate_use...
As @ThomasWeller sudo does the same thing, meaning it's secure enough, I dropped the terms on the dir from 744 to 711 and file perms from 744 to 600 Thank you @ThomasWeller once again
74,082,864
74,083,695
how to insert vector element into link with cURL c_str() function in C++?
I'm working on a c++ code that fetches a variable from a text file and adds it to a fixed url, similarly to the following example: int x = numbers[n]; string url = "http://example.com/" + x; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); but I'm getting this error message after compiling Protocol "tp" not supported...
You are adding an int to a const char* pointer (that was decayed from a string literal of type const char[20]). That will offset the pointer by however many elements the int indicates. Which, in your case, appears to be 2, which is why CURL thinks the URL begins with tp: instead of http:. Your code is basically the e...
74,082,882
74,085,642
Qt C++ - How to pass slider value into function that will be slotted into another slider?
I'm super new to Qt so bear with me. I'm doing my class assignment in which I need to create a window with 3 sliders and a label in which I can load my image. These 3 sliders are corresponding to HSL (Hue, Saturation, Luminance) that of course will change my image. Math needed for these transformations is done. I have ...
You can't connect signals and slots like that. Try use my solution: Remove the parameters of MainWindow::changeHSL(int h, int s, int l), replace the h, s, l into the values of h, s, l sliders (They're ui->horizontalSlider, ui->horizontalSlider_2, ui->horizontalSlider_3), like this: void MainWindow::changeHSL() { in...
74,082,951
74,083,137
How do I translate reinterpret_cast<WPARAM>(reinterpret_cast<LPCREATESTRUCT>(lParam)->hwndParent) to VB6?
I neeed to convert a piece of code from C++ to VB6. Specifically, this one: reinterpret_cast<WPARAM>(reinterpret_cast<LPCREATESTRUCT>(lParam)->hwndParent) Can somebody tell me what this would look like in VB6? I am not experienced enough in C++ to understand what exactely this does. Thank you very much! About the back...
That's just the handle of the form where the control resides, you can replace that code with Me.hWnd.
74,083,171
74,083,255
Implicit instantiation of undefined template 'boost::enable_shared_from_this<TCP_Connection>'
I've been trying to follow a Boost tutorial to integrate Asio for a few hours now, but I have a class inheritance problem with Boost's enable_shared_from_this class. I've included everything I needed for this class but the problem still persists and I'm not sure what this message means Implicit instantiation of undefin...
#include <boost/enable_shared_from_this.hpp>
74,083,298
74,083,904
How can I access a private (non-static) method in C++?
Currently I am working on a project where I want to control a model train for a nice showcase. I have multiple locomotives which all have a unique address (just think of it as a UUID). Some locomotives have a headlight, some of them have a flashing light, some have both and some of them have none. My base class is this...
You have misunderstood how class inheritance works: Inheritance establishes an is-a relationship between a parent and a child. The is-a relationship is typically stated as as a specialization relationship, i.e., child is-a parent. There are many ways you can tackle what you want to achieve here, but this is not it. Y...
74,083,370
74,083,417
How template class resolve member methods
I used to do what suggested here https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl to separate template header and implementations. We basically explicitly instantiate the desired template at the end of .cc file so that the compilation unit contains enough information for the linker to work with...
No, if you explicitly instantiate a member (including a constructor), then only the definition for that member will be explicitly instantiated. The explicit instantiation may cause implicit instantiation of other members of the class, but that isn't enough to use these members in a different translation unit. If you do...
74,083,711
74,091,640
How do I create a timer that I can query during the program and whose format is int, long or double?
I want to start a clock at the beginning of my program and use its elapsed time during the program to do some calculations, so the time should be in a int, long or double format. For example i want to calculate a debounce time but when i try it like this i get errors because the chrono high resolution clock is not in a...
I find the question misguided in its attempt to force the answer to use "int, long, or double". Those are not appropriate types for the task at hand. For references, see A: Cast chrono::milliseconds to uint64_t? and A: C++ chrono - get duration as float or long long. The question should have asked about obtaining the d...
74,083,798
74,083,833
to check the multiple of five and two
#include using namespace std; int main () { int multiple; cout << "Please give a number you want to check the multiple of: "; cin >> multiple; if ((multiple % 5 == 0), (multiple % 2 == 0)); { cout << multiple << " is multiple of five. " << endl; cout << multiple << " is the multip...
It shows an error in the else statement because C++ doesn't expect a semi-colon (;) at the end of your if statement. When C++ sees a ; your if-statement is considered done. It has no effect — it just skips it. Also, your if-syntax is wrong. It shouldn't have a comma ,. This should be what you intended to do: if (multip...
74,083,911
74,084,118
private static member in base class being acessed by derived classes
I am currently using the old VC++98, and I am facing issues trying to encapsulate a static member declared as private in a base class. I wish that the derived classes do not have access to such static member, but I can't find out how. The following example code is compiling and running without problems (whereas it shou...
How can I make the static member inaccessible in the derived class? Use a compliant compiler. The code doesn't compile in standard C++ (any version) just like you expect.
74,084,022
74,084,028
C++11 namespace scoping with functions
Right now, I am coding a complex project in c++. I've simplified the example, where in a namespace I'm defining two functions, that both need each other. namespace Example { void foo() { bar(); } void bar() { foo(); } } Is there any way to fix my issue, without separating the functions f...
You can forward-declare inside a namespace exactly the same way you can do it at global namespace scope: namespace Example { void bar(); void foo() { bar(); } void bar() { foo(); } } However, as for any function, if these are functions defined in a header file shared between multiple...
74,084,081
74,084,110
difference between size_t and int in a "Plus One" problem algorithm
vector<int> plusOne(vector<int>& digits) { int n = digits.size(); for (int i = n - 1; i >= 0; i--){ if (digits[i] < 9){ digits[i]++; return digits; } else{ digits[i] = 0; } } digits.insert(digits.begin(), 1); return digits; } ...
Because size_t is an unsigned type. If i is a size_t, then i >= 0 is always true because, by definition, an unsigned value is never less than 0. To make it work with a size_t type it will be necessary to adjust the overall logic, in order to accommodate it. Something like: for (size_t i = digits.size(); i-- > 0; ){
74,084,223
74,084,224
Difference between lambda and member function pointer
In my answer here, Barry pointed out that it's better to call views::transform(&Planter::getPlants) because views::transform([](Planter const& planter){... accidentally copies. #if 1 auto plants = planters | std::views::transform([](Planter const& planter){ return planter.getPlants();}) | std::views...
Oh I actually know this one. The deduced return type of the lambda actually decays the const ref qualifiers of getPlants. You can fix this by declaring the return type of the lambda to be decltype(auto) views::transform([](Planter const& planter) -> decltype(auto){...}); https://godbolt.org/z/ocK5PG1z1
74,084,270
74,084,592
Can you achieve fn(x1 ^ fn(x0)) with a fold expression?
Is it possible to achieve the following using a fold expression? template<class... Args> auto foo(Args... args) { //calling foo(x0, x1, x2) should be exactly equivalent to //calling fn(x2 ^ fn(x1 ^ fn(x0))) }
If you insist on a fold expression, something along these lines could probably be made to work (not tested): template <typename T> struct Wrapper { T& val; }; template <typename T, typename U> auto operator^(Wrapper<T> l, Wrapper<U> r) { return Wrapper(r.val ^ fn(l.val)); } template<class... Args> auto foo(Args.....
74,084,392
74,097,720
How to declare context type whe using multiple 'with' directives?
I have known that it is possible to get information like position_cache and error_handler at the same time by using multiple with directives refer to this doc: https://www.boost.org/doc/libs/1_75_0/libs/spirit/doc/x3/html/spirit_x3/tutorials/annotation.html It can be configured like this when initializing the parser wi...
Note how context chains to the underlying context (phrase_context_type). You can rinse-repeat: using iterator_type = std::string::const_iterator; using phrase_context_type = x3::phrase_parse_context<x3::ascii::space_type>::type; using error_handler_type = error_handler<iterator_type>; using error_context_type =...
74,085,227
74,170,250
How to deal with IntelliSense not being able to recognize C++20 features?
It's not new that IntelliSense often lags behind C++ development. For instance, the code below is valid in C++20, using the new Template String-Literal Operator feature. template<typename C, size_t Size> struct StrWrapper { std::array<C, Size> m_buf; consteval StrWrapper(const C(&str)[Size]) : m_buf{} { ...
Depending on how you use the return value of your operator afterwards, you might satisfy IntelliSense by providing a dummy implementation just for IntelliSense: template <typename C, size_t Size> struct StrWrapper { std::array<C, Size> m_buf; consteval StrWrapper(const C (&str)[Size]) : m_buf{} { std::cop...
74,085,373
74,085,449
The correct syntax of a member which is a class template
I have a class : template<typename F1, typename F2, typename F3> class A { F1 f1; F2 f2; F3 f3; A(F1 f1_, F2 f2_, F3 f3_) : f1{f1_}, f2{f2_}, f3{f3_} {}; apply_f1() {f1();}; apply_f2() {f2();}; apply_f3() {f3();}; } and have the ...
You could declare a as A<std::function<void()>, std::function<void()>, std::function<void()>>. That will let it accept capturing lambdas: #include <functional> class B { public: B() : a([this] {}, [this] {}, [this] {}) {} private: A<std::function<void()>, std::function<void()>, std::function<void()>> a; }; N...
74,085,474
74,085,606
How to transform an adjacency matrix into an incidence Matrix
I'm trying to transform the adjacency matrix into an incidence matrix of an undirected graph. For edges : (1, 2), (1,5), (1,6), (2,3), (2,5), (3,4), (3,5), (4,5), (5,6) Adj matrix is : 0 1 0 0 1 1 1 0 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 0 1 1 1 1 0 1 1 0 0 0 1 0 and I expect the result for the incidence matrix to be 0 1 0 0...
The ideas in the code are correct. But the indexing in the array is wrong. Indexing should start at 0. Note: this also applies when setting up the adjacency matrix. The numbers you use to name the vertices/nodes where originally 1,2,3,4,5,6. I propose to call them 0,1,2,3,4,5. Your original edge (1,2) then becomes (0,1...
74,085,748
74,087,387
Registering callbacks in Lua
I have the following structure (more general criticism on architecture welcome): I have a rather large C++ program doing zillion things. To provide scripting a large number of lowish level commands are handled by Lua. Each "command" has an associated Lua fragment that's called when "command"must be executed. Lua fragm...
The C function just need to be in the following form. static int registerCallback(lua_State* L) { const char* callbackName = luaL_checkstring(L, 1); //make a copy if you want to save it out of the scope return 0; } lua_register(L, "registerCallback", registerCallback); Then in lua you can pass the name to...
74,086,666
74,087,067
Is this the correct way of implementing the Consumer Producer problem with multiple Producers?
I'm new to multi-threading programming and I was wondering if there are some best practices when trying to implement the Consumer Producer problem with multiple Producers. This is my current implementation and it seems to work fine, my main doubt is regarding the use of mtx.lock() (for example if I should use a lock_gu...
Overall, this looks fine to me. The spin wait while(g_n==0); is a bit expensive but I guess this is pat of the example and this part will not be used in production. Otherwise, it is better to replace it with a passive waiting approach (typically another wait condition or a semaphore). for example if I should use a loc...
74,086,758
74,086,778
What purpose does the dot( . ) fulfil in this piece of code
In an example that's in my C++ book, I've found this piece of code at the end of an example problem, which verified if 3 integers were in an arithmetic progression. if (b==(a+c)/2.) I don't think I've seen the dot after 2 ever used in such a way and I don't know what it's purpose is here.
2. is a double literal. It's the same as 2.0. Integer division is different than floating point division, so in some cases having a double instead of an int makes an important difference. Although this form is perfectly valid, for readability purposes often 2.0 is preferred. In some (not all) newer languages derived f...
74,087,025
74,087,876
Generate explicit instantiations with multiple parameters with preprocessor
In my project, I want to have a bunch of explicit instantiations of my templated functions to reduce build time. Now I have a lot of functions, which can have different templates. For this reason (and in case I want to have more of them) I do not want to type them manually, but have them generated by the preprocessor. ...
You can add to your macros like so to achieve a somewhat maintainable list: #define GEN_X(f) REP_INT(3, f) #define GEN_Y(f, x) f(x, real) f(x, bool) f(x, index) #define GEN_Z(f, x, y) f(x, y, 0) f(x, y, 1) // GEN_F3 = generate functions with at least 3 arguments #define GEN_F3(x, y, z) template bool match_any<x, y, z>...
74,087,188
74,087,263
Why this constexpr expression gives me an error?
In the code below, constexpr for the line 2 does not give an error, but line 1 does. #include <iostream> using namespace std; class ComplexNum{ public:constexpr ComplexNum(int _r=0,int _i=0):r(_r),i(_i){} private: int r,i; }; int randGen(){ return 10; } constexpr int numGen(int i,int j){ return i+j; } int mai...
The compiler can't compile line one because randGen() is not constexpr. The compiler can't magically tell if a function is constexpr. Maybe it looks constexpr, but you actually want it to run at runtime. For that reason, the compiler doesn't evaluate expressions which are not marked constexpr explicitly. Do this: #incl...
74,087,799
74,087,860
I read the input number with getchar(), why is the number reversed in the linked list?
I typed 1234, but the list has 4,3,2,1 in it. I suspect the problem is getchar() itself, or a function in the class, but I have no way to find out. The link class is responsible for some linked list operations, such as deletion, insertion, etc., while the node class is responsible for creating and assigning nodes. The ...
With the insert you inserted to the FRONT of the list. So you had "1", then "2->1" ... If you want to insert to the end, don't insert at the head, but hake a Node* tail in the class Link and an insert_end function as //... Node* temp; void insert_end(const Node &cache){ Node *temp = new Node(cache); tail->next=...
74,088,267
74,088,346
C++ Custom iterator for circular buffer, how to implement end()?
I have written a circular buffer of size N. I've also written a custom iterator. I'm using them for logic like this: auto iter = circular_buffer.begin(); while(iter != circular_buffer.end()) { ++iter; } What is the implementation for end()? Usually it should point to the last element + 1, but if the buffer contain...
Note: the following assumes that the circular nature of the buffer is a property that is being exposed to the user for their use, rather than being an implementation detail of the system (as is the case for std::list implementations). Giving a circle a proper "range" is something of a problem since... it's a circle. It...
74,088,322
74,103,811
Are IUnknown AddRef and Release thread safe?
Are IUnknown AddRef and Release interfaces are thread safe (atomic)? I know what they do are incrementing/decrementing reference counts, but I wonder how they do. Particularly, IUnknown interface that inherits to Direct 3D components such as ID3D12DeviceChild. Version of Direct 3D is 12 if necessary. The reason why I'm...
TL;DR: For Direct3D 11, Direct3D 12, and DXGI, all use of the IUnknown methods should be 'thread-safe'. For Direct3D 11, the methods of ID3D11Device are all 'thread-safe' by design. The methods of ID3D11DeviceContext are not 'thread-safe'. That said, you can safely call AddRef and Release on all ID3D11DeviceChild-deriv...
74,088,402
74,088,602
Overload the ""_something operator on identifiers
Is possible, in C++, to overload the ""_something operator for function identifiers or callables in order to make it have custom behaviour? I recently saw something similar in this cppcon video, where the presenter is exposing how to build a unit test framework using modules, zero macros... but I am not understanding w...
The UDL operator "" is just a function call. Functions can return anything. They can, for example, return an object type which has an overloaded operator(), and is therefore callable. They can return an object type with an overloaded operator=, and is therefore assignable. Etc. It's not about how you overload the UDL o...
74,089,280
74,089,598
value return by cstyle cast of a variable is prvalue or lvalue?
AFAIK, if you cast to non-reference type, you get an prvalue. int x = 234; (int)x = 23; std::cout << x << "\n"; Output : 23 (in msvc) In GCC and Clang, cstyle cast return a prvalue (as expected), meanwhile in MSVC, it return an lvalue. Am i missing something or it is an bug in MSVC ? see live demo here
If you cast to an lvalue reference type you will get a lvalue. If you cast to rvalue reference type you will get a xvalue. If you cast to non-reference type you get an prvalue. So, you should get a prvalue here. Use the latest version of c++ in msvc, you will get your expected output. Use flag : /std:c++latest
74,089,461
74,089,470
Pointer as an argument in function pointer
Ok so I have a question. How to make a pointer as a argument inside a function pointer? I tried this: void (*myFunction)(*myClass); or void (*myFunction)((*myClass)); But first return error: excepted identifier before * token and second one same but with '('. Any help appreciated. Edit: its inside class definition ...
Try this instead: void (*myFunction)(myClass*); When declaring a pointer for a variable or function parameter, you need to specify the type before the *, and the name after (in a function parameter, the name is optional). So, a pointer to a type named myClass would be declared as myClass* rather than *myClass. The reas...
74,089,609
74,089,878
How to reuse an IMFSample without consuming additional memory
I wrote a screen video capture program in C++ /CLI. I capture the video 30 times a second and display it in a picture box. My idea was to copy the IMFSample to a reusable output sample then free the source sample to control memory usage. Although I call sampleOut->RemoveAllBuffers() prior to sampleOut->AddBuffer(destBu...
The question you are interested in is how to reuse samples instead of allocating them each time. The primary call you want to avoid is MFCreateMemoryBuffer because it is the actual memory consumer, not the buffer attachment/detachment from sample objects. The ideal solution is along these lines: you create a memory al...
74,089,619
74,089,817
Proportional scaling a window in Qt
How can I lock the aspect-ratio for resizing the window of my application? For Example aspect-ratio: 16/9.
If you mean you want to be prevent the user from resizing the away from a fixed 16:9 ratio (so e.g. if the user drags the window shorter, it would automatically become thinner as well), I'm not sure that's possible via the Qt API, because window-resizing is handled by the OS's window manager, not by the Qt library itse...
74,089,679
74,089,746
Trouble passing a function pointer to a method from main in C++
I have the following set up: poster.h template<class T> class Poster { private: unique_ptr<Poster<T>> testPtr = nullptr; public: void post(void (*callback_function)(T), T data) { post2(testPtr, callback_function, data); } void post2(unique_ptr<Poster<T>> p, void (*callback_functi...
In post2(), you take unique_ptr<Poster<T>> by value. That only works if you pass it an rvalue reference ('temporary', or something in std::move()). From your example it's not apparent if you really need unique ownership inside post2() (not generally, but in the function). If you don't need ownership, you might take uni...
74,089,773
74,089,822
How can I give a global callback function a local instance?
In global namespace I have a GLFW callback function: void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) { } } This function must recieve an object from local namespace of main function: int main() { ....
Set the user pointer to window and retrieve it in the callback. glfwSetWindowUserPointer(window, &lightSphere); glfwSetKeyCallback(window, key_callback); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { Sphere* sphere = static_cast<Sphere*>(glfwGetWindowUserPointer(window)); }
74,090,088
74,090,209
Different results of constexpr function during runtime vs compile time
I have this code below that recursively traverses the nodes of a graph (for simplicity, only the edges are shown here). I would expect the result of the count_dfs() function to be 4 regardless of whether the function is evaluated at runtime or compile time. On MVSC this isn't the case. It works as expected on Clang and...
It looks like an issue with how MSVC treats views. Here is a somewhat ugly but equivalent code that works without views: #include <iostream> #include <ranges> #include <array> struct Edge { int from{}; int to{}; }; template<std::size_t n> constexpr auto node_input_edges(std::array<Edge, n> const& edges, int id) {...
74,090,696
74,090,810
using a const static array in constructor result in 'warning ... is used uninitialized in this function'
I am trying to understand a compiler warning. I have a simple class #pragma once #include <framework/project_definitions.hpp> #include <framework/free_rtos/free_rtos.hpp> #include <modules/net/imqtt_client.hpp> #include "mqtt_command_base.hpp" namespace application::commands { class check_alive_command : public m...
It's simple, really. You have two variables named _payload_buffer. One is your static constant, and the other one is one of mqtt_command_base's members. When you refer to _payload_buffer in check_alive_command's constructor, you're really using the member, not the static variable. So of course, it is uninitialized at t...
74,090,771
74,090,928
How to check whether an element exists in an array as in Python using "in"
A user has to select a choice from the menu, and the program's goal is to check whether the user has selected a valid choice or not. In python I would run a while loop and compare them using "in": (userChoice in validChoices). How do I do that in C++ using a while loop? Valid choices are stored in this variable: const ...
You can simply call auto it = std::find(std::begin(validChoices), std::end(validChoices), userChoice); by checking statement if(it != validChoices.end()) it means that your choice have been found in the validChoices, because userChoice value have been found before validChoices end structure iterator. If it would be v...
74,090,931
74,090,952
Can't add numbers to an existing index in an array
I'm new to C++ and can't understand what is wrong here. This code was made for problem 339A from CodeForces. I get an unsorted sum str input with numbers from 1-3 (Ex. 1+2+3+2+1). I'm trying to find the total ocurrences of every number, but when trying to sum to an index of the array, it just overflows or gives me an u...
For starters you need to initialize the array int arr[3] = {}; And you need to compare characters like for example if(s[i] == '1'){ If you are sure that s[i] contains only characters '1'-'3' then instead of the if statements you could write for example ++arr[s[i] - '1']; or you could use only one if statement if ( '...
74,091,075
74,091,125
C++ generating a variable number of nested FOR-loops
I have a struct containing a vector of elements: struct SomeStruct { std::vector<Element> vec; }; each Element contains a container: struct Element { Container m_container; }; The vector can contain 3, 4 or 5 Elements. This is guaranteed. If there are 3 items, the next stage contains a series of 3 nested for ...
You can solve solve this problems most of the times with recursion. so void loop(int n,const vector<double>& vec, vector<double> outer_vars){ if (n!=vec.size()){ for(const auto& z : vec[n]){ outer_vars.push_back(some_func(z)); loop(n+1,vec,outer_vars); } } }
74,091,297
74,091,348
How to access to the actual type of a template specialization type parameter
Suppose the following structures: // struct 'A' struct A { static std::string toString() { return "A"; } }; // struct 'B' inherits 'A' struct B : public A { static std::string toString() { return "B"; } }; // struct 'X' struct X { static std::string toString() { return "X"; } }; then the following template...
Specialization for A requires an exact match, but A and B are different types. Inheritance is irrelevant here. Try to make a specialization more generic: template<typename T, typename = std::bool_constant<true>> struct ToString { // ... }; template<typename T> struct ToString<T, std::bool_constant<std::is_base_of_...
74,091,601
74,092,362
How to use QGroupBox and QCheckBoxes to one check another?
I'm trying to understand how to use signals to when one QCheckBox be checked it uncheck all other checkboxes present in the same QGroupBox class GroupBox : public QGroupBox { public: GroupBox(QWidget *parent = nullptr) : QGroupBox(parent) { } public slots: void uncheck(); }; class CheckBox : pub...
QCheckBox inherits from QAbstractButton You should use clicked or stateChanged signal instead of checked. e.p. connect(this, SIGNAL(stateChanged(int)), this, SLOT(checked(int))); Btw; if using a modern Qt version, you should ditch the SIGNAL and SLOTS macros and instead use the new connect() syntax that's checked at ...
74,091,630
74,091,702
Efficient Way to draw many individual pixels to a screen in SDL2
I'm currently working on something in C++ using SDL2 that requires being able to draw a lot of individual pixels with specific color values to the screen every update. I'm using SDL_RenderDrawPoint just to make sure my program works but I'm sure the performance on that is terrible. From a cursory search it seems like u...
The pixel format RGBA8888 means that each pixel is a 32 bit element with each channel (i.e. red, green, blue or alpha) taking up 8 bits, in that order. You may want to declare pixels as containing the type "32 bit unsigned integer". An unsigned int is typically 32 bits, but it may also be larger. std::vector<Uint32> pi...
74,091,674
74,091,770
(C++) Variables in header warned as unused even though they definitely are
Not an emergency because the code still works, I'm mainly just curious. I'm using raylib to make an RPG. I wrote a function that changes the displayed rotational sprite depending on the last direction the player moved. If you're unfamiliar with raylib, textures are a variable type which must be initialized with the fun...
The static keyword has different meanings depending on where it is used. Marking a variable at namespace scope as static (in contrast to block or class scope) gives it internal linkage, meaning that there will be a different variable of the same name and type in each translation unit including the declaration (i.e. ea...
74,091,977
74,091,997
Why do we need two constructors while doing operator overloading?
I saw a code in sololearn platform(C++ course) and it is about defining overloading for operator +. you can see the code below: #include <iostream> using namespace std; class Account { private: int balance=0; int interest=0; public: Account() {} Account(int a): balance(a) ...
Look at your operator+. The first line is: Account OBJ2; Without a default constructor, that line is illegal. You could avoid the need for the default constructor there by using the other constructor: Account operator+(const Account &obj) const { // Added const for correctness Account OBJ2(this->balance + ...
74,092,324
74,092,441
How to using regex match all content before these specific symbol in cpp?
I want to find a front(first) part before some symbols in a string. For example, "ABC, ZXC", "AB.QWE,CV", I want to get the result, "ABC" and "AB". By the way, if there is some chinese character in this sentence, like "1月1日,天气晴" how to get the front part(1月1日)? It is easier to reach in Python by import re front_part = ...
C++ regexes don't have an equivalent to the (.*?) that you're using in Python. In C++ you'll want to use something like: [^.,] to match the part up to (but not including) the first . or ,. On the other hand, given how simple of a pattern you're looking for, you could easily forego using regexes altogether: std::string ...
74,092,366
74,092,423
range-expression of range based for loop in C++
I am trying to pass a pointer of vector to range based for loop for its range-expression. Here is the syntax of range based for loop: attr(optional) for ( init-statement(optional) range-declaration : range-expression ) loop-statement Referenced from cppreference.com: range-expression is evaluated to determine the sequ...
Otherwise, begin-expr is begin(__range) and end-expr is end(__range), which are found via argument-dependent lookup (non-ADL lookup is not performed). begin() and end() are looked up only via ADL. For pointers, it works like this: For arguments of type pointer to T or pointer to an array of T, the type T is examined...
74,093,442
74,093,725
How to iterate over an integer range when you don't know if it is in increasing or decreasing order?
I am trying to iterate over a range in one loop and NOT using below two for-loops: if (firstIndex <= secondIndex) for (int i = firstIndex; i <= secondIndex; i++) {...} else for (int i = firstIndex; i >= secondIndex; i--) {...} I considered using boost::irange but it does not cover secondIndex index. Up...
In a contrived way, you can use for (int i= first; first >= second ? (i <= second) : (i >= second); i+= first >= last ? +1 : -1) A variant is possible with a increment variable and multiplies. I don' like it much. int inc= first >= second ? +1 : -1; for (int i= first; inc * i <= inc * second; i+= inc)
74,094,006
74,094,159
C++: Nested dictionaries with unordered_maps
I'm trying to write some code that will allow me to create a dictionary with the unordered_map object in C++. It will basically look like string1 string2 int_vec1 string3 int_vec2 ... i.e. It's a dictionary of string and integer-vector pairs, indexed by strings. I have the following code of a s...
There is no conversion from std::pair to std::unordered_map. You seem to wish my_dict.insert({key_0, {{key_01, val_01}}}); The inner braces are initializer list for the inner unordered map with the pair initializer.
74,094,219
74,094,534
C++ use RAII objects with comma operator?
I have a lock class like this: class Mutex { Guard lock(); // acquire the lock } class Guard { ~Guard(); // release the lock } This is how I'm using it now: Mutex m_mutex; T m_data; T get_data() { auto guard = m_mutex.lock(); return m_data; } But I'm thinking is it safe / good practice to write like this? ...
It is mostly safe. The order of destruction has been clarified with CWG 1885, so that the temporary object materialized from the m_mutex.lock() call will be destroyed only after the result object of the function has been initialized. The built-in comma operator also guarantees that the left-hand operand is sequenced be...
74,094,593
74,094,745
Conditional includes of header and implementation files containing functions with identical names
When I try to compile the following 6 files all together, I get "multiple definition of `funcX(float, float)'" error. If I remove "includeB.h" and "includeB.cpp" from the folder, then remaining 4 files are compiled. What am I doing wrong? Appreciate your help. Thanks in advance! Assume my common.h file looks like this:...
You can't have two definitions for the same function (funcX here). Two solutions: set up your build system so that only one of includeA.cpp or includeB.cpp is linked to the executable. add an #include "common.h" in includeA.cpp and includeB.cpp and compile only one version of funcX depending on the value of CONFIG. ...
74,094,757
74,097,489
In what cases boost::asio::ip::tcp::socket::read_some does not read all of the requested number of bytes?
According to the documentation basic_stream_socket::read_some "…operation may not read all of the requested number of bytes". What does it actually mean? Let's assume following scenario: we want to write a client which sends commands to a server and the server responds with lines of printable ASCII characters, each lin...
read_some reads what is available, until the buffer supplied is full. What is available is dependent on the TCP stacks and intermediate hardware. In general the timing and fragmentation of TCP packets can NOT be relied on. So, so code that does rely on it is probably flawed¹. The good news is that the docs you quoted g...
74,094,760
74,094,804
When is it safe to leave out a const from a function's parametrization?
Many times I write C++ functions I seem to use many more const modifiers than other folks. For example, I write Excel .xlsx files and I use LibXL library for this, and the documentation mentions a function like this: bool writeNum(int row, int col, double value, Format* format = 0) I happened to inherit this function ...
In declaration (as opposed to definition), the top-level1 const on a parameter has no effect. Arguably, it's an implementation detail of the function, that shouldn't appear in the declaration (it adds clutter, yet doesn't provide any new information for the caller). Note that const int x and int *const x are top-level ...
74,095,194
74,095,248
Can not understand the c++ code about deleting punctuations
This is a piece of code that I found online, basically, it helps me to erase all the punctuation in a string. for(size_t i = 0; i<text.length(); ++i) if(ispunct(text[i])) text.erase(i--, 1); Like in the sentence: "hello, I am John". It will delete the comma. But I do not understand why in the code: text.erase(...
++i pre- in/decrement will increment i before using it, so if i is 1 it will first update it to 2 and than use it. i-- pos- in/decrement will use i before decrementing it, so if i is 5 it will use 5 and than update it to 4
74,095,621
74,095,712
function to returning reference of iterator of object
I would like to write a function to returning reference of iterator of an map entry in order to update the value of the entry. However, it fails at compile stage #include <map> #include <iostream> using namespace std; pair<int, string>& map_find(map<int,string>& m, int k){ return *(m.find(k)); } int main() { ...
The value type of std::map<Key, Value> is std::pair<const Key, Value>, not std::pair<Key, Value>. There are also useful member type aliases. #include <map> #include <iostream> using MyMap = std::map<int, std::string>; MyMap::reference map_find(MyMap& m, int k){ return *(m.find(k)); } int main() { MyMap m; ...
74,096,106
74,096,904
How to measure the time elapsed since the last message received from a datagram socket in Poco C++?
My code monitors a datagram socket (implemented in the Poco framework), and I'd like to get notified if there were no messages received after a certain time. I have an infinite loop to monitor the socket, but the loop stops at receiveFrom() function, if no messages were received. Here is the code: #include <iostream> #...
You should set a timeout on your Poco socket. Poco::Timespan wait_time( 10000 ); // microseconds // from header file Poco/Net/Socket.h sa.getReceiveTimeout( wait_time ) Then check the number of bytes returned by receiveFrom(..) is > 0 or check for a timeout exception. Use this opportunity to do your other work.
74,096,474
74,096,938
Conversion from char* to std::string gives wrong symbols
My code is: std::string get_time() { char buf[20]; std::time_t timestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); strftime(buf, 20, "%d.%m.%Y %H:%M:%S", std::gmtime(&timestamp)); std::cout<<buf<<std::endl; return std::string(buf, 20); } ... auto timestamp = ge...
First of all, get_time() returns a std::string. Because nothing references this string, it gets deleted at the end of the line. Then, calling get_time().c_str() keeps a pointer to that string (see std::basic_string<CharT,Traits,Allocator>::c_str on cppreference). However, that string isn't guaranteed to exist. Other pr...
74,096,612
74,096,720
How to initialize nested struct in C++?
Let's say I have following declaration in the C++: struct Configuration { struct ParametersSetA { float param_A_01; float param_A_02; float param_A_03; } parameters_set_A; struct ParametersSetB { float param_B_01; float param_B_02; } parameters_set_B; }; Then somewhere in the code I have...
The problem is that we can't use any of the unqualified names param_A_01 or param_A_02 or an expression that involves any of the two like param_A_01 + param_A_02 as initializer forparam_A_03. Additionally, you have incorrectly put a semicolon ; after param_A_01 + param_A_02 instead of comma , . I've corrected both of t...
74,096,736
74,097,492
Convert int to UIntPtr in C#
Thanks in advance. In the following piece of simple code, the model.Count is an System.Int32 integer which I get from the a third party library named Xilium.CefGlue (v107). I iterate over this integer to get the value based on the index. indexCollection = cefMenuModel.Count; for(int x=0;x<indexCollection;x++) { v...
Assuming that the UIntPtr values will be in the range of a 32-bit integer (which I assume they must be, because you can't address more than 2^31 items in an array in C#), then you can just freely cast between a UIntPtr and an int: UIntPtr uip1 = new UIntPtr(34234); Console.WriteLine(uip1); // 34234 int i = (i...
74,097,013
74,126,107
C++/CLI usage with unmanaged code - Boost, <future>
I am trying to compile a C++ library for use with C# on Windows (the library is Vanetza). The library uses CMake, I am building from Microsoft Visual Studio Community 2022 (64-bit). I can build the library as shared DLL no problem. For use with C#, I thought of compiling the library as C++/CLI (common language runtime ...
Write a class in c++/cli that connects to your C++ code. The code will call the router which I presume will return a future. Then in manged/cli you create a task that hooks up to that future. So you have the original code compile to a static C++ lib and link that into your managed C++/cli dll
74,097,037
74,097,180
Inheritance from STL priority_queue with custom comparator not working
I would like to inherit from STL priority queue to have some additional functionality such as: allowing removal. But I am struggling to make this work when I use custom comparators. MWE: #include <queue> template<typename T, class Container=std::vector<T>, class Compare=std::less<typename Container::value_type>> clas...
Constructors are not automatically inherited, so your class probably lacks any constructor, except the implicitly-declared ones. You can explicitly inherit all constructors of the base class: template<typename T, class Container=std::vector<T>, class Compare=std::less<typename Container::value_type>> class custom_prio...
74,097,243
74,097,300
C2280 error attempint to reference a deleted function
The function DataContainer.initial() triggers a C2280 error. After defining a move assignment operator it works. But I am not clear why in function initial_2() it works. The obvious difference is that data_a is a local variable and data_b is a class member. Thanks for helping. #include <vector> #include <iostream> cla...
In the function initial_2, you are creating a new object of type DataTypeA from an existing object, so you can use the move constructor. However, in initial, you are assigning new data to an existing object. For this, you need to have the assignment operator. See Difference between the move assignment operator and move...
74,097,670
74,097,776
No instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Enemy *, _Alloc=std::allocator<Enemy *>]" matches the argument list
for (auto enemy : this->enemies) { if (enemy->getHP() <= 0) { enemies.erase(enemy); } } I have a vector enemies containing multiple of Enemy* elements and i want to erase an enemy if their hp is 0 or below I write the code above and it gave me this error message: No instance of overloaded function ...
The std::vector<T>::erase function does not have a erase(T a) overload. And if you want to remove elemennts from a vector you can't iterate over them like that. I suggest a convencional loop. for (size_t i=0; i<this->enemies.size();++i){ if (this->enemies[i]->getHP()){ std::swap(enemies[i],enemies::back());...
74,097,800
74,097,881
I can change the values even when I use const word with my own array class template
So I'm trying to write my own array template and everything works until i try to create a const object of my class template. in main.cpp I create the object with the copy contructor and I change it which I would expect to not work but it works. Help would be appreciated :D main.cpp # include "Array.hpp" int main( void...
The issue is this: T& operator[](int n) const { if (n < 0 || n >= size_) throw std::out_of_range("out of range"); return (array_[n]); } Because this is declared to be a const method, it can be called on a const Array. Though, it returns a non-const reference to the element. Because Array stores the e...
74,098,047
74,098,601
Send parameters with dynamically generated QComboBox
I want to insert a QComboBox inside a QTableWidget. When I change the Index of the CB I'll call a methode to change the status in the sqlite table. But for this, I need do pass two parameters to the methode. The ID(First element of the row), and the current index of the CB. I generate the QTableWidget like that: ... fo...
Since currentIndexChanged only has one parameter, your slot cannot capture more than that. But, since the row ID does not change on emission, you can wrap onComboChanged into a lambda as shown here, which captures the row by copy: connect(combo, &QComboBox::currentIndexChanged, this, [=](int index) {this->onCom...
74,098,207
74,098,567
Pass ownership of an object into method of the same object?
I came across come C++ code similar to the following (more or less minimal) example. Please consider the marked method call in the function on the bottom: #include <memory> static unsigned returnValue = 5; void setReturnValue(unsigned u) { returnValue = u; } class MyObject { public: MyObject(unsigned uIN)...
Since you tagged this question C++14, that means we now have to engage with the question of which expression resolves first: the uniqPtrToObject-> one or the initialization of the function parameter? The answer is... it is indeterminate. Neither is sequenced before the other in C++14. The -> is sequenced before the fun...
74,098,791
74,138,899
Soap getProfiles returns error if device codec is set on H.265
I Generated proxy with gSOAP 2.8.123E. Using message included in MediaBindingProxy, I try to retrieve the profile list on a remote Device with GetProfiles message. If I set the device codec on H.264 everything is fine, but when codec is H.265 I retrieve an error in soap response (sniffing with wireshark I notice that t...
Reading documentation on Onvif profile T, H.265 is enabled in "http://www.onvif.org/ver20/media/wsdl" and not in "http://www.onvif.org/ver10/media/wsdl". This solve the problem.
74,098,960
74,099,124
How can I avoid memory leaks coming from std::list and std::vector
I keep fighting memory leaks on a project coded by a former colleague. Valgrind doesn't seem to like std::vector and std::list resize. For example, if I take this method: void BaseImage::setImageSize(unsigned short width, unsigned short height, unsigned short nbBytePerPixel, const boost::posix_time::ptime& timestamp) {...
Valgrind does not tell you that resize did something funny. It tells you that you forgot to deallocate some memory, and gives you an idea on who allocated them, so you can find the responsible to free them. So who should free them? Ah, that would be the vector. And who should free the vector? Ah, that would be your ...
74,100,332
74,107,144
OpenMP parallel for does not speed up array sum code
I'm trying to test the speed up of OpenMP on an array sum program. The elements are generated using random generator to avoid optimization. The length of array is also set large enough to indicate the performance difference. This program is built using g++ -fopenmp -g -O0 -o main main.cpp, -g -O0 are used to avoid opti...
As pointed out by @High Performance Mark, I should use omp_get_wtime() instead of clock(). clock() is 'active processor time', not 'elapsed time. See OpenMP time and clock() give two different results https://en.cppreference.com/w/c/chrono/clock After using omp_get_wtime(), and fixing the int i to size_t i, the resul...
74,100,507
74,100,664
C++ Expression: Vector subscript out of range
I recently started learning c++ and I'm trying to make a tic-tac-toe game. I'm using a vector for the board and modifying the board once per player turn. The board looks like this: std::vector<char> board = { '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', }; Here is the function modifying the board: int player_turn...
You're experiencing undefined behavior since your function doesn't return a value in each branch. int player_turn(std::vector<char> board) { int guess; std::cout << "Please enter field 1-9: \n"; std::cin >> guess; if (guess < 10 && guess > 0 && board[guess-1] == '-') return(guess); else { st...
74,101,066
74,105,309
Getting co_await with boost::process::async_system working
Like the title says, I want to co_await for a process spawned with boost::process::async_system. So I'm doing something like this: Example on Coliru namespace bp = boost::process; bp::async_pipe ap(io_); // Create the child process object with our parameters and a redirected stdout co_await bp::async_system(io...
I'd mold the code a bit for style: http://coliru.stacked-crooked.com/a/33667a7d106de0e7 The Real Problem Now with the above, there's is still an error inside my_coro when you try to uncomment the async_system call. Instead of reading the message, I looked at the code, figured that it should have worked, and looked at t...
74,101,362
74,105,362
Convert a streambuf to const_buffer
How do I "consume" a streambuf and thereby convert it to a const_buffer? Example: const_buffer read(boost::shared_ptr<tcp::socket> sock) { boost::system::error_code error; // getting response from server boost::asio::streambuf receive_buffer; boost::asio::read(*sock, receive_buffer, boost::asio::transfe...
const_buffer is not an owning data structure. Logically, you cannot consume the data and still have a const_buffer referencing it. You should probably use a container like std::string or std::vector: return std::string(buffers_begin(receive_buffer.data()), buffers_end(receive_buffer.data())); // or r...
74,101,443
74,101,473
Wrong placement in 2d vector
I'm trying to print a full closed maze (where the user inputs width and height), but when I print the maze the "|" walls are not placed correct. Why is this, because the parameters are set. Also the right amount of "|" are placed but at wrong positions int vectorLength = (userRows * 2) + 1; int vectorWidth = (userC...
It looks like your code works by replacing characters in your maze vector. Since your vector is initialized all to empty strings, there is nothing between each "|" to give space. You should either initialize your vector to be full of spaces " " or find another way to pad the space between each bar.
74,101,498
74,102,669
CPython C/C++ extension: Dealloc never called
Initial situation: I have a Python C extension module which defines a init() method which creates and returns a new Python object. I followed the approach of heaptypes.c in the official python sources. My source code (my_module.cpp) is almost a 1:1 copy of the example in the Python sources : typedef struct { PyObje...
You are using the API incorrectly. PyType_FromSpec returns a TYPE, not an Object instance (it is not the same as PyObject_New). So it will never call init (the constructor) of said type. You are doing: x = MyModule.init(). x is actually a HeapCTypeObject TYPE. You haven't constructed an instance of that type yet. If yo...
74,101,544
74,102,123
Must difference_type be comparable?
The requirements for random access iterators are found here. On this page, you will see that for any two RandIts, a and b, a<b and a-b are both legal c++. a-b returns a difference_type. In my code, I want to compute a<b, but instead of comparing a and b, I want to compare a-first and b-first. This requires two things: ...
The standard requires iterator_traits<It>::difference_type to be a "signed integer type" (or void). This statement is to be taken literally. [basic.fundamental]/1 defines a number of types which are "integer types" and a subset of them to be "signed integer types". These are the only "signed integer types" in C++. You ...
74,101,568
74,102,013
Memory usage of a vector of struct with an int and a string
What is the expected memory usage of a vector of a struct, that contains a string (let's say on average 5 bytes), an int (4 bytes) and a double (8 bytes). Would each entry just take 17 bytes or are there other things to consider? struct Entry { int entry1; string myString; // on average 5 characters double value;...
You're going to use at least sizeof(std::vector<Entry>) + N * sizeof(Entry) bytes, and short string optimization means that if all of your strings are short you'll probably use exactly that much. How much memory that is will depend on your compiler, standard library implementation, and architecture. Assuming you're co...
74,101,708
74,101,780
Simplifying the Makefile
I use this Makefile to build a small C++ application: BIN_CPP=Main CPP=g++ INCLUDES_APR=/usr/local/apr/include/apr-1 LIB_SRC = $(wildcard My*.cpp) LIB_OBJ = $(LIB_SRC:.cpp=.o) RM=rm all: Main MyClass.o: MyClass.cpp $(CPP) -I$(INCLUDES_APR) -c $< -o $@ MyModel.o: MyModel.cpp $(CPP) -I$(INCLUDES_APR) -c $< -o ...
By removing the explicit rules, you are relying on GNU make's built-in rules to compile your files, which is good. But GNU make's built-in rules can't possibly know about your local variable INCLUDES_APR, so when it compiles the source files that variable is not used. You should add the -I flag to the standard variabl...
74,102,221
74,102,375
What does type aliasing through reference (of `signed` to `unsigned`) with `reinterpret_cast` do?
My questions are: As of which version of the standard does the following code become valid (if any)? What is the observable behavior of the program? (In C++20) #include <climits> int main() { int foo = INT_MAX; ++reinterpret_cast<unsigned&> (foo); // foo = static_cast<int> (foo + 1u) return INT_MIN == foo; } ...
This has been permitted for all versions prior to C++20 according to the strict aliasing rule: If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined: ... a type that is the signed or unsigned type corresponding to the dynamic...
74,102,290
74,108,719
clang-format and special delimiters
I am using a special raw string delimiter in my code to format doc string, it looks something like R"mydelimiter( some raw string )mydelimiter" Now, clang-format likes to produce the following R "mydelimiter( some raw string ) mydelimiter " which actually introduces a compilation error. I know that I can mark...
As pointed out in the GitHub issue opened for this, the problem is in the GNU style option. clang-format relies on the clang parser, but the clang parser may give different results for different versions of the C++ standard. The GNU style option sets the C++ standard used for parsing to C++03, a time where raw string l...
74,102,415
74,102,577
Properly handling owner drawn Win32 button hovering
I want to add multiple color themes to my Win32 application, this means that I have to manually handle all the control drawing manually by using the BS_OWNERDRAW style flag. I then handle all the drawing in the WM_DRAWITEM message through the LPDRAWITEMSTRUCT structure stored in the lParam. Here's the problem though, b...
I've tried using the SetWindowSubclass function by giving each control it's separate WindowProc callback where you can track the mouse leaving and entering the control. This works, but that also means that I need to transition all drawing commands over to the subclass procedure, which seems rather stupid to me, since ...
74,102,714
74,140,838
what cpp function in firefox gets invoked when javascript invokes clipboard.getData()?
What C++ function is invoked in Firefox source code when Javascript invokes clipboard.getData() ? My guess is line 57 in MessageEvent::getData But when I put a printf statement in there, it never gets hit. Does anyone know which C++ function gets called in Firefox source when Javascript invokes clipboard.getData() ?
DataTransfer::GetData is invoked.
74,103,004
74,157,547
How Unreal Engine implements UPROPERTY macro?
I'd like to implement something like UPROPERTY() macro in my project, but I cannot find any references of what it actually is. I mean, there're are tutorials on how this macro works, but these are just use cases. How does the compiler know that UPROPERTY() references the variable under it? example: UPROPERTY(EditAnywhe...
UPROPERTY is not a real C++ macro. It looks like one, so the compiler accepts it, but it actually is used by the Unreal Header Tool (UHT) to create code that will then be added in the GENERATED_BODY code of your class. The UHT is a parser that just takes all of your code and searches for all those UCLASS, UPROPERTY, UF...
74,103,156
74,103,407
Sample application with imgui library generate error
I am new in imgui and just installed it with vcpkg and created an application in vs2022 and add these codes: #include <imgui.h> using namespace std; void MySaveFunction() { } int main() { ImGui::Text("Hello, world %d", 123); if (ImGui::Button("Save")) MySaveFunction(); } but when I run this applicati...
Dear ImGui provided some detailed examples on how to get started. Don't be scared to read the code, which might be long and overwhelming if you are new to it. You basically need to choose a backend, I personally prefer DirectX 11. Then you have to create a window and initialize DirectX. Then create the ImGuiContext - w...
74,103,820
74,103,973
Making a class template declared in an outer anonymous namespace a friend
Clang refuses to compile the following code (godbolt) while gcc sees no problem with it. Clang error message is shown below line marked (2): namespace // Overall anonymous namespace is required and cannot be removed. { template <typename T> struct Friend; namespace ns { class Secret { template <typename T> ...
Yes, you are right that simply friend struct Friend is a declaration of a templated class ::(anonymous namespace)::ns::Friend. Both compilers are right, as when you attempt to use Friend<T>::bar() gcc will complain about access as well (clang just checks a lot earlier than gcc) To specify the class template in the glob...
74,104,224
74,104,272
Since For loops is n Timecomplexity So is it Better To Use Only couts for example in cpp and never use for loops?
in algorithms Complexity For loops is N Time complex Nested For loop Is n2 time complex but cout in cpp or printf in c and cpp is Constant time Complex So its faster so is it Better To use Cout 10 times to print number1to10 since its Actually faster ? or ? (We should use Only for loops when Its really hard to code it f...
If you copy and paste a printout n times then the code still takes O(n) time. Unrolling the loop doesn't change the fact that you've got n printouts. Except now you have O(n) lines of code instead of the O(1) lines of a for loop.
74,104,268
74,104,287
Undefined Behavior in Unions with Standard Layout structs
Take the following code union vec { struct { float x, y, z; }; float data[3]; constexpr vec() : data{} {} }; constexpr vec make_vec(float x, float y, float z) { vec res; res.data[0] = x; res.data[1] = y; res.z = z; return res; } int main() { constexpr vec out = ma...
Yes, this is UB. After you write to float data[3]; part of the union, you are not allowed to read the struct { float x, y, z; }; This is as simple as that. that share a common initial sequence Doesn't cover these two, as an array is not the same as a float followed by another float. Important edit The answer above as...
74,104,455
74,104,511
Get a vector that is rotated towards a point that is perpendicular to a normal vector
I want to calculate a vector that is perpendicular to a normal vector of a plane, and if you are looking at the plane top down you will see the resulting vector pointing towards a point. Example Image: What I've tried This is the code I've made to try to calculate the vector. It doesn't work not sure what to add to fi...
In other words you're seeking a vector from hitPosition towards the projection of goalPoint along the Y axis. You don't need trigonometry for this. A vector (X,Y,Z) is perpendicular to the normal of the plane if it satisfies: X*normalVector.X + Y*normalVector.Y + Z*normalVector.Z == 0 (See dot product.) That vector po...
74,104,611
74,104,634
I don't know why my c++ arrays are not working
The errors I received are these: error: 'NoOfHours' was not declared. Its the same with taxrate, salary, tax, and netpay. The output I'm looking for is a table using the gathered data from the user: | Name | Position | No. Of Hours | Salary |Tax|netpay| | -------- | -------------- |----------------|--...
Most of your arrays are declared inside of the 1st loop, so they are out of scope when the 2nd loop tries to access them. Fix your code's indentation, then the problem will be easier to see. You need to move the affected arrays outside of the 1st loop, at the same level as the RatePerDay, Name, and Position arrays 1. ...
74,105,193
74,105,236
What is the difference between "int x" and "(int)x"?
I wanted to know the difference in C++ of the following examples. Why example two is not applicable? First example: void ReceiveServerConnect(BYTE* ReceiveBuffer) { LPPRECEIVE_SERVER_ADDRESS Data = (LPPRECEIVE_SERVER_ADDRESS) ReceiveBuffer; } Second example: void ReceiveServerConnect(BYTE* ReceiveBuffer) { L...
Your first example, with the parentheses, is doing a cast from one type to another. It's an old-style C cast which is a very blunt instrument. For C++ you should prefer one of the new styles: LPPRECEIVE_SERVER_ADDRESS Data = static_cast<LPPRECEIVE_SERVER_ADDRESS>(ReceiveBuffer); The second example is simply bad synt...
74,105,699
74,106,122
Getting top layer of 3d noise
I've generated a cubic world using FastNoiseLite but I don't know how to differentiate top level blocks as grass and bottom one's dirt when using 3d noise. TArray<float> CalculateNoise(const FVector& ChunkPosition) { Densities.Reset(); // ChunkSize is 32 for (int z = 0; z < ChunkSize; z++) { f...
This answer applies to Perlin like noise. Your integer chunk size is dis-contiguous in noise space. 'Position' needs to be scaled by 1/Height. To scale the noise as a contiguous block. Then scale by Height. If you were happy with the XY axes(2D), you could limit the scaling to the Z axis: FastNoiseLiteObj->GetNoise(...
74,105,980
74,106,066
The erase function of strings in c++
well I was doing this problem from leetcode " https://leetcode.com/problems/valid-palindrome/ " and to remove the punctuations I used this for (auto i:s) { if (ispunct(i)) { s.erase(remove(s.begin(), s.end(), i), s.end()); continue; } } but when it runs it leaves some punctuation charac...
Modifying a string (or any other collection) while looping over it is a poor idea. Your iterator into the string is based on the state of the string at the beginning of your loop. Changing the state of the string inside the loop may lead to unexpected behavior of your iterator. Rather you may want to create a new strin...
74,105,996
74,122,916
Is it possible to use the COM DLL without register in Registry using RegAsm.exe?
I need to use the C# dll from C++ code. Is there any way to use the dll without register it into registry. Because register in registry needs administrative privilege. If any suggestion please let me know
I solved this Problem by Register the COM dll in HKEY_CURRENT_USERS hive by this code https://stackoverflow.com/a/35789844/19616470
74,106,392
74,106,439
const function modifying data in Doubly Linked List
I have created a doubly linked list. in the list, there is a function that is const, and is not supposed to modify the object. but it is modifyind I dont know why. #include<iostream> using namespace std; class Node { public: int data; Node* prev; Node* next; Node(int val) :data(val), next(NULL), prev(NU...
The const qualifier for the member function only tells the compiler that you won't modify this object. And you don't do that: You modify head->data which is another object. It would be a different issue if you tried to reassign the variables head or tail.
74,106,522
74,106,574
What differs between parentheses and curly in std::tuple?
Well today I met a werid behavior when using std::tuple() and std::tuple{}. Here is an easy demo: #include <iostream> #include <tuple> #define rd ({ int x = (std::cin >> x, x); x; }) template <typename... Args> void log(const Args &...args) { ((::std::cout << args << ", "), ...); } auto main() -> int { ...
Your friends are correct. The unspecified behaviour occurs because the evaluation order of function arguments is not specified, it can happen in any order and can change between calls. Meaning the order of std::cin is not guaranteed. The compiler is free to reorder them as it sees fit. This applies to std::tuple(), hen...