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
71,740,385
71,741,933
why the jdk native refactor get class from heap
I am reading the jdk 19(support the m1 chip when compile) source code, in the refactor source code in reflection.cpp, the function look like this: oop Reflection::invoke_method(oop method_mirror, Handle receiver, objArrayHandle args, TRAPS) { oop mirror = java_lang_reflect_Method::clazz(method_mirror); ...
This reads the clazz field of a java.lang.reflect.Method object. java.lang.reflect.Method is a regular Java class (with some support from native helpers). Why do you expect it not to be stored on the heap? Note that java.lang.reflect.Method is not the same as a hotspot-internal C++ class Method. The class Method is an...
71,740,495
71,740,796
Is implicitly deleted default constructor same as Compiler not synthesizing the default constructor
I am learning about class in C++. I came to know that in certain situations the default constructor can be implicitly deleted. Also, i read that when we have a user defined constructor then the compiler will not automatically synthesize the default constructor. To my current understanding, an implicitly deleted default...
This is covered in [class.default.ctor]: If there is no user-declared constructor for class X, a non-explicit constructor having no parameters is implicitly declared as defaulted ([dcl.fct.def]) So if there are user-declared constructors, there is no creation of an "implicitly declared" defaulted constructor. The bro...
71,740,678
71,741,078
CMake error in FindTerminfo with clang-15 on MacOS
I'm using llvm in my project and find it with cmake's find_package(LLVM REQUIRED CONFIG). Configuration fails with message: [cmake] CMake Error at /Applications/CMake.app/Contents/share/cmake-3.23/Modules/Internal/CheckSourceCompiles.cmake:44 (message): [cmake] check_source_compiles: C: needs to be enabled before use...
It's actually a well-known issue in clang-14 and greater. Temporary solution is to use C language in your project. project(test LANGUAGES C CXX) # instead of project(test LANGUAGES CXX)
71,741,225
71,741,668
What is time complexity of the given code for sorting?
I thought about sorting using hash map, and the time complexity of insert operation is O(log(n)) so, I am wondering is it possible to sort using O(log(n)+n)? //sahil L. Totala #include <bits/stdc++.h> #include <iostream> using namespace std; int main () { cout << "how much no. do you want:"; int n; map < in...
As it stands right now, the code is something like O(N log M), where N is the total number of input elements, and M is the number of unique elements. You're attempting to insert N elements into your map, but that attempt will only succeed for elements that weren't previously present. That means the map will only contai...
71,741,459
71,744,704
Can I create a c++ class instance and use it as an entity in Android JNI?
Let's say I create a class 'Car' in cpp. I want to creat an instance of that class with it's empty constructor in cpp. Can I do it and use it in java code on android? For instance: Java code Car myCar = new Car(); CPP class class Car{ std::string model; int creationYear; Car(){} } thanks for the help
Yes. You can easily have a native object that shadows a Java object - assuming you can call the C++ Car() constructor. You could use a public static method in the C++ Car class to do that. It's a bit of a hack, but a Java long is guaranteed to be 64 bits, so it's long enough to hold a native pointer value. In Java: p...
71,741,517
71,741,645
How to grant friend class access to value of modified member
What is the proper method to grant class access to modified value of private member of different class. Using Friend Class is granting me access to value of private member if provided but won't let me access to modified value data of that member. For example when I am building vector in one Class and I would like to wo...
You may want to store a reference / pointer to a particular Foo inside each Bar instance. class Bar { public: Bar(Foo& f) : foo(&f) {} // take a Foo by reference and store a pointer to it void Print(); private: Foo* foo; }; void Bar::Print() { // use the pointer to the Foo in here: std::cout << foo->...
71,741,705
71,757,956
How to move the Gtk::Entry cursor?
I'm trying to make a custom Gtk::Entry widget (gtkmm4) that accepts only numbers and shows text as currency. Decimal and thousand separators are automatically added to the text. So I derived from Gtk::Entry and connected the signal_changed() with a member function that formats the input: class CurrencyEntry : public Gt...
The position seems not to be updated from the entry's handler. I tried other handlers (like insert_text) and the same issue arises. One way to solve this is to, from within you entry's handler, add a function to be executed in the idle loop. In that function, you can update the position. Here is the code: #include <alg...
71,741,742
71,746,258
Import C++ function in Python through ctypes: why segmentation fault?
I tried to call this C++ file (myfunc.cpp) from Python. I decided to use ctypes module, since it seems to work pretty well for both C and C++ code. I followed several tutorial (e.g., Modern/2020 way to call C++ code from Python), which suggests to add 'extern C' on the top of the C++ function to be called in Python. #i...
As mentioned in the chat we had, the code posted in the question segfaults because the following code returns a zero-length vector when first called: std::vector<int> to_xy(int k, int nside) { int x = k%nside; int y = floor(k / nside); vector<int> res(x, y); // if k==0, this is length 0 return res; }...
71,741,978
71,742,253
Recursive iteration over type lists and concatenation into a result type list
Consider a scenario having various classes/structs, some having complex data members, which can contain more of them itself. In order to setup / initialize, a list of all dependencies is required before instantiantion. Because the types are known before instantiation, my approach is to define a type list containing inv...
I'll just look at the metaprogramming part. As always, the solution is to use Boost.Mp11. In this case, it's one of the more involved algorithms: mp_iterate. This applies a function to a value until failure - that's how we can achieve recursion. We need several steps. First, a metafunction to get the dependencies for a...
71,742,203
71,760,027
Attempting to call Write() multiple times from separate thread(s) causes crash [gRPC] [C++]
I'm attempting to write an async streaming gRPC server (following this example) in C++ where multiple calls to Write are performed on a separate thread. Unfortunately, this causes a SIGSEGV on my system. The server is able to perform one write before it crashes. The below code provides a simple example of what I'm atte...
Turns out I had a misunderstanding of gRPC and the completion queue. I was calling Write() before the completion queue returns the tag, which caused the crash. To resolve this, I created a static void* member variable in MyServer called m_tag and passed it into the Next function's tag parameter, like so: GPR_ASSERT(m_q...
71,742,508
71,743,033
GCC/Clang not optimising static global variable
GCC does not seem to be able to trace and optimize programs that read/write global variables in C/C++, even if they're static, which should allow it to guarantee that other compilation units won't change the variable. When compiling the code static int test = 0; int abc() { test++; if (test > 100) \ return 123...
I think you are asking a little bit too much for most of the compilers. While the compiler is probably allowed to optimize the static variable away according to the as-if rule in the standard, it is apparently not implemented in many compilers like you stated for GCC and Clang. Two reasons I could think of are: In you...
71,742,686
71,742,778
What is the correct way of declaring an iterator?
I am wondering if there is any difference between using std::set<int,std::greater<int>>::iterator itr; and std::set<int>::iterator itr; I tried the two of them in the code below and the result is the same, I would like know is there is any difference between one and the other or if there is any instance in which I sh...
std::set<int>::iterator itr; is wrong. It happens to work on both GCC, Clang, and MSVC by default. But e.g. if I enable GCC's iterator debugging (-D_GLIBCXX_DEBUG), it stops compiling. Normally you don't need to manually spell the iterator type. You can do for (auto itr = s1.begin(); ...). Or, if the iterator needs to ...
71,742,712
71,743,088
What would be the best approach to override cmath functions while still using them?
I'm trying to make my own math library with support for keeping stats on how many times each mathematical function in used. I would like all functions to have the same name as those in cmath so that I can easily just replace my math library header with cmath in my code and have it work the same way, just without the st...
To expand on my comment, and presuming this is part of some test-framework type thing, this could work how you want? // my_math.hpp namespace jesper { float tanf(float ang); /* more functions declarations */ } // my_math.cpp #include "my_math.hpp" float jesper::tanf(float ang) { /* function definition */ }...
71,744,379
71,744,690
What is wrong with this Coin Change solution using DFS with memoization?
I've solved Leetcode's Coin Change 2 problem with a DFS + memoization approach in Python, with the solution below # O(m*n) def change(amount: int, coins: List[int]) -> int: cache = {} def dfs(i, a): if a == amount: return 1 if a > amount: return 0 ...
Your memoization in the C++ solution looks at index and amount (a constant), when your Python one looks at index and a. Changing it accordingly fixes it, i.e [...] if (dp[index][a] != -1) { return dp[index][a]; } dp[index][a] = dfs(index, a + coins[index], amount, coins, dp) + dfs(index + 1, a, amount, coins,...
71,744,856
71,753,248
install_name_tool errors on arm64
I have c++ app that has multiple dependencies that takes the form of dynamic libraries. install_name_tool works fine to change the paths of those libraries in relation to the main executable, but the problem is that some of those libraries have dependencies themselves. For x64, running install_name_tool again on those ...
Figured it out! Since Big Sur, codesigning for arm64 is much more strict than it is for x64. So, I needed to run codesign --force -s - /path/to/dylib on every dylib
71,744,879
71,744,943
Fastest way to transfer/copy data from float* to vector<float>
I have a float* variable. I want to copy the value in the float* to the vector . Could you suggest the fastest way to do it on C++? This is my baseline code std::vector<float> CopyFloat2Vector(float* input, int size1) { std::vector<float> vector_out; for (int i = 0; i < size1; i++) { vector_out.push_back(inpu...
std::vector has a constructor for that. I would assume the standard library implementation will make use of as much optimization as it can in that: std::vector<float> CopyFloat2Vector(float* input, int size1) { return {input, input+size1}; }
71,744,958
71,745,139
How to return const& from std::visit?
I have encountered what i consider to be a strange situation with std::visit and overloaded which is giving me a compiler error. To illustrate what i am trying to do I have an example using std::visit 3 different ways. Approach 1, calling std::visit directly on a variant which returns a T const&, Approach 2, wrapping ...
The default behavior when calling a lambda (or a function for that matter) is to have the value returned by copy. Since your lambda expressions that you pass to overloaded return by copy, binding a reference to that in the return type of visit_get_name (or wrapper::get_name) is not allowed, which is why Approach 2 and ...
71,745,234
71,755,027
How to detect which variable/code is creating a stack-based buffer overrun
I have an application that has started failing with 0xc0000409 - The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application. I have a full crash dump and source code, but this leads me to terminate() and abort() f...
Activate Application Verifier for your application. It helps finding the problem more closely to the actual root cause. Then run it using a debugger. Fix your symbols Use a large CounterString (16 MB or so; funny generators here) and paste it into every textbox you have. This will probably overflow every unprotected b...
71,745,650
71,745,711
VS Code :: C++ :: Error with giving inputs to the program
I have just setup the VS Code to run C++ using the YouTube video Now when I write a simple code #include <iostream> using namespace std; int main() { cout << "Enter your first name:"; cin << first_name; cout << "Your name is" + first_name; return 0; } I keep getting the error PS C:\Users\raman\OneD...
Your code has two problems: First first_name is not declared cin uses >>, not << #include <iostream> using namespace std; int main() { string first_name; cout << "Enter your first name:"; cin >> first_name; cout << "Your name is" + first_name; return 0; }
71,745,708
71,745,726
What's the right grammar to use this member function?
My goal is knowing the name of this "Planner" by using function "getName()" getName() defined in Planner.cpp: const std::string& ompl::base::Planner::getName() const { return name_; } The way I called this function : void ompl::geometric::SimpleSetup::clear() { std::cout << base::Planner::getName() << std::end...
This is a non static method, so you have to call it with an object. For example, if planner_ is a pointer to an instance of a ompl::base::Planner class, then you can use planner_->getName(); or void ompl::geometric::SimpleSetup::clear() { if (planner_ != nullptr) { std::cout << planner_->getName() << std::...
71,745,756
71,745,817
How to include Vcpkg on CMakeLists.txt?
So I have a project which depends on opencv, which is installed with vcpkg. The project is build with cmake. CMakeLists.txt cmake_minimum_required(VERSION 3.19.1) set(CMAKE_TOOLCHAIN_FILE ~/vcpkg/scripts/buildsystems/vcpkg.cmake) project(mylib) set (CMAKE_CXX_STANDARD 14) find_package(OpenCV REQUIRED) include_dire...
This include_directories(~/vcpkg/installed/x64-osx/include) looks odd. This should be instead that: include_directories(${OpenCV_INCLUDE_DIRS})
71,746,147
71,747,242
How do I correctly pass converting constructor from an std::queue through to the underlying std::deque?
I have created a custom memory allocator. To use it with STL Containers, I've also created a wrapper so that it adheres to the std::allocator_traits requirements. #include <cstdint> #include <memory> #include <deque> #include <queue> class CustomAlloc { public: CustomAlloc(const std::size_t& maxMem) noexcept :...
If you can't change CustomAlloc code as Ted Lyngmo suggested, the alternative is to define CustomQueue as a subclass of std::queue: template<typename T, typename Alloc> struct CustomQueue : std::queue<T, CustomDeque<T, Alloc>> { CustomQueue(Alloc& alloc) :std::queue<T, CustomDeque<T, Alloc>>(STLAdaptor<T, Alloc>(al...
71,746,951
71,747,083
Why is temporary Node necessary in Reversing a linked list in cpp?
Here is the working code: Node* Reverse(Node *head) { Node *prev = NULL; Node *next; Node *current = head; while (current != NULL) { next = current -> next; current -> next = prev; prev = current; current = next; } head = prev; return head; } And this do...
You don't need the current variable. (despite it's name head would be confusing) The code is different because you don't assign prev to head in the second snippet. Node* Reverse(Node *head) { Node *prev = NULL; // Node *current = head; Node *next; while (head != NULL) { next = head -> next;...
71,747,171
71,747,414
Mouse right click option using eventFilter in Qt
I have QGraphicsView, which has many QGraphicsItem. I am trying to create a right click menu on these QGraphicsItem. Right click menu has multiple options. But only 1st option works. It means, if I click on 2nd option, it does not work. If I change the sequence ( means 1st one will go to 2nd position, and 2nd one will ...
The usual way to do something like this is to override the QGraphicsItem::mouseReleaseEvent() or QGraphicsItem::mousePressEvent() function of your item class. This way, you won't have to do anything (no looping, etc...), it is already handled by the event loop. Here you can find a simple example: void MyItem::mouseRele...
71,747,705
71,748,706
glm::lookAt gives unexpected result for 2D axis
Basically I have a local space where y points down and x points right, like | | ---------> +x | | +y and the center is at (320, 240), so the upper left corner is (0,0). Some windowing system uses it. So I have this code auto const proj = glm::ortho(0.0f, 640.0f, 0.0f, 480.0f); aut...
That's not how view and projection work. The view matrix tells you which point should be mapped to [0,0] in view space. It seems you try to map the center of the visible area to [0,0], but then you use a projection matrix which assumes that [0,0] is the top-left corner. Since you first apply the view matrix, that gives...
71,747,942
71,748,834
DX12) Part of the Constants buffer is cut off
This is my Constant buffer for Object Drawing. actually, gWorld and gOldWorld have correct values, but gCubemapOn, gMotionBlurOn, gRimLightOn values are going wrong. gCubemapOn must be TRUE and it looks like, but actually that value is 65537. and gRimLightOn must be TRUE, but as you see, actual value is FALSE. The co...
I believe this is the same problem as seen here. HLSL bool is 4 bytes and C++ bool is 1 byte. If you declare your CPU struct as struct ObjectConstants { XMFLOAT4X4 World; XMFLOAT4X4 oldWorld; int32_t cubemapOn; int32_t motionBlurOn; int32_t rimLightOn; }; it should work.
71,748,073
71,752,783
GL_SHADING_LANGUAGE_VERSION returns a single language
when using glGetString on the enum GL_SHADING_LANGUAGE_VERSION I get only one value for return, while I was expecting space separated values as with glGetString(GL_EXTENSIONS). what is even more confusing is that when I use glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, *); I get a number bigger than one, and when I u...
It is this way because that's how the feature was originally defined. All GLSL versions are backwards compatible with prior ones, so the expectation was that if you had a 1.10 shader, you could feed it to any implementation that accepted 1.10 or higher. But with the break between core and compatibility, that become unt...
71,748,115
71,748,351
Can Boost::asio::post can interrupt the running thread?
I am new to Boost::asio and I am currently looking at io_context. I have a question regarding the function io_context::post Posting on thread can preempt what's running on that thread currently ? because in the documentation i have seen : Deprecated: Use post.) Request the io_context to invoke the given handler and ret...
No it cannot interrupt the running thread(s) associated with the io_context. post() enqueues the task to the io_context which will execute it eventually. The "return immediately" is meant in terms of the post() call itself, not the task. So the post() function returns immediately without blocking, but the task is sched...
71,748,795
71,753,236
building a nested JSON
Some data files that I need to read / parse have headers in the style: level0var = value0 level0var.level1field = value1 level0var.level1array[11].level2field = value2 ... In other words, they look like nested C-style structs and arrays, but none of these are declared in the header: I need to infer the structure as I...
This is indeed trivial to do with the json_pointer, using the correct operator[] overload and the json_pointer::get_unchecked() function that already does all this work for you. The only effort is to convert your .-separated key into the /-separated path it expects. #include <nlohmann/json.hpp> #include <algorithm> #i...
71,748,860
71,749,245
Make a curl request for xml_rpc c++ server
I am trying to make a curl request for a c++ xml-rpc server. After a bit of reading, I came to know the xml-rpc request using curl will look like this curl --connect-timeout 10 -d' <xml request> ' -H 'Content-type:text/xml' https://<Billing Core server>:<Port>/RPC2 In my case it will be curl --connect-timeout 10 -d' <...
I created a file name set_title.xml <?xml version="1.0" encoding="UTF-8"?> <methodCall> <methodName>set_title</methodName> <params> <param> <value> <string>BhanuKiran</string> </value> </param> </params> </methodCall> And made a curl request curl -H "Content-Type: tex...
71,748,924
71,754,560
How to count index of vectors in C++?
I have 5 int vectors v1 to v5. I want to count the index of the same vectors separately. If a different vector appears in the next vector, it outputs the index of the previous same vectors and starts counting for the new vector. Any help would be appreciated. std::vector<int>v1={1, 2, 3}; std::vector<int>v2={1, 2, 3};...
You want to just search the collection of vectors and find in which positions are the elements that match your criterion? Then maybe like this: std::vector<int> v1={1, 2, 3}; std::vector<int> v2={1, 2, 3}; std::vector<int> v3={1, 2, 3, 4}; std::vector<int> v4={1, 2, 3, 4}; std::vector<int> v5={1, 2,...
71,748,947
71,758,962
Using Boost/odeint with class (calling integrate from outside the class with ODE-function inside the class)
I have written a lot of code that got VERY messy over the last couple of weeks/months and I wanted to clean up, by putting most of it into classes. However, I can't figure out, how to call an ODE-function, that is inside a class with Boost/integrate from outside the class. I'm not sure, if this is the cleanest/best pra...
Calling a non-static member function requires an instance of the class. The simplest fix is to mark the odefun as static. This will work unless you wanted to access the internals. Assuming that the correct signature for odefun is actually void(std::vector<double>, std::vector<double>&, const double) or compatible: ODEc...
71,749,257
71,750,090
How to use a string entered in a txt file as an if condition
A function containing the function of a vector is included in a class called Vector. I will determine which function to use in the main function by the string entered in the txt file. class Vector { public: // private? double x, y, z; public: Vector() { x = 0; y = 0; z = 0; } Ve...
You can't compare C-style strings for equality using the == operator. In code like if (VecFun == "Add"), both the VecFun variable (the name of a char array) and the "Add" (a string literal) decay to pointers to their first elements; and, since they are different items in different memory locations, that test will alway...
71,749,389
71,749,579
c++ switch - not evaluating and showing "Condition is always true"
I was experimenting whether I can use "logical or" inside case clause for a switch statement. I tried this way for the first case and the system skipped it all together when I gave input as "A" or "a" in both the cases. # include <iostream> using namespace std; int main () { /* prg. checks if the input is an vowel *...
The case ('A'|| 'a') should be written as: switch (ch) { case 'A': case 'a': cout << "it is vowel" << endl; break; // ... If it matches on 'A' it will fall through to the next case (unless there's a break in between). In this case, you may want to combine all vowles: switch (ch) { case 'A': case 'a': case 'E':...
71,749,809
71,750,570
Switch QPoint to struct in mathematical expression
Don't understand how QPoint is being calculated here. QPoint has x and y. I've tried running this with a custom struct but I get errors such as Invalid operands to binary expression. Works: void test(QPoint p0, QPoint p1, QPoint p2, QPoint p3) { QPoint point; for(double t = 0.0; t<=1.0; t+=0.001){ p...
If you look at the Qt documentation about QPoint, you'll see that the operator*() and operator+() (that you use here) are overloaded for QPoint. If you want to make it work with your class, you will need to overload them as well. The minimum required overloads you need to make your test() function work are: Point opera...
71,751,299
71,751,420
Efficient sorting of multiple vectors with respect to one vector?
I have a 2D vector, S, and a 1D vector, I. Both S and I contain integers. Here is an example: vector<int> I={6,2,3,1,4,5,0}; vector<vector<int>> S; S[0]={0,1,3}; S[1]={1,2,4}; S[2]={4,5,6}; S[3]={0,3,5}; I contains numbers 0..n and vectors S are all subsets of I. I want to sort items in vectors S, with respect to the ...
You can populate a map of weights used for the sorting and then provide a custom comparator for sort: #include <iostream> #include <vector> #include <algorithm> #include <unordered_map> int main() { std::vector<int> I={6,2,3,1,4,5,0}; std::unordered_map<int,unsigned> weights; for (unsigned i = 0; i < I.siz...
71,751,610
71,754,741
Ensure derived class implements static method while maintaining default move / move assign
I'd like to ensure some derived classes implement a static method and found this SO question: Ensure derived class implements static method The top answer uses CRTP to solve the issue with a static_assert in the base class destructor to ensure that the template argument type implements a static int foo(int). However, a...
What you have is a concept that the class needs to fulfil. You can simply check for it after the definition of the class, probably easiest with a static_assert: template<typename T> static constexpr bool assert_is_fooable() { static_assert(std::is_same<decltype(T::foo()), int>::value, "ERROR: No 'static int foo()' ...
71,751,861
71,751,993
Deallocating std::list without going out of scope
In STL one of the ways to create a dynamically allocated array is to create a list. When lists go out of scope destructor for every element is called and the list is deleted. Is there a way to destroy list (and more importantly release the memory used) before list going out of scope, and if it's possible then what is t...
In STL one of the ways to create a dynamically allocated array is to create a list. Linked lists and arrays are quite different data structures. Is there a way to destroy list (and more importantly release the memory used) before list going out of scope You can erase all elements of std::list, or any other standard...
71,752,259
71,752,619
Purpose of explicitly deleting the default constructor
The codebase I’m working on was developed mostly pre-C++11. A lot of classes have a never-defined default constructor declared in the private section. I’m rather confident that in Modern C++, the Correct Way™ is to make them public and = delete them. I “upgraded” classes to this countless times by now and it never lead...
Any function can be = deleted. A default constructor is a function, so it can be deleted. There's no need to make a language carveout for that. That some users choose to explicitly delete the default constructor (or the pre-C++ pseudo-equivalent of a private declaration with no definition) when it would not have been g...
71,752,270
71,752,593
std::make_shared leads to undefined behavior, but new works
Consider the following example class: class Foo { public: void* const arr_; Foo() = delete; Foo(const size_t size, bool high_precision) : arr_(Initialize(size, high_precision)) {}; template <typename T> T* GetDataPointer() { return (T* const)arr_; } private: static void* ...
Your call to make_shared is using a copy constructor for your Foo class, which you haven't defined. Thus, the default (compiler-generated) copy will be used, and the destructor will be called to delete the temporary. As your class doesn't properly implement the Rule of Three, this (potentially) causes undefined behavio...
71,753,355
71,756,155
Virtual function with non-shared method
I'm on a personal project and I need to do something unusual. My code is kinda long but the problem comes from the structure so I'll use a very simplified version of the problem. I have two classes (A and B), with B derived from A. B uses every attributes and methods of A, including one which creates a modified clone ...
Well, according to the comments, my research and how I think c++ works, I give up finding something that looks like virtual methods and still be satisfying. So I resolved to use the CRTP, for those who are interested here's the code of my model of a 3 (I deleted one) inherited class CRTP with an additional type templat...
71,753,426
71,808,652
Need help expanding particle system spread / divergence from 2 to 3 dimensions
I need help. I've been struggling with this for a week now and getting nowhere. I am building a 3D particle system mainly for learning and I am currently working on particle spread / divergence. In specific, introducing random direction to the particle direction so as to create something that looks more like a fountain...
Likely it is because the values of velx, vely and velz are getting overwritten on subsequent calculations. See whether the below works the way you are expecting. // X Divergence float velxXD = (velx * vsin_anglex_dir); float velyXD = (velx * vcos_anglex_dir); float velzXD = velz; // Y Divergence float velxYD = velx; f...
71,753,517
71,857,528
How to include flex ops to the tensorflow lite for microcontrollers interpreter?
Good afternoon, I am trying to implement a transformer network onto a DE10-nano board (2xCortex-A9, armv7-a), using tensorflow lite for microcontrollers (TFLM). I trained the network using python and converted it to .tflite format. When doing so, I get a warning : "TFLite interpreter needs to link Flex delegate in orde...
Flex delegates are not available in TFLM: https://groups.google.com/a/tensorflow.org/g/micro/c/b4v-84f8J5Q. The thing to do is to modify the network to avoid using it. Also, some ops are not compatible between TFLM and TFLite, follow this guide if you're in the case: https://github.com/tensorflow/tflite-micro/blob/main...
71,754,010
71,754,097
Why does the base constructor get called instead of the one with parameters (virtual inheritance)?
#include <iostream> using namespace std; class Point { int x,y; public: Point() { x=0; y=0; } Point(int x, int y) { this->x=x; this->y=y; } Point(Point &p) { x=p.x; y=p.x; } friend class Square; }; class Square { Point _p...
In virtual inheritance, virtual base is constructed according to the most derived class. class Paralellogram: public Rectangle, public Rhombus { public: Paralellogram(Point &p, Point &q, int side_1, int side_2) : Square(), // You have implicitly that Rectangle(p,side_1,side_2), Rhombus(p,q,s...
71,754,032
71,777,388
Is It Possible To Use Reflection To Pass A COM Object From C# to C++?
I have a C# assembly that does some work and sends the results of the work back to a C++ core. I am trying to use Reflection to pass it back since the C# assembly runs on a different thread than the one it was initialized by from the C++ core. I have tried using the COM interface as the parameter type. IDL: HRESULT...
With COM, you should never cast a COM interface into another COM interface like this: STDMETHODIMP CInspectionCore::SendEvent(IDispatch *pEventData) { IEventData *pIEventData = (IEventData *)pEventData; // wrong! } Instead you must use QueryInterface, this works fine: STDMETHODIMP CInspectionCore::SendEvent(IDispa...
71,754,165
71,754,799
Why are unqualified names from nondependent base classes favored over template parameters
The C++ standard says that unqualified names from nondependent base classes are preferred over template parameters. What is the reasoning behind this? The following snippet is from C++ Templates: #include <iostream> template <typename X> class Base { public: int basefield; using T = int; }; class ...
Unqualified lookup is approximately equivalent to trying a qualified lookup in each containing scope and keeping the first hit. Since D2<…>::T can find Base<double>::T, it is the lookup in the class’s scope that succeeds; that lookup naturally precedes that for the template parameters that are introduced lexically out...
71,754,645
71,754,919
C++ killing child thread stops execution of the main thread
I am completely confused with timers and how threads (pthread) work in C++ Timers arent timers but clocks and you cant (I at least cant) kill a thread without killing main thread. What I need - a bit of code which executes once in 24hrs on a separate thread. However if the app needs to stop it - I cant do anything but ...
I dont know how I missed it but if I call pthread_cancel instead of pthread_kill it works just fine.
71,754,789
71,754,952
Erase row from 2D vector where element appears?
I want to delete evry row in a 2d vector, where an element x appears in row for example : x = 2 vec= {{1,2,4,5},{3,7,9},{2,5,7},{1,6,10}} result vec= {{3,7,9},{1,6,10}} I try this #include <iostream> #include <vector> #include <algorithm> void Delete(std::vector<std::vector<int> > &v, int x) { v.erase(std::re...
One of many errors is the comparing only first elements of the subvectors. You wish v.erase(std::remove_if(v.begin(), v.end(), [x](const std::vector<int>& v) { return std::find(v.begin(), v.end(), x) != v.end(); }), v.end());
71,755,034
71,755,308
C++ use sort function on a struct type of array
#include<bits/stdc++.h> using namespace std; ifstream f ("date.in"); ofstream g ("date.out"); int v[10001],maxi,i,maxi1,n,k,mini=INT_MAX,j; struct interval { int stg,dr; } x,a[10001]; int main() { f>>n; for(i=1;i<=n;i++) { f>>x.stg>>x.dr; a[i].stg=x.stg; a[i].dr=x.dr; v[x...
The solution was not that hard: bool cmp( interval a, interval b ) { return (a.stg < b.stg && a.dr < b.dr); }
71,755,049
71,755,228
conditional type define in c++?
I need to define a template class A, which has a nested type according to nested type in template argument. Like this: template<typename Container> class A { public: using NestedType = if (Container has nested type Container::NestedTypeA) { Container::NestedTypeA; } else if (Container has nested...
In C++20, you can just use concepts template<typename Container> struct B { }; template<typename Container> requires requires { typename Container::NestedTypeA; } struct B<Container> { using NestedType = typename Container::NestedTypeA; }; template<typename Container> requires requires { typename Container::Ne...
71,755,420
71,755,637
GCC mod() definition
I was making faster mod(x,2) function in C++ with GCC (compiled using -O3 -ffast-math) and bumped to difference in results between GCC and Octave: float fast_fmod2(float x){ // over 50x faster than std::fmod(x, 2.0f) x *= 0.5f; return 2.0f * ( x - std::floor(x)); } Result (mod(input,2.0f)): Input : -7.85...
I'm assuming you mean std:fmod instead of std::mod (there's no std::mod in the official c++ standard) The reason for this difference is that std::fmod doesn't do what you think it does. std::fmod calculates the remainder and not the arithmetic modulus. Computes the floating-point remainder of the division operation x/...
71,755,425
71,756,215
Last notify_all isn't triggering last conditional_variable.wait
What I'm Trying To Do Hi, I have two types of threads the main one and the workers where the workers are equal to the number of cores on the CPU, what I'm trying to do is when the main thread needs to call an update I set a boolean called Updating to true and call condition_variable(cv).notify_all then each thread will...
Here is how your code works: some waiting in Update is over when notified: cv.wait(lk, [] { return (int)UpdateManager::CoresCompleted >= (int)UpdateManager::ProcessorCount; }); It goes out of waiting and requires the lock on the mutex. Proceed to do its stuff then reaches the end and notifies the other thread that the...
71,755,482
71,755,570
How do I assign to a const variable using an out parameter in C++?
In a class header file Texture.h I declare a static const int. static const int MAX_TEXTURE_SLOTS; In Texture.cpp I define the variable as 0. const int Texture::MAX_TEXTURE_SLOTS = 0; Now in Window.cpp class's constructor I attempt to assign to the variable using an out parameter, however this obviously does not com...
EDIT 2: So since you're trying to abstract OpenGL contexts, you'll have to let go of the "traditional" constructor/destructor idioms. And just for your information (unrelated to this question): OpenGL contexts are not tied to windows! As long as a set of windows and OpenGL contexts are compatible with each other, you m...
71,756,200
71,838,162
how to transfer QImage from QLocalServer to QLocalSocket
I have two mac apps that communicate with each other using QLocalSocket. Able to send the received QString but not able to send the received QImage Below is my code. SERVER SIDE CODE QImage image(":/asset/logo_active.png"); QByteArray ba; qDebug() << image.sizeInBytes() <<image.size(); ba.append((char *)image.bit...
Finally I got the solutions I used QDataStream below is the code example. SERVER SIDE CODE: QDataStream T(mSocket); T.setVersion(QDataStream::Qt_5_7); QByteArray ba; ba.append((char *)img.bits(),img.sizeInBytes()); T << ba; mSocket->flush(); CLIENT SIDE CODE QByteArray jsonData; QDataStream socketStream(mLocalSo...
71,756,251
71,756,328
Why logical operation is not working properly if i use string::size()
string s; cin >>s ; //input string is: a int i=1; if(i < s.size()-3 ) cout <<"Yes"<<endl; else cout << "No"<<endl; If the input string is a then output should be No but compiler is showing Yes. int i = 1; int len = s.size()-3; if(i < len ) cout <<"Yes"<<endl; else cout << "No"<<endl; If I use the len variable then...
s.size() returns an unsigned type. Since s.size() is 1 in your example, unsigned(1)-3 will wrap to a very large positive value. Thus: int i=1; if(i < s.size()-3) compares a signed i to an unsigned value, and so will implicitly convert the value of i to unsigned and evaluate the if as true since 1 is less than that la...
71,756,300
71,756,593
Passing a concept-constrained function overload
The following code fails to compile (Godbolt link): #include <concepts> template <class Fn> decltype(auto) g(Fn&& fn) { return fn(); } template <typename T> requires(std::integral<T>) int f() { return 0; } template <typename T> int f() { return 1; } int main() { f<int>(); f<void>(); g(f<int>); // error: inval...
It seems that neither GCC nor Clang has fully implemented the rules for forming pointers to constrained functions: [over.over]/5 definitely considers constraint ordering in choosing an overload. There were some late changes to these, although they’re just as relevant to the disjoint-constraints case as to the unconstr...
71,756,956
71,757,341
set empty std::regex
How to create a regex from an input argument? If the argument is empty or undefined no regex should be set int main(int argc, char* argv[]){ std::string arg_name; std::string arg_filter; std::cmatch rem; std::regex re; // Match cmd name if(argc > 1){ arg_name = std::string(arg...
As mentioned in the comments, you should use smatch instead of cmatch since you are using std::string. Also, you have created 2 separate re variables. You only want one. int main(int argc, char **argv) { // Match cmd name std::string arg_name; if (argc > 1){ arg_name = std::string{argv[1]}; } ...
71,757,049
71,757,157
Delaying Movement of Servo after button press - Arduino
Recently I have been working on a project where the main goal is to move a servo on a model rocket to deploy a parachute. I want to make is so that 10 seconds after I press the button the parachute is released. I have some code for this already but It is not working, as it stops the code completely. Does anyone know ho...
In Arduino, a delay is usually done with delay(10000); (for 10 seconds). I've never seen or heard of the time.delay() function, so that might be the issue. Otherwise the code looks like it should work as you want. It also might depend on the board you're running it on. I remember having issues using delay() for long pe...
71,757,204
71,826,759
Sending a request to my http server hangs indefinitely in CI environment (CircleCI andgithub actions). Works as expected locally
So I’m writing a basic http server in c++ for school. At the moment my service can receive a request and send a basic response. I’m writing a basic acceptance test with python requests and executing it in a shell script by running the webserver in the background and then running the python client. Locally (on Mac) runn...
This could be caused by trying to run as root in your container, since this could be blocked/limited by the host system (which is configured/owned by circleCI/github in this case) for security reasons. You could try explicitly creating and using a separate user in your Dockerfile, avoiding weird permission issues. As a...
71,757,320
71,757,370
Why does my QT C++ application not update a pushbuttons' text inside the event routine when directed to do so?
I'm very new to Qt Creator and have a question regarding the reason that an update to a pushbuttons text is not occurring at the time I am expecting it to. Below is a snippet of the code showing the pushbutton event. The pushbutton launches another external process (AVRDUDE), which in turn reads the contents of the EEP...
The UI is updated only when the code gets to the Event Loop, which won't happen until your application returns. You can force events processing by calling QCoreApplication::processEvents(); after your UI updates, but the recommended way would be to push that blocking code to another thread and use signals/slots to upda...
71,757,442
71,758,841
Can you do C++-style CUDA?
I follow some guidelines to deal with memory management in C++. Some examples: I never use malloc. I almost never need or use new or delete. I use smart pointers, and almost never need to write destructors. I want to learn CUDA. I have been looking online for tutorials that match my C++ style of programming, but everyt...
CUDA started out (over a decade ago) as a largely C style entity. Over time, the language migrated to be primarily a C++ variant/definition. For understanding, we should delineate the discussion between device code and host code. For device code, CUDA claims compliance to a particular C++ standard, subject to various...
71,757,836
71,757,985
How to make a function dispatch table with a two dimensional map
I want to make a function dispatch table with a 2 dimensional map but i can't figure out how to make a brace enclosed list. enum state_t{ OPENED, CLOSED, OPENING, CLOSING, } state_t do_something(instance_data *data); state_t do_bar(instance_data *data); std::map<const state_t, std::map<const state_t, std::function<sta...
You seem misunderstood smth. The proper initializer list for map in map should look like bellow. const for the key type argument is odd, the key type is const inside the map. std::map<state_t, std::map<state_t, std::function<state_t(instance_data *data)>>> state_table {{ OPENED, { {OPENED, do_something}, {CLOSI...
71,758,110
71,758,336
How can I make a template class within a template class
I am working on recreating the forward linked list class so I can better understand pointers. I have hit a roadblock, I have a template class called forward_list. Within this class in the private section I have another class which I want to have the same type as the main (external) class, this class is called node. #if...
Your first example is pretty close to what you want. The thing to realize is that while forward_list is a class template, forward_list<T> is a class, and forward_list<T>::node is also a class, not a class template. But also forward_list<int>::node is a totally separate class from forward_list<double>::node, even though...
71,758,665
71,761,221
OpenGL draw transparent sphere over solid sphere
I have a small sphere with an Earth texture and I want to have a slightly bigger sphere with clouds texture over it, that is transparent. I draw my objects like this. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, ...
Do the following: enable backface culling enable depth test disable blending draw solid earth enable blending draw transparent clouds
71,758,785
71,758,912
no matching function for call to CLASS:CLASSCPP(C++)
ERROR : Description Resource Path Location Type no matching function for call to 'Saat::Saat()' Ucus.cpp /project9/src line 4 C/C++ Problem This my class called Saat #ifndef SAAT_H_ #define SAAT_H_ #include <string> class Saat { public: Saat(int, int); std::string to_string() const; private: ...
In a class, members are created before the body of the constructor is entered. Your code is attempting to default construct a Saat, and then overwrite it in the body through assignment. Because your Saat class does not have a default constructor, your code doesn't compile. WHY doesn't your class have a default constru...
71,758,822
71,758,921
Strange behaviour of vector in cpp
I was writing the naive version of the polynomial multiplication algorithm. I tried the following code: #include <iostream> #include <vector> using namespace std; vector<int> multp(const vector<int>& A, const vector<int>& B) { vector<int> result = {0}; for(int i = 0; i < A.size() + B.size(); i++) { re...
vector<int> result = {0}; creates a vector with one element so you aren't allowed to access anything but result[0]. An alternative would be to create the vector with as many elements that you need, A.size() + B.size() - 1. Example: #include <iostream> #include <vector> std::vector<int> multp(const std::vector<int>& A,...
71,758,847
71,796,997
ANTLR4: Re-visiting parse rules after the whole ast is visited
I am currently implementing generic functions for my own language, but I got stuck and currently have the following problem: Generic functions can get called from another source file (another parser instance). Let's assume we have a generic function in source file B and we call it from source file A, which imports sour...
I don't think the best approach is to hack around with parsers. Parsers should turn one array of characters into one AST. In your case, you've got a fairly complex but new language, using multiple files. When you import B, you really want to import the AST. C++ historically messed with a literal #include and the parsin...
71,758,865
71,758,936
Compile-time arithmetic via generic types in Rust, similar to C++?
I'm just learning Rust and would like to write code that uses generic types to perform compile-time arithmetic. For example, in C++ I can write the following code (on Goldbolt): #include <iostream> template <int X> struct Test { constexpr static int x = X; }; template <int X1, int X2> auto operator+(const Test<X1...
You can do it, but const generics aren't complete yet, so it currently requires a nightly compiler and an explicitly enabled feature: #![feature(generic_const_exprs)] #![allow(incomplete_features)] use std::ops::Add; pub struct Test<const X: u8>; impl<const X: u8> Test<X> { pub fn x(&self) -> u8 { X } } impl<co...
71,759,207
71,759,455
I need to track changes to files, but I cannot think of a way
I have an idea that I am working on. I have a windows mini-filter driver that I am trying to create that will virtualize changes to files by certain processes. I am doing this by capturing the writes, and sending the writes to a file that is in a virtualized location. Here is the issue: If the process tries to read, it...
Two solutions: Simply copy the original file to virtualized storage, and use only this file. For small files, it will probably be the best and fastest solution. To give an example, let's say that any file smaller than 65536 bytes would be fully copied - use a power of two in any case. If file is growing above limit, s...
71,760,243
71,781,767
Use std::function to wrap a function with optional arguments (using maybe boost::optional), and serve as a template in another class
In my recent project I want to define a class X which has an input functional in its constructor, i.e., std::function<double(const A&, const B&)>. In real applications, the argument of class B is optional (sometimes it will not have this argument). So I am trying to use the boost::optional for the second argument in my...
With typo fixed, it would be #include <functional> #include <optional> template <typename Function, typename A, typename B, typename... Args> class X { public: X(Function f, A a, std::optional<B> b) : f_{f}, a_{a}, b_{b} { } void call_function(Args... args){ f_(a_, b_, args....
71,760,259
71,760,305
How to forward a non-movable object in std::pair
I can't figure out the syntax to perfectly forward a std::pair when it contains something that's non-movable. #include <mutex> #include <list> #include <utility> struct A { A(int x) { } }; int main() { std::list<std::pair<std::mutex, std::mutex>> v; v.emplace_back(); // ok std::list<std::pai...
You must construct the std::mutex in-place from an empty argument list. This can be done using the std::piecewise_construct constructor, which allows you to forward arguments for the constructors of the two elements as std::tuples. // for std::forward_as_tuple #include<tuple> // ... v3.emplace_back(std::piecewise_con...
71,760,656
71,760,732
How to transferring an array of main functions to a class?
First of all, I made this class. class Matrix { public: double ele[4][4]; int numOfRow; int numOfColumns; public: Matrix() { numOfRow = 0; numOfColumns = 0; ele[4][4] = 0; } Matrix(double mat[][4], int Row, int Col) { numOfRow = Row; numOfColumns = Col; ...
You are assigning a value to your matrix out-of-bounds: ele[4][4] = 0; The last element of double ele[4][4]; is ele[3][3]; This is undefined behavior, so it makes no sense to analyze what happens after it. You can 0-initialize your Matrix in its constructor like this: Matrix(): ele(), numOfRow(), numOfColumns() {}...
71,761,445
71,773,988
why does wxDC::GetTextExtent() return the same value for a high DPI display in wxWidgets?
I am trying to scale my application written in c++ with wxWidgets for high DPI displays. I am following the guidelines in the official link. Everythings work fine so far except the return value of wxDC::GetTextExtent() function. When I move my window to a monitor with a different DPI, the font size scales but the retur...
wxDC::GetTextExtent() and wxWindow::GetTextExtent() should return the same value and if I insert this code in the minimal sample: void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxClientDC dc(this); wxLogMessage("wxDC: %d, wxWindow: %d", dc.GetTextExtent("Hello").x, Ge...
71,761,810
71,762,002
sleep_for causes buffering effect
If I comment out the sleep_for, the program churns out commas and dots without issues. But when I add the sleep_for, it hangs for a while before suddenly writing all of the commas and dots you would have expected to come evenly during the hang all in one go. This program was reduced to a minimum working example from so...
Output to std::cout is buffered. It might be that the output without the delay will fill up the buffer quick enough that you won't notice it. If you want immediate output you need to explicitly flush it: std::cout << c << std::flush;
71,762,727
71,762,912
Is there a data structure for implementing a function equivalent to 'tail -n' command in C++?
I want to write a function equivalent to the Linux tail -n command in C++. While, I parsed over the data of that file line-by-line thereby incrementing the line count, if the file size gets really big(~gigabytes), this method will take a lot of time! Is there a better approach or a data structure to implement this func...
One of the things that is slowing down your program is reading the file twice, so you could keep the last n EOL positions (n=10 in your program) and the most convenient data structure is a circular buffer but this isn't provided by the standard library as far as I know (boost has one). It can be implemented by an std::...
71,762,790
71,762,872
Why do I get a not declared in this scope error even though the header file is included?
The error I get is /opt/workspace/IhmActon/ihm_acton/src/model_inference/retinanet/engine.cpp:213:5: error: ‘trt_unique_ptr’ was not declared in this scope trt_unique_ptr<trt::IHostMemory> serialized_engine = wrap_trt_ptr(engine->serialize()); This is a photo snippet of that function and where the error is The ...
trt_unique_ptr is inside namespace ihm_springfield. Use ihm_springfield::trt_unique_ptr instead.
71,763,111
71,763,730
How make std::set insertions faster?
I am using the std::set container to store some scalar integer values. I've noticed that the insert operation is slow when I call it in a loop. How can I make it faster? Here is some representative code: std::set<unsigned long> k; unsigned long s = pow(2,31); for(unsigned long i = 0; i < s; i++){ k.insert(i); } s...
How make set function faster? You can make this faster by using hints, since you know that every insert is to the end of the set: for(unsigned long i = 0; i < s; i++){ k.insert(k.end(), i); } Alternatively, you could potentially make it faster using another data structure, such as std::unordered_set for example....
71,763,247
71,763,485
Compare vector<int> with no name
#include <iostream> #include <string> #include <vector> #include <list> using namespace std; int main() { std::list<int> list{ 1, 2, 3, 4, 5 }; std::vector<int> vec1{ 1, 2, 3, 4, 5 }; std::vector<int> vec2{ 1, 2, 3, 4 }; if(vector<int>(list.begin(), list.end()) == vec1) { cout << "haha"; ...
How is it possible to compare vector with no name and vec1. std::vector has overloaded operator== as a non-member function. template< class T, class Alloc > bool operator==( const std::vector<T,Alloc>& lhs, const std::vector<T,Alloc>& rhs ); This means that when you wrote: vector<int>(list.begin(),...
71,763,498
71,763,598
Why does the following not compile?
Given the following code, #include <iostream> #include <string> #include <string_view> #include <unordered_map> struct sstruct { std::string content; std::string_view name; virtual std::string get_content() { return ""; } }; int main() { std::unordered_map<std::string, sstruct> map{ ...
If the member function is not virtual, then your class is an aggregate class. (For the requirements making a class aggregate, see here.) An aggregate class can be aggregate initialized, which means it can be initialized with a braced initializer list such as {"dddd", ""} and aggregate initialization will initialize eac...
71,763,917
71,764,165
How much can I change code to keep rand() giving same output for given seed?
I'm implementing an algorithm. Because calculations takes time, and I need to repeat them multiple times, I'm saving to output file seed values as well. The idea was that I could repeat same instance of a program if I'll need to get more info about what was happening (like additional values, some percentage, anything t...
Your understanding about srand is correct: seeding with a specific value should be enough to generate a reproducible sequence of random numbers. You should debug your application to discover why it behaves in a non-reproducible way. One reason for such behavior is a race condition on the hidden RNG state. Quoting from ...
71,764,074
71,764,235
srand(n) giving same values for any n
void generator() { int n = <some number>; srand(n); int first = randint(9); digits.push_back(first); while (digits.size() < 4) { bool flag = true; int num = randint(9); for (int j = 0; j < digits.size(); j++) { if (num == digits[j]) { ...
std::experimental::randint is coupled with std::experimental::reseed to set the seed per thread: srand will have no effect on the generated output. You'll probably find that randint is automatically seeded with a constant value which accounts for your output. As it never became part of the C++ standard, I cannot commen...
71,764,991
71,766,247
gdb watch a variable by address stop at where it cannot be modified
A program crashes. I use gdb to check, find that a private member of a instance is changed in a very weird way. This variable refreshRank,is only modified at line 283 and 286. I use gdb to watch refreshRank by watch its address, i.e., watch *0x5555559ec278. I get the address by p &refreshRank when I am in a member func...
As @j6t points out, the last line it executes, totalReads[transaction->core]++;, transaction->core is out of bound. And in the class definition: uint64_t totalReads[NUM_CPU]; uint64_t totalPrefReads[NUM_CPU]; uint64_t totalWrites[NUM_CPU]; unsigned channelBitWidth; unsigned rankBitWidth; unsigned bankBitWidth; unsign...
71,765,067
71,765,414
Error about operator overloading when I try to compile this code
#include<iostream> #include<iomanip> using namespace std; class Rice { float price_per_kg, total_weight; public: Rice(float w) { price_per_kg = 10.0; total_weight = w; } void display_rice() { cout<<"----------------------------------------"<<endl; cout<<"\tRi...
The compiler is telling you a Rice isn't a Product. Either you change the return type Rice operator+(const Product &p) Or you change the expression you return { Product result = *this; result.kg += p.kg; // or some other things? return result; } Or you re-think your classes. Do you really mean that a Prod...
71,765,698
71,765,798
Use class as type in other class constructor
i would like to use a class Point in an other class Rect. class Point { int x, y; public: Point (int px, int py){ x = px; y = py; } }; class Rect { Point top_left; Point bottom_right; public: Rect (Point p1, Point p2){ top_left = p1; bottom_right = p2; ...
The problem is that when a Rect object is created, the member variables are constructed and initialized before the Rect constructor body is executed. Since there's no explicit initialization of the Point member variables, they will need to be default constructible, which they aren't because you don't have a default Poi...
71,765,955
71,770,854
How to place a space at the end of cout
I need to know why c++ doesn't see the space just at the end of cout function. I'm using CLion and C++ 23 (language_standart) int main() { string Item ; double Price ; int Quantity ; double Total ; cout << "Your item to buy : " ; getline(cin, Item) ; cout << "Price of the item : " ; c...
Apparently one of the workarounds is, try doing the following: in Registry (Help | Find Action..., type Registry there) disable the run.processes.with.pty option and restart CLion. Does that help? According to the response in CPP-12752 disabling PTY (without CLion restart, since the run.processes.with.pty option is not...
71,765,969
71,767,336
Binary Search Implementation in C++
I have written a program which should do the following: read product item data from an inventory file and add them in a vector object. The program will allow user to view, search and order the product items. The inventory file should be updated after the order of any item. For operation #2 (searching) and #3 (orderin...
I checked your GitHub project. I think you have to sort data before binary search. Current Data in the sample text file list like this: Dish Washer Microwave Cooking Range Circular Saw And these are not sorted, so you can not use Binary Search.
71,765,979
71,766,399
Double derived class produces error unless call to Base
The following code causes my compiler to produce two errors: type name is not allowed and expected an expression. #include <iostream> class Base { protected: template <typename T1> void print_pi() { std::cout << (T1)3.141596 << std::endl; }; }; template <typename T2> class Derived : public Base ...
In the class Derived the name print_pi is a dependent name. You can use for example template <typename T3> class DoubleDerived : public Derived<T3> { public: void test() { Derived<T3>::template print_pi<int>(); } }; or template <typename T3> class DoubleDerived : public Derived<T3> { public: void t...
71,766,043
71,767,154
Why does a segmentation fault not occur?
I am expecting a seg-fault to occurr after the execution of the code below, but it doesn't. Could someone tell me why? int main(){ float *arr; cout << arr[0] << "\n" --> This prints out a ZERO. I am expecting a seg-fault. cout << arr[1000] << "\n" --> This gives me a seg-fault return 0...
Since the pointer arr is not initialized, it probably has the value of whatever value that memory address had when it was previously used. In your case, the code that used that memory address previously probably used that memory address for storing a pointer, i.e. for storing another memory address that points to a val...
71,766,426
71,768,080
Sort in descending order the array elements that belong to the shaded area
#include <iostream> #include <cmath> #include <stdlib.h> #include <iomanip> using namespace std; int **CreateMatrix (int rows, int cols); void FillMatrix (int **matrix, int rows, int cols); void OutputMatrix (int **matrix, int rows, int cols); void SortMatrix (int **matrix, int rows, int cols); void DellMatrix(int **...
I would do it like that: int NumberOfValues(int cols) { int count = 0; for (int i = cols; i > 0; i -=2) count += i; return count; } void FillMatrix(int **matrix, int rows, int cols){ int N = 19; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i...
71,767,545
71,777,790
OpenMP parallel loop much slower than regular loop
The whole program has been shrunk to a simple test: const int loops = 1e10; int j[4] = { 1, 2, 3, 4 }; time_t time = std::time(nullptr); for (int i = 0; i < loops; i++) j[i % 4] += 2; std::cout << std::time(nullptr) - time << std::endl; int k[4] = { 1, 2, 3, 4 }; omp_set_num_threads(4); ...
As already pointed out in the various comments, the crux of your problem is false sharing. Indeed, your example is the typical case where one can experiment this. However, there are also quite a few issues in your code, such as: You will likely see overflows, both in your loops variable and in all of your j and k tabl...
71,767,599
71,767,745
no matching function for call to ‘std::exception::exception(<brace-enclosed initializer list>)
My project builds on Windows (vc++17) and I am new to Linux builds so I am not sure what is going on. I created CMakeLists files for my project (with a C++17 requirement), generated the makefile, and then I used make to try build it on Linux. The error is: /home/julien/source/zipfs/zipfs/include/zipfs/zipfs_assert.h:30...
std::exception does not provide a constructor that accepts a const char* parameter. If one exists on the Windows standard library you are using, it is a non-portable extension to the language. There are many derived classes that could be used as your base class instead, which do support this constructor.
71,768,643
71,769,027
what is stopping the random num generator from randomizing every time a player starts a new game?
{ int i,game = 0,guess,count = 0; int rando; srand (time(0)); rando = rand() % 50 + 1; cout << "****Welcome To The Game****\n"; cout << "1: Start the game\n"; cout << "2: End the game\n"; cin >> game; while (game != 2 && count != 11) { ...
int randomGame() { int gameMenuChoice = 0; srand(time(0)); std::cout << "****Welcome To The Game****\n"; std::cout << "1: Start the gameMenuChoice\n"; std::cout << "2: End the gameMenuChoice\n"; std::cin >> gameMenuChoice; while (gameMenuChoice != 2) { const int rando = rand()...
71,768,869
71,769,034
Polymorphic pointer change at run time
I am really confused about polymorphic pointers. I have 2 classes derived from an interface as shown below code. #include <iostream> using namespace std; class Base { public: virtual ~Base() { } virtual void addTest() = 0; }; class B: public Base { public: B(){} ~B(){} void addTest(){ ...
It's perfectly fine to change what a pointer points to. A Base* is not an instance of Base, it is a pointer that points to an instance of a Base (or something derived from it -- in this case B or C). Thus in your code, base = new B() sets it to point to a new instance of a B, and then base = new C() sets it to point to...
71,768,929
71,775,108
check boolean expression in dataframe Rcpp (C++)
I have a dataframe dat with data and a vector rule with logical rules set.seed(124) ro <- round(runif(n = 30,1,10),2) dat <- as.data.frame(matrix(data =ro,ncol = 3)) ; colnames(dat) <- paste0("x" ,1:ncol(dat)) rule <- c("x1 > 5 & x2/2 > 2" , "x1 > x2*2" , "x3!=4") I need to check if the expression is true id <- 2 ...
Two things worth stressing here are you do not need a low over all rows as R is vectorized, and that already fast you can sweep the rules over your data and return a result matrix Both of those are a one-liner: > res <- do.call(cbind, lapply(rule, \(r) with(dat, eval(parse(text=r))))) > res [,1] [,2] [,3] ...
71,768,987
71,770,102
Type Punning via constexpr union
I am maintaining an old code base, that is using a union of an integer type with a bit-field struct for type-punning. My compiler is VS2017. As an example, the code is similar to the following: struct FlagsType { unsigned flag0 : 1; unsigned flag1 : 1; unsigned flag2 : 1; }; union FlagsTypeUnion { un...
You might use std::bit_cast (C++20): struct FlagsType { unsigned flag0 : 1; unsigned flag1 : 1; unsigned flag2 : 1; unsigned padding : 32 - 3; // Needed for gcc }; static_assert(std::is_trivially_constructible_v<FlagsType>); constexpr FlagsType makeFlagsType(bool flag0, bool flag1, bool flag2) { F...
71,769,919
71,770,164
what does func() = var_name; assignment do in c++?
I was studying about l-values and r-values but I am confused with this: #include<iostream> int& get_val(){ return 10; } int main(){ get_val() = 5; int a = get_val(); std::cout<<a<<std::endl; return 0; } I know about int a = get_val(); (i.e., it will assign the returned value to the variable), but ...
Your get_val function is defined as returning a reference to an integer; however, what you actually return is a reference to a constant, so any attempt to assign a value to that will not compile. In fact, the function itself (attempting to return a reference to 10) won't compile; clang-cl gives this: error : non-const...
71,770,190
71,778,887
Implementing two pointer technique in sets in C++
I am trying to implement two pointer technique in sets in C++. I want to check if the difference of two elements of a set equals to a constant 'k'. void solve(int n,int k,set<int> s){ auto it_1 = s.begin(); auto it_2 = s.end(); while(it_1 < it_2){ if(*it_2 - *it_1 == k){ cout << "YES" <...
The problems with the iterators can be solved quickly. Simply use the != operator instead of < Do not start from the end-iterator, but one element before. Because the end-iterator points at past the last valid element. But, unfortunately the 2 pointer approach will not work, if you want to find a pair with a given de...
71,770,439
71,771,023
c++ arduino multiple display objects in a structured array
I have declarations for multiple OLED displays running via an 8 channel i2c Mux: Adafruit_SSD1306 display1(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET); Adafruit_SSD1306 display2(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET); Adafruit_SSD1306 display3(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET); Adafruit_SS...
You could initialize your array like this: Adafruit_SSD1306 display[]{ {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, {SCREEN_WIDTH, SCREEN_HEI...
71,770,724
71,771,036
Generating simple format string at compile time
I'm trying to generate a simple format string for fmt at compile time, but I can't quite figure out the string concatenation. I'm limited to c++ 14. What I'd like is to be able to generate a format string for N items, so it could be used as follows: auto my_string = fmt::format(format_string_struct<2>::format_string, ...
You have several typos (and a concat limited to 2 argument). template<int...I> using is = std::integer_sequence<int,I...>; template<int N> using make_is = std::make_integer_sequence<int,N>; constexpr auto size(const char*s) { int i = 0; while(*s!=0){++i;++s;} return i; } template<const char*, typename, const c...
71,771,147
71,771,211
Why does my DLL not require a DllMain function?
I just added a C++ Windows DLL project to a Visual Studio (2022) solution. The wizard put a DllMain in there. That jumped out at me; I didn't remember my other DLLs having DllMain functions; Searching my code, it turns out that none of my 9 DLLs have DllMain functions. Yet they all build and work fine. I checked th...
The runtime library ("CRT" = C/C++ Runtime Library) provides the real DLL entry point _DllMainCRTStartup, that does things like initializing global variables before calling your DllMain. There's documentation on MSDN that describes this: DLLs and Visual C++ run-time library behavior Documentation of the linker /ENTR...