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
70,192,581
70,193,326
Uninitialized default constructor in c++: munmap_chunk(): invalid pointer
having this code: #include <iostream> #include <iterator> #include <initializer_list> #include <algorithm> class Foo { public: Foo() = default; explicit Foo(size_t size) :size(size){ ar = new double[size]; } Foo(std::initializer_list<double> initList): Foo(initList.size()){ std::copy(in...
If it is not brace-initialized, then the int *ar is indeterminate. But what does that mean? How could be pointer indeterminate? Because you are not assigning any value to the pointer, not even nullptr. So its value will consist of whatever random bytes were already stored in the memory location that the pointer is o...
70,192,715
70,200,923
Qt: Shared C Library Exported From Golang
I was doing some tests with Golang exporting shared libraries that can be used in C and came up with the following: calcLib.go: package main import "C" //export Calculator func Calculator(x int, y int) int { return x+y; } func main() { // Need a main function to make CGO compile package as C shared library } ...
In qmake project files LIBS variable uses same cli keys as gcc linker -L to specify searchpath for libraries and -l for library name (without lib prefix and without .a or .dll or .so suffix, I believe version with prefix should also work). So it should be LIBS += -L$${PWD}\shared -lCalc qmake-variable-reference
70,193,786
70,194,189
OpenGL: Problem with lighting when rotating mesh
I'm drawing some static geometry (a sphere, a cube, etc.) together with some dynamic geometry (a rotating torus.) I can see that there is a problem because specular lighting on the torus is static and the torus is rendered dark when the rotation angle changes... I'm targeting OpenGL 2.1 (desktop), OpenGL ES2 (mobile)...
I found the solution: passing a new normal matrix (extracted from the model-view matrix) to the shader when drawing the dynamic mesh. Matrix modelMatrix; modelMatrix .translate(75, -60, 100) .rotateY(clock()->getTime()); Matrix modelViewMatrix = modelMatrix * camera.getViewMatrix();...
70,193,889
70,196,028
Qt6 Connect Signal to Lambda Function
I'm using a DataRouter class to handle communication with a QSerialPort (and then communicate the results elsewhere). The connected device sends a status package every second or so, and I would like to read it without polling the device. I tried directly using QSerialPort's waitForReadyRead function, but no matter how ...
If your "target" is not QObject you need to use the following overload of connect. The problem is that, you are trying to use non-QObject as "context" to determine the lifetime of the connection and that's not possible. To mitigate it you will need to release the connection somehow on DataRouter's destruction; one way ...
70,194,630
70,194,799
How to iterate Set in nested way like array in CPP
I want to perform this kind of operation using a set: set<int> s; for (int i=0;i<n-1;i++){ for(int j=i+1;j<n;j++){ cout << s[j]; } }
Oh, Are you looking for this. What you want to achieve is can be done with the help of C++ Iterators. set<int> st = {4, 3, 5, 6}; set<int>::iterator it1, it2; for (it1 = st.begin(); it1 != st.end();) { for (it2 = it1++; it2 != st.end(); it2++) { cout << (*it2) << space; } cout << endl; } Output 3 ...
70,194,714
70,213,443
How to return a StructArray from Multiple Scalar Functions
I have a scenario where I am working with temporal data in Apache Arrow and am using compute functions to extract date/time components like so: auto year = arrow::compute::CallFunction("year", {array}); auto month = arrow::compute::CallFunction("month", {array}); auto day = arrow::compute::CallFunction("day", {array});...
Is there a simply way of registering such a function with the current API? I don't think so, your use case looks too specific. On the other hand if you do that often you can implement something that would do it for you: std::shared_ptr<arrow::Array> CallFunctions(std::vector<std::string> const& functions, ...
70,194,784
70,194,842
Why it shows illegal memory location when sorting vector after merge?
I tried to sort a new vector after merge two vector, the code like that, #include <iostream> #include <vector> #include <map> #include <string> #include <algorithm> using namespace std; void vec_output(vector <int> vec_input) { for (int i = 0; i < vec_input.size(); i++) { cout << vec_input[i] << ...
The problem is that v3 is empty so writing v.begin() as the last argument to set_union isn't possible. You should use back_inserter as: set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3)); The std::back_inserter will return an output iterator back_insert_iterator that will use v3.push_back t...
70,195,292
70,195,419
Error while concatenating a vector to itself in c++
I am simply trying to concatenate a vector to itself but the following code is not working and I am not able to find the issue. If my input vector is {1,2,1}, the o/p I am getting is {1,2,1,1,16842944,1}. Please tell where I am wrong. The output I want is [1,2,1,1,2,1] vector<int> getConcatenation(vector<int>& nums) {...
In your original program push_back invalidates the iterators and using those invalidated iterators can lead to undefined behavior. One way to solve this would be to use std::copy_n with std::vector::resize as shown below: vector<int> getConcatenation(vector<int>& nums) { std::vector<int>::size_type old...
70,195,308
70,236,070
Longest common prefix in binary representation
We are given a undirected tree with N (1 to N) nodes rooted at node 1. Every node has a value assigned with it, represented by array - A[i] where i:[1:N]. We need to answer Q queries of type : -> V X : longest length of the common prefix between value V and any ancestor of node X including X, in their binary representa...
You can solve this problem in O((N+Q) log N) time using fully persistent binary search trees. A "persistent" data structure is one that preserves the previous version when it's modified. "Fully persistent" means that the previous versions can be modified as well. Often, fully persistent data structures are implemente...
70,195,610
70,200,809
Correct variadic pack expansion
I am working on C++20 implementation of tuple: template<size_t INDEX, typename T> struct wrap { [[no_unique_address]] T data {}; }; template<typename...> class base {}; template<size_t... INDEX, typename... Ts> class base<index_sequence<INDEX...>, Ts...> : public wrap<INDEX, Ts>... { public: constexpr base( const...
Parameter pack expansion also applies to member initializer lists, so you can simply do this: template<size_t INDEX, typename T> struct wrap { [[no_unique_address]] T data {}; }; template<typename...> class base {}; template<size_t... INDEX, typename... Ts> class base<std::index_sequence<INDEX...>, Ts...> : public wr...
70,195,782
70,196,798
Does the effect of std::launder last after the expression in which it is called?
Consider the following sample code: struct X { const int n; }; union U { X x; float f; }; void fun() { U u = {{ 1 }}; u.f = 5.f; // OK, creates new subobject of 'u' X *p = new (&u.x) X {2}; // OK, creates new subobject of 'u' if(*std::launder(&u.x.n) == 2){// condition is true because of std::l...
cppereference is quite explicit about it: std::launder has no effect on its argument. Its return value must be used to access the object. Thus, it's always an error to discard the return value. As for the standard itself, nowhere does it state that its argument is also laundered (or not), but the signature of the fun...
70,195,806
70,196,027
Why g++ O2 option make unsigned wrap around not working?
I was trying to write a queue with c++, and I learn from intel dpdk libring that I can do that by writing codes like that using the unsigned wrap around property: #include <cstdio> #include <cassert> #include <atomic> #include <thread> size_t global_r = 0, global_w = 0, mask_ = 3; void emplace() { unsigned long loc...
Are you aware that once global_w is incremented to 3 then the while loop in emplace() becomes an infinite loop? AFAIK, infinite loops result in undefined behavior in C++. I believe your problem comes from the fact that you define std::jthread objects as temporaries. This means that they are destructed at the end of exp...
70,195,940
70,195,969
Cannot initialize a variable of type 'int *const' with an rvalue of type 'const int *'
Why I have the error for the following code: const int r = 3; int *const ptr = &r; However it works normaly if I define r as a plain int. As I understand, the second line only defines the pointer ptr as a const, which means that the value of this pointer cannot be changed. But why I a const pointer cannot point to a c...
The clockwise/spiral rule says that the definition int *const ptr = &r; makes ptr a constant pointer to non-constant int. That is, while the variable ptr itself can't be modified (you can't assign to ptr), what it points to can. And that doesn't match the type of r which is constant. If you want a constant pointer to ...
70,196,184
70,199,176
How the forcing rebuild in my Makefile actually work?
How to force make to always rebuild a file from this answer more specifically, I was able to achieve my goal as a beginner, so I better commented on everything. I have these 4 files in one directory; ls -F: iterator Makefile test* test.cpp where all the files should be self-explanatory, but I have some little feeli...
From the manual: One file can be the target of several rules. All the prerequisites mentioned in all the rules are merged into one list of prerequisites for the target. If the target is older than any prerequisite from any rule, the recipe is executed. In your case you have two rules for the app target. The prerequis...
70,196,602
70,196,659
User Defined Literal naming in C++
In a recent code review I came across the following: constexpr Dimensionless operator"" _(...) {} In my reading of the standard I cannot work out if this is UB, unspecified behaviour, or underspecified behaviour. From 17.6.4.3.2 [global.names] we know that: Each name that begins with an underscore is reserved to the ...
Does the standard allow for a literal that is only an underscore (42_)? Yes. As per [lex.ext] the grammar of a user-defined-literal, for all families of user-defined literals, is: <family-specific grammar> ud-suffix ud-suffix: identifier [over.literal]/1 describes the limitations on the ud-suffix in the contex...
70,197,200
70,216,424
How to write file-wide metadata into parquetfiles with apache parquet in C++
I use apache parquet to create Parquet tables with process information of a machine and I need to store file wide metadata (Machine ID and Machine Name). It is stated that parquet files are capable of storing file wide metadata, however i couldn't find anything in the documentation about it. There is another stackover...
You can pass the file level metadata when calling parquet::ParquetFileWriter::Open, see the source code here
70,197,214
70,197,326
Can I use templates to create a function that creates a variable without it appearing in function parameter list?
If I have function template like : template<typename T> void create() // T absent here in function parameter list { T var; // variable of type T created without it appearing in function parameters // do something } Is this a valid function? Can function use template variables without them appearing function param...
Is this a valid function? Yes it is a valid function template. But note that since there is no way to deduce the template parameter T from function call argument since the function takes no call arguments, you must explicitly specify the template argument when calling this function template as shown below: int main()...
70,197,414
70,198,694
QMultiMap with QVariant as key
I have a multimap with QVariant as key, but it's not working with QByteArray. The funcion map.values("\xc2\x39\xc7\xe1") is returning all the values of the map. This is a small example: #include <QCoreApplication> #include <QMultiMap> #include <QVariant> int main(int argc, char *argv[]) { QCoreApplication a(argc, ar...
It appears to be a bug in Qt, because the operator QVariant::operator<() does not provide a total ordering, even though QByteArray::operator<() does. And QMap relies on that (see QMap documentation). QByteArray b1("\xc1\x39\xc7\xe1"); QByteArray b2("\xc1\x39\xc7\xe2"); QVariant v1(b1); QVariant v2(b2); assert(b1 < b2 ...
70,197,659
70,197,733
c++ callbacks to another member function
I have a question on callbacks. Previously, I am associating my callbacks to a class Q class Q{ using Callback = std::function<void(char*, int)>; Q:Q(); Q:~Q(); void Q::RegisterCB(Callback callbackfunc) { callback_func = callbackfunc; } void Q:someEvent() { callback_func(); } }...
&R::handleCallback has the type void (R::*)(char*, int), which is not convertible to std::function<void(char*, int)>. Also, RegisterCB takes one argument, not two. The most straightforward fix is to wrap the call in a lambda function, q.RegisterCB([this](char* p, int x) { handleCallback(p, x); });
70,198,828
70,199,633
How to play a sf::Sound in a loop?
We (school) are developping a game in C++ with SFML. The game is a fight game, where we need to play little sounds when the player gets hit for exemple. I'm attempting to play a sf::Sound in a loop. I know we should not call the play() method of sf::Sound in a loop, but as the SFML apps all run in while loops, I have n...
The issue is not with "being called outside the loop"; the issue is that your sf::Sound object is destroyed at the end of the playSound function! First, define two global (or class-) variables: std::map<std::string, sf::SoundBuffer> buffers; std::map<std::string, sf::Sound> sounds; You can now define playSound as foll...
70,199,212
70,211,034
How to set QSizePolicy in QSS stylesheet
Is it possible to change the QSizePolicy property from the stylesheet? So far I know every QWidget has the property sizePolicy. But the QSizePolicy constructor takes two arguments; so I'm not sure how to set this property from a QSS file. Also calling: MyWidget { qproperty-sizePolicy: 2; // "Expanding", Expanding, ...
It seems it is not possible out of the box. I will have to subclass whatever QWidget I want and add two Q_PROPERTIES for each direction of the QSizePolicy. See this thread.
70,199,224
70,200,485
trouble linking with glfw using premake and vs2019
I am trying to build a simple project using premake 5. On win10 using visual studio 2019. Premake is new for me, but I start simple : the only dependencies are glm ( headers only library), GLAD, and GLFW. I included GLAD and GLFW as subprojects in my premake file. Project generation goes fine. glm is correctly included...
Thanks to 'Botje' comment, I realized there was a bunch of missing files in the premake script. (I got this file from another project and wrongly assumed it was correct ) I found the missing files when looking into CMakeLists.txt present in glfw project source directory. here is the new lua premake script for glfw proj...
70,199,643
70,200,012
undefined behavior with std::labs with unsigned number across multiple platforms
I want to find absolute of (a-b), where a, b are 32-Bit unsigned integer. I have used std::labs as shown below. But the operation is behaving differently in different platforms! #include <iostream> #include <cstdlib> using namespace std; int main() { uint32_t x = 0, y = 0, z_u = 0, result_labs = 0, result_abs = 0,...
The behavior is defined (except may be for the printf). You call the functions with x - y argument. Both x and y are uint32_t so the result is also uint32_t, so it will never be negative. Arithmetic operations on unsigned types "wraps around". labs takes long argument, so the argument is converted to long before passin...
70,200,519
70,201,377
How to statically allocate memory based upon type information from another translation unit
I have a bunch of complex classes in one translation unit which involves a bunch of header dependencies. In addition, the translation unit provides a factory function. // MyClass.h #include "Interface.h" // lots of other includes class MyClass : public Interface { // lots of members }: // Creates an instance of My...
How to achieve my goal then? Approuch 1: static assert and "gueess" sizes. There is no dependency between interface.h and the class, but you have to manually update the header on each change (or, better, generate the header from the build system). // interface.h using Interface_storage = std::aligned_storage<20, 16>;...
70,200,637
70,200,792
C++ struct and function declaration. Why doesn't it compile?
This compiles fine (Arduino): struct ProgressStore { unsigned long ProgressStart; unsigned long LastStored; uint32_t FirstSectorNr; }; void IRAM_ATTR ProgressInit(ProgressStore aProgressStore){ } Leave out the IRAM_ATTR and it doesn't compile anymore(?): Verbruiksmeter:116:6: error: variable or field...
See here: https://stackoverflow.com/a/17493585/2027196 Arduino does this mean thing where it finds all of your function definitions in main, and generates a function declaration for each above the rest of your code. The result is that you're trying to use ProgressStore before the ProgressStore struct is declared. I bel...
70,201,184
70,201,282
How to read data from a Vector
How can I use the following vector to read true/false from using a while or for loop. With this implemtation of the loop I get an error for the oprator != no operator "!=" matches these operands vector<bool> Verification; Verification.push_back(true); Verification.push_back(false); Verification.push_back(true); Veri...
You are declaring it as the wrong type. The result of Verification.begin() is a std::vector<bool>::iterator. But you don't need to specify that. Use a range-for loop instead for (bool b : Verification) { std::cout << std::boolalpha << b; }
70,201,241
70,201,665
C++ dynamic_cast dowcast fails
While writing my first big project in C++, I encountered a problem which I wasn´t able to solve using google and documentation alone. I cannot figure out, why this dynamic_cast fails, even though r is pointing to a MeshRenderer Object. for (RenderEventConsumer* r : d->getConsumers()) { glUseProgram(mPickingShader-...
Thanks to Kaldrr. The solution was to derive publicly from RenderEventConsumer. class GameObject : public TickEventConsumer, public RenderEventConsumer, public PhysicsTickEventConsumer {...}
70,201,258
70,362,140
SURF and Matching with Undistorted Image OpenCV C++
i'm working on OpenCV 4 in ROS Melodic. After undistort(), images have a black background that is detected by SURF. How can I fix this?
I found solution thanks to Micka's comment. I filtered featurs during lowe ratio test: //-- Filter matches using the Lowe's ratio test //Default ratio_thresh: 0.7f; vector<DMatch> matches; size_t i = 0; bool lowe_condition = false; bool black_background_condition = false; //Filter matches in black background for (i; ...
70,201,383
70,201,662
Get array index from pointer difference in c or c++
I know how to get a pointer from a pointer and adding a index. But is it possible to get the index of a array if you only have a pointer to the array beginning and a pointer to one element element? #include <iostream> #include <array> auto pointer_from_diff(auto *x, auto *y) -> auto { return // ? what here? } auto...
&x[k] is the same as &x[0] + k. Thus, p - &x[0] is &x[0] + 2 - &x[0], which is 2.
70,201,710
70,201,895
How to hide functions in C++ header files
I am writing a header-only template library in C++. I want to able to write some helper functions inside that header file that will not be visible from a cpp file that includes this header library. Any tips on how to do this? I know static keyword can be used in cpp files to limit visibility to that one translation uni...
There isn't really a way. The convention is to use a namespace for definitions that are not meant to be public. Typical names for this namespace are detail, meaning implementation details, or internal meaning internal to your library. And as mentioned in comments, C++20 modules changes this situation.
70,201,889
70,202,138
equality comparison of two std::unordered_map fails
How to check for equality of two std::unordered_map using std::equal to check if both containers have same keys and their corresponding key values. Below my code prints unequal even though both containers have same size, set of keys and the corresponding key values are equal. #include <iostream> #include <unordered_map...
https://en.cppreference.com/w/cpp/algorithm/equal Two ranges are considered equal if they have the same number of elements and, for every iterator i in the range [first1,last1), *i equals *(first2 + (i - first1)). Consider this code added to your code snippet: for (auto it : um1) std::cout << it.first << ": " << ...
70,201,949
70,203,551
How to initialize array of objects with user defined values and take input from user?
#include <iostream> using namespace std; class car{ string owner; string car_num; string issue_date; car(string o, string cn, string id) { owner = o; car_num = cn; issue_date = id; } void getInfo() { cout << "Car's Owner's Name : " << owner << endl; cout << "Cars' Number : " << car_num << endl;...
car c1[n]; //incomplete code due to the issue In fact, you have 2 issues here: Variable-Length Arrays (VLA) are not allowed in standard C++. They are optionally allowed in standard C, and are supported by some C++ compilers as an extension. You can't have an array of objects w/o default constructor (unless you fully...
70,202,069
70,202,546
CMakeLists.txt's generated makefile works on MacOs but not on linux due to "no option -Wunused-command-line-argument" error
I'm using the following CMakeLists.txt to generate the Makefile to compile a library I'm writing: cmake_minimum_required(VERSION 3.10) # set the project name and version project(PCA VERSION 0.1 DESCRIPTION "framework for building Cellular Automata" LANGUAGES CXX) # specify the C++ sta...
As Ubuntu uses gcc, it doesn't seem to support unused-command-line-argument warning: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html So you should update your CMakeLists.txt with: if (NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU") add_compile_options(-Wno-error=unused-command-line-argument) endif()
70,202,336
70,202,562
How to compare sum of two int64 with INT64_MAX?
I know number greater than INT64_MAX will wrap around negative, So how to compare when sum overflow, that is sum greater than INT64_MAX. #include <iostream> using namespace std; int main() { int64_t a = INT64_MAX; int64_t b = 1; // cin >> a >> b; if (a + b <= INT64_MAX) { cout << "Yes" << endl; } else ...
First compare b to either INT64_MIN - a or INT64_MAX - a before the addition to prevent undefined behavior (UB) of signed integer overflow. // True when sum overflows. bool is_undefined_add64(int64_t a, int64_t b) { return (a < 0) ? (b < INT64_MIN - a) : (b > INT64_MAX - a); } Worst case: 2 compares. For div, mul, s...
70,202,832
70,203,119
Is it possible to deprecate implicit conversion while allowing explicit conversion?
Suppose I have a simple Duration class: class Duration { int seconds; public: Duration(int t_seconds) : seconds(t_seconds) { } }; int main() { Duration t(30); t = 60; } And I decide that I don't like being able to implicitly convert from int to Duration. I can make the constructor explicit: class Dura...
You can turn Duration(int t_seconds) into a template function that can accept an int and set it to deprecated. #include<concepts> class Duration { int seconds; public: template<std::same_as<int> T> [[deprecated("uses implicit conversion")]] Duration(T t_seconds) : Duration(t_seconds) { } explicit Duration...
70,202,840
70,203,580
function for solving 0/1 knapsack problem using Brute-force recursive solution
I am trying this code for solving 0/1 knapsack problem using Brute-force recursive solution, but it keeps running with no output at all when I make the size of the problem(profit and weight arrays) 100. if any one can tell me why? and how to solve it. Please if any one can tell me when to find trusted pseudocodes and c...
Setting the size to 100 just makes it take too long. Exponential running times are no joke. I have no idea if your code is correct but just looking at it I can see that the only arguments to the recursive call that ever change are capacity and currentIndex so it is easy to apply memoization in your code, which will be ...
70,203,998
70,205,058
Why doesn't CMake add the "GENERATED" property to file created by "configure_file"?
The CMake configure_file command can be used to create concrete files from templates. Calling configure_file(foo.h.in foo.h) will generate the foo.h file which did not existed prior to running cmake. Yet, it's not marked with the GENERATED property. Calling get_source_file_property(is_generated foo.h GENERATED) returns...
According to documentation, the purpose of a source file's property GENERATED is to prevent checking of the file during configuration process: This information is then used to exempt the file from any existence or validity checks. E.g. add_executable command could emit an error if one of its source files does not exi...
70,204,442
70,210,898
Does C++11 sequential consistency memory order forbid store buffer litmus test?
Consider the store buffer litmus test with SC atomics: // Initial std::atomic<int> x(0), y(0); // Thread 1 // Thread 2 x.store(1); y.store(1); auto r1 = y.load(); auto r2 = x.load(); Can this program end with both r1 and r2 being zero? I can't see how this result is forbidden by the description ...
That cppreference summary of SC is too weak, and indeed isn't strong enough to forbid this reordering. What it says looks to me only as strong as x86-TSO (acq_rel plus no IRIW reordering, i.e a total store order that all reader threads can agree on). ISO C++ actually guarantees that there's a total order of all SC oper...
70,204,806
70,218,140
Singleton pattern with gtk3 and gtkmm
I'm working on a gui app with cpp and gtkmm3. In this app, some widgets require the singleton pattern to implement such as window (because i want just one window in all over the app) this is my header file: class MyWindow : public Gtk::ApplicationWindow { public: MyWindow(BaseObjectType *pWindow, Glib::RefPtr<Gtk:...
The major problem with the Singleton design pattern is that it gives you: a single instance AND global access. The single instance aspect of the singleton is what people usually are looking for (like in your case), but not global access. The usual "alternative" to this is to declare a MyWindow instance and then injec...
70,205,358
70,370,989
How to use llvm toolchain on Linux always by default
I'm trying to build linux docker image, that will use clang and llvm libs (compiler-rt, libunwind, libc++, ...) for build always by default. I've seen this question, but it uses CMake variables. I want to not have to make any edits to the projects themselves, so that llvm is always used by default. How can I achieve th...
You have to build llvm with special flags (full info): -DLIBCXX_USE_COMPILER_RT=YES # compiler-rt in libc++ -DLIBCXXABI_USE_LLVM_UNWINDER=YES # libunwind in libc++ -DCLANG_DEFAULT_CXX_STDLIB=libc++ # libc++ as std lib in clang by default -DCLANG_DEFAULT_RTLIB=compiler-rt # compiler-rt in clang by default And upda...
70,205,452
70,205,591
concepts return type requirement syntax two versus one template parm
I am wondering how the std::same_as is defined and how we use it in a concept or requirement. Example: void f1() { } bool f2() { return true; } template < typename T> void Do( T func ) { if constexpr ( requires { { func() } -> std::same_as<bool>; } ) { std::cout << "Func returns bool " << std::end...
A concept is generally similar to a constexpr inline bool variable template. However, it does have special properties. With regard to this question, a concept whose first template parameter is a type is a special kind of concept: a "type concept". In certain locations, a type concept can be used without its first templ...
70,205,523
70,219,550
C++: Is there a more elegant solution to this (multiple dispatch) runtime polymorphism?
The main problem is simple, really. Given a base (more abstract) class and multiple derived ones that need to interact with each other, how do you go about doing it? To give a more concrete example, here is an implementation with hitboxes for a 2d videogame: #include <stdio.h> #include <vector> #include "Header.h" b...
Here is a simplified example (untested) of the classical double dispatch. struct Circle; struct Rectangle; struct Shape { virtual bool intersect (const Shape&) const = 0; virtual bool intersectWith (const Circle&) const = 0; virtual bool intersectWith (const Rectangle&) const = 0; }; struct Circle : Shape { b...
70,205,568
70,205,792
Working with hooks (SetWindowsHookEX & WH_GETMESSAGE)
I'll start with a description of what exactly I need and why. I am making an in-game interface in a library (dll), and I need the ability to both receive and delete messages (prevent the target process from receiving them), depending on different conditions in the code. In addition to messages from the mouse and keyboa...
I decided to go the first way and put the WH_GETMESSAGE hook on the messages of the thread that created the window. However, my attempts to block the message were unsuccessful. Per the documentation, a WH_GETESSAGE hook cannot block a message, only view/modify it. When the hook exits, the message is always delivered...
70,205,692
70,207,672
Generalization of tree creation
I want to generalize this binary tree creation process in order to let different types of nodes to be included in the tree itself. For example, I want to let the user choose if he wants to build a tree with the structure city (as I did below) or with the structure people or any structure he wants to define in the sourc...
Most of the pieces are already there. The first step you can do is to simply change the signature of insertNewNode and visualizeInOrder to accept node<T> instead of node<city>. So insertNewNode would become: template<typename T> void insertNewNode(node<T>* root, node<T>* leaf) { if (root) { if (leaf->i...
70,206,156
70,206,810
How sizeof a not-polymorphic C++ class can be larger than the summed sizeof of its members?
In the following example struct E inherits structs C and D and has no other data members: struct A{}; struct B{}; struct C : A, B {}; struct D : A, B {}; struct E : C, D {}; int main() { static_assert(sizeof(C) == 1); static_assert(sizeof(D) == 1); //static_assert(sizeof(E) == 2); // in Clang and GCC s...
First, it can be larger than the sum of sub-objects due to padding and alignment. However, you're probably aware of that, and that's not what you are asking. To determine the layout in your case, you can print the offsets of all the sub-objects (and the sizes of their types) using the following code: static E x; int ma...
70,206,310
70,235,659
c++ overloading global delete is not working on VSCode c/c++ extension
I'm working on a school project about overloading the global new/delete, and was having problems with the default operator delete being called instead of my overloaded version. Originally I thought it was a problem with my code, but I installed Dev-C++ and the overloaded operator was called successfully. This is the co...
After some experimenting, I've concluded that there is a bug in the VSCode c/c++ extension. I installed visual studio and ran the code there, and it worked fine. I also spoke with a classmate using the c/c++ extension, and she was having the same problem I was. Now that we have both switched, the problem has disappeare...
70,206,386
70,206,929
Best way to handle handle input for money
So I'am making a basic banking program in c++ and have a deposit function that accepts a double, so i want to handle input from the user for a double that is valid as money so to 2 decimal places and not less than 0. What is the best way to go about this? I have this so far, is there anything else I need to check for m...
You should never use doubles or floats to store these types of information. The reason is that floats and doubles are not as accurate as they seem. This is how 0.1 looks in binary: >>> 0.1 0.0001100110011001100110011001100110011001100110011... This is an example how 0.1 is stored in a float. It is caused by cutting o...
70,206,640
70,206,884
Determine which window the message was sent (SetWindowsHookEx & WH_KEYBOARD)
I need to be able to determine which window the message is intended for, but I don’t understand how to do it correctly. In WH_MOUSE has a special structure (MOUSEHOOKSTRUCT) that stores the hwnd of the window, but where to get the hwnd in WH_KEYBOARD? LRESULT CALLBACK messageHandler(int nCode, WPARAM wParam, LPARAM lPa...
At the time a keyboard action is generated, the OS doesn't know yet which window will eventually receive the message. That is why the WH_KEYBOARD hook doesn't provide a target HWND, like a WH_MOUSE hook does (since a mouse message carries window-related coordinates). When a keyboard message is being routed to a target...
70,207,015
70,207,177
Doubly Linked List Bubble Sort
My project is a bubble sort system for doubly linked list. I am trying to sort elements of doubly linked list (which are objects) by Date. I used pointer-based sort because I do not want to change the data of pointers. The problem is my code can (I think efficiently) sort the linked list. But in the end, when I try to ...
The problem is that when you swap the head pointer, you don't update head to refer to the new head node. One way to address this is after you do the swap, you should check to see if the head pointer should be updated. temp = swap(employee1,employee2); if (employee1 == head) head = temp; Alternatively, in swap, if ...
70,207,300
70,207,329
C++ - How to cout the person with the highest score in a program
I'm working on a program that allows the user to input some names and integers for a soccer game, ie input the player's name, jersey number, & points scored, and then prints it all at the end. How would I go about finding the player's name who scored the most points, and print that? This is my incomplete code below: vo...
You need to track the index of the highest player in the array, not just the highest points. In your cout statement, you are using the highest points as if it were an index, which it is not. Try this instead: void showHighest(Player p[], int size) { int highest_points = 0; int highest_index = -1; for (int...
70,207,558
70,207,685
Is there a way to refactore this code and make it work?
I'm trying to create a function and link it to a header file and call the function to my main.cpp. This is the code from one function which I'll be calling in my main.cpp file. I'm trying to create a sort function that determines whether the integers in the file are sorted in order or not. The file I'll be reading from...
Here is a code fragment that checks if numbers in a file are sorted, ascending: std::ifstream resultant("A"); int previous_number; int number; resultant >> previous_number; bool is_sorted = true; while (resultant >> number) { if (number < previous_number) { std::cout << "File not sorted\n"; is_s...
70,207,749
70,208,133
Why the second program performs worse, even though it should have considerably less cache misses?
Consider the following programs: #include <stdio.h> #include <stdlib.h> typedef unsigned long long u64; int program_1(u64* a, u64* b) { const u64 lim = 50l * 1000l * 1000l; // Reads arrays u64 sum = 0; for (u64 i = 0; i < lim * 100; ++i) { sum += a[i % lim]; sum += b[i % lim]; } printf("%llu\n", ...
I'd expect that: a) while the CPU is waiting for data to be fetched into L1 for the sum += a[i % lim]; it can ask for data to be fetched for the sum += b[i % lim]; into L1. Essentially; Program 1 is waiting for 2 cache misses in parallel while Program 2 is waiting for 1 cache miss at a time and could be up to twice as ...
70,207,898
70,207,924
Inline function with one of two parameters as constexpr
Assume I have a function with two parameters where first parameter is dynamic but second parameter is always constant known at compile time: uint8_t convert_bcd(uint8_t num, uint8_t mask) { uint8_t result = mask & 0x0F & num; if constexpr ((mask & 0xF0) != 0) // mask is known at compile time, can be optimized ...
Write a template. template<uint8_t mask> uint8_t convert_bcd(uint8_t num) { uint8_t result = mask & 0x0F & num; if constexpr ((mask & 0xF0) != 0) result += 10 * ((mask & 0xF0 & num) >> 4); return result; } uint8_t result1 = convert_bcd<0x7F>(data[0]); uint8_t result2 = convert_bcd<0x3F>(data[1])...
70,207,963
70,208,096
Restricting a range or similar concept to only accept a given type
I would like to declare a function akin to the following: string concat(const range<string> auto& strings); I have achieved the same via the following: template <template <typename> typename T> requires range<T<string>> string concat(const T<string>& strings); But this is too hefty and repetitious for me to consider ...
Maybe something like this: template <class R, class T> concept range_of = std::ranges::range<R> && std::same_as<std::ranges::range_value_t<R>, T>; static_assert(range_of<std::vector<int>, int>); static_assert(range_of<decltype(std::declval<std::vector<int>&>() | ...
70,208,047
70,208,064
returntype depending on template argument type
So I'm trying to write an algorithmic derivator, to derivate/evaluate simple polynomials. My Expression Logic is as follows: there are Constants and Variables, combined in to either a multiply or add Expression. In my Expression Class i have the method derivative which should return different Expressions depending whet...
auto derivative() { if constexpr (op == Ad) return l_.derivative() + r_.derivative(); else if constexpr (op == Multiply) return l_.derivative() * r_ + l_ * r_.derivative(); } The if constexpr is required if the branches deduce to different types.
70,208,485
70,208,620
How to prevent CMake from double compiling sources when bundling static C++ libraries?
I'm trying to build a static library libbar with CMake. libbar should contain libfoo, i.e. all object files from subdirectory target libfoo should appear in libbar as well. The simplest dir tree is as follows: bar ├── bar.cpp ├── CMakeLists.txt └── foo ├── CMakeLists.txt └── foo.cpp Here is foo/CMakeLists.txt:...
target_sources(foo PUBLIC foo.cpp) This line forces targets that link to foo to include foo.cpp among their sources. What is the correct way to build libbar containing libfoo without double compilation? You have explicitly asked for this, so just... don't: target_sources(foo PRIVATE foo.cpp) PUBLIC means "apply t...
70,208,655
70,208,753
Keyboard interrupt adding numbers to terminal before closing
C++ newbie coming from python. When I compile and run the following code, then press Ctrl+C before inputting anything, I see the terminal still prints You entered 0^C. #include <iostream> int main() { int num1; std::cin >> num1; std::cout << "You entered " << num1 << "\n"; } First of all, coming from Pyth...
num1 is not initialized, which means it contains whatever random value was in memory. When control-c is pressed, std::cin >> num1; fails. Then next line will print some random value that was in num1 earlier. The correct version should be int num1 = 0; if (std::cin >> num1) std::cout << "You entered " << num1 << "\n...
70,208,706
70,208,995
Smallest Binary String not Contained in Another String
The question description is relatively simple, an example is given input: 10100011 output: 110 I have tried using BFS but I don't think this is an efficient enough solution (maybe some sort of bitmap + sliding window solution?) string IntToString(int a) { ostringstream temp; temp << a; return temp.str(); }...
You can do this pretty easily in O(N) time. Let W = ceiling(log2(N+1)), where N is the length of the input string S. There are 2W possible strings of length W. S must have less than N of them as substrings, and that's less than 2W, so at least one string of length W must not be present in S. W is also less than the nu...
70,208,707
70,208,838
Why can't the global variable delta be used in method of class?
I'm a beginner of C++. In this sample, I want to use the global variable delta in method update_v() of class neuron. But it can't be used. Could you tell me why if you know? #include<iostream> #include<cmath> using namespace std; unsigned long nextt=1; long clock=0; long delta=0; class neuron{ public: do...
In void update_v(){, you do delta(0.04*pow(previous_v,2)+previous_v), so it makes the compiler thinks that you are calling a function named delta. But there's none, so it throws a error. It looks like you forget to use the * operator: void update_v(){ current_v = previous_v + delta * (0.04 * pow(previous_v,2) + pre...
70,208,728
70,210,226
memset of allocated memory after std::vector::reserve
There is a closely related question about this topic already here, but the question was highly contested and the related discussion was a bit confusing to me. So is the following thinking correct? My situation is the following: I have a data structure that uses chunks to store data. I want to preallocate a large number...
is it safe to 0-initialize the memory using memset after reserve? Maybe it works, but you'd better not. Accessing a nonexistent element through [] is UB. is it guaranteed that I still have 0-initialized memory in the example of ChunkT being struct {size_t keys[512]; size_t values[512];}; after fetching my chunk w...
70,208,952
70,208,972
C++ namespace "std" has no member "format" despite #include <format>
I am new to C++. I am trying to store the current date and time as a string variable. At this question, I found an answer, and installed the date.h library. However, when I try to use the code provided, I am met with the error: namespace "std" has no member "format" Despite having #include <format> at the top of the ...
std::format was added to C++ in the C++20 standard. Unless you compile with C++20, you won't have std::format.
70,209,072
70,209,103
Why did the output repeate again in some substring?
#include <iostream> #include <string> #include <algorithm> int main() { std::string s = "abcdefg"; int n = s.size(); for (int i = 0; i < n; i++) { for (int j = n; j > i; j--) { std::cout << s.substr(i,j) << std::endl; ...
The 2nd parameter of substr is supposed to be count, i.e. the length of the substring, so change std::cout << s.substr(i,j) << std::endl; to std::cout << s.substr(i,(j-i)) << std::endl; LIVE
70,209,349
70,209,360
Using a type without template arguments as a template argument
I have a class named Registry which correlates an ID with some data. I would like to make it so the underlying structure which stores these pairs can be any std::mapish type, of which the user can define (e.g.: std::map, std::unordered_map). My initial thought was to do something like this: template<typename Value, typ...
You need to declare Container as a template template parameter. E.g. template<typename Value, template <typename...> class Container, typename ID = size_t> class Registry{ using Storage = Container<ID, Value>; static_assert(std::is_same_v<Storage, std::map<ID, Value>> || std::is_same_v<Storage, std::unordered_...
70,209,568
70,209,586
C++ Canonical Project Structure, can't find headers
I'm fairly new to C++ and writing makefiles. I'm trying to compile a C++ project with the "canonical" structure described here with a makefile. I'm running into a problem where the compilation is failing because it can't find the headers due to using <brackets> instead of "quotes" when including the headers. How do I t...
Usually, you would use the -I option, followed by a relative or absolute path to the directory where the headers are. For example: gcc -c src/foo.c -o obj/foo.o -I src (However, compiler options are not part of the C++ standard, so it depends on what compiler you are using, and you did not say.)
70,209,613
70,223,553
Print elements of C++ string vector nicely in GDB
I want to view the content of std::vector<std::string> in GDB nicely I can view it with just like in this suggestion print *(myVector._M_impl._M_start)@myVector.size() But it prints out all stuff that is part of the C++ STL and it is a bit difficult to view the "actual" content of the strings Is there any way to view ...
Is there any way to view the elements nicely without displaying some part of the STL containers? You either have a very old GDB, or some non-standard setup. Here is what it looks like on a Fedora-34 system with default GDB installation: (gdb) list 1 #include <string> 2 #include <vector> 3 4 int main...
70,209,714
70,209,929
Why is my string extraction function using back referencing in regex not working as intended?
Extraction Function string extractStr(string str, string regExpStr) { regex regexp(regExpStr); smatch m; regex_search(str, m, regexp); string result = ""; for (string x : m) result = result + x; return result; } The Main Code #include <iostream> #include <regex> using namespace std; s...
Regexes in C++ don't work quite like "normal" regexes. Specialy when you are looking for multiple groups later. I also have some C++ tips in here (constness and references). #include <cassert> #include <iostream> #include <sstream> #include <regex> #include <string> // using namespace std; don't do this! // https://s...
70,209,879
70,210,191
Why is the last value in this specific example user input not being taken for my while loop?
I'm facing a bug where, after taking in the user input from a while loop, my code does not accept the last value. This bug happens on ONE specific example, and I have no clue why this is happening. So, for example, the user inputs: 7 3 1 4 0 0 2 0 The output is: 3140020 HOWEVER, with the following user input (this ...
The issue is not in cout << curr_inp; The issue is in loop which you used for(int i = 0; i< floor(n/2);i++ ) { vec[i]->left = vec[2*i+1]; vec[i]->right = vec[2*i+2]; } You are trying to call left and right with null vector After I added null check there is no segmentation fault for(int ...
70,209,887
70,218,029
Nothing renders in my QT application -- just a blank screen
I'm following the documentation for the WebEngineView in QT and I can't get this simple example to work. I've included an image of the layout for context. This all builds without errors, but when the form loads there's nothing there. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::Ma...
Turns out it wasn't a WebEngine problem at all, it was a problem of not being aware of some of the 'automagical' things that QT does behind the scenes. I renamed the centralwidget to root. Renaming it back to centralwidget fixed the problem. I could probably also have set the central widget in the constructor like so (...
70,210,827
70,216,076
Give two inputs to torch::jit::script::Module forward method
I am trying to build and train a network in python using pytorch . My forward method takes two inputs as follows : def forward(self, x1, x2): I trained this model in python and saved using torch.jit.script . Then I load this model in c++ using the torch::jit::load. How do I now pass the inputs to the model in c++ ? If...
The problem is by concatenating the two tensors and giving the concatenated tensor as input to the model. Then in the forward method, we can create two separate tensors using the concatenated tensor and use them separately for the output computation. For concatenation to work, I appended the tensors with 0's so that t...
70,211,035
70,211,400
multithreading gives different output sometimes
I am currently trying to get a better understanding of multithreading and am experimenting using std::thread. I have this piece of code: volatile int m = 0; void ThdFun(int i) { for (int j = 0; j < i; ++j) { m++; //std::cout << "hello1 " << m << " " <<std::endl; } //std::cout << "Hello World...
Your problem is the m++; line. What it really does, is something like this: Read m from memory into register Increment the register value Write the register value back to m The problem with your code is that the access to m is not synchronized between the threads, so it is possible for one thread to read m (step 1) a...
70,211,552
70,211,672
how do I run my code on cmd instead of vscode's internal terminal
everyone. I'm kind of new in this field. So bear with it. I'll try to be as specific as I can: let's say when I run a code(c++ file) in VScode it runs that code on VScode's internal terminal..like this => VScode but I want that code to run on my Window's CMD like "CodeBlocks" software. Like this => CodeBlocks but I don...
VSCode has a built-in terminal. That is why in the first case(first image in your question) you see the output as it is. If you don't want to use the built in terminal provided by VSCode then i suggest you open a standalone/separate terminal. And then cd into the project you want to build/compile and then compile the p...
70,211,681
70,211,706
How to provoke a compile-time error if a specific overload of a function is called?
According to https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view, std::basic_string_view class has 7 overloaded ctors. I only care about 2 of them since right now I don't use the rest of them in my code. These are the instances that I care about: constexpr basic_string_view( const CharT* s, siz...
Add another overload taking const char* and mark it as delete (since C++11). void func( const char* str ) = delete; LIVE
70,211,741
70,212,169
How to convert a large string number (uint256) into vector<unsigned char> in C++
I have a string number ranging in uint256, such as "115792089237316195423570985008687907853269984665640564039457584007913129639935". I want to store the bytes of this number into a vector<unsigned char>. That is, I want to get 0xffffff...fff (256bit) stored in the vector, where the vector's size will not be larger tha...
This Boost.Multiprecision-based solution worked for me well: std::string input { "115792089237316195423570985008687907853269984665640564039457584007913129639935" }; boost::multiprecision::uint256_t i { input }; std::stringstream ss; ss << std::hex << i; std::string s = ss.str(); std::cout << s << std::endl; std::vec...
70,211,995
70,212,010
using strcmp between string array and 2d array string
I need to search a word in 2d array an array that I enter but when Im using strcmp function, I have an error "No Matching function for call to 'strcmp' bool checkIfSameMedicine (char str1[], char str2[][MAXSIZE]) { for (int i = 0; i <= 3; i++) { if (strcmp(str2, str1)) { return true;...
You have to write at least for (int i = 0; i <= 3; i++) { if (strcmp(str2[i], str1) == 0) { return true; } } return false; Though the code looks not good due to using the magic number 3. The function should be declared and defined like bool checkIfSameMedicine( const char str2[][MAXSIZE]), size_t ...
70,212,028
70,214,627
Data structure for a crossword puzzle grid?
I'd like to design a crossword puzzle editor in C++. It is a grid of blocks, each block containing a letter (or being black between two words), possibly a number and a thick or thin border line. The block is therefore a container class for them. The grid is a container of blocks. But how would I structure the grid? A ...
By default, plain static/dynamic arrays (or their wrappers) are the most preferable: they are the most comfortable for both the programmer (random access API etc) and the processor (memory locality etc). The easiest-to-implement Block layout in an array/a vector is [first row Blocks..., second row Blocks..., etc] - a 1...
70,212,059
70,212,139
Compiler/linker complaining about function definition not found in C++
I've done this so many times, yet the reason why Visual Studio is complaining about this escapes me. Manipulator.cpp: #include "Manipulator.h" Manipulator::Manipulator() {} Manipulator::~Manipulator() {} void proc(std::string p, int f, std::string c) { // switch-case p to c based on f: return; } Manipula...
The compiler is correct in complaining, because the definition should be void Manipulator::proc(std::string p, int f, std::string c) { ... } You just defined a free function instead of a member of Manipulator.
70,212,283
70,215,057
Automated unit tests build and run on commandline with Visual Studio solution
I'm working on a project with multiple Unit Tests. I have a visual studio .sln file with around 10 XXPrj in it. Those projects are made with Google Test. Everything works well if I want to run them using Visual Studio 2019, I can build and run the unit tests. I would like to know what is the best way to run them an aut...
Build Building a Visual Studio solution/project through the command line is done with msbuild.exe. It works best to add the path of MSBuild to the PATH environment variable. MSBuild is usually installed somewhere in the Visual Studio folders. E.g. on my machine the path is as follows: C:\Program Files (x86)\Microsoft V...
70,212,364
70,213,446
compiler cannot recognize my class in c++ - cyclic dependency
having this base class: Core.hpp: #ifndef C3_CORE_HPP #define C3_CORE_HPP #include <c3/utils/Str.hpp> #include <c3/utils/Vec.hpp> #include <c3/school/Student.hpp> class Core { public: Core() = default; explicit Core(std::istream&in); virtual ~Core(); virtual double grade() const; const Str &getN...
As i said in the comment, the problem is due to cyclic dependency. In particular, your Student.hpp includes --> Grad.hpp which in turn includes --> Core.hpp which finally includes --> Student.hpp So as you can see from above, you ended up where you started, namely at Student.hpp. This is why it is called cyclic depende...
70,212,775
70,212,989
template non-type template parameters
Following is my code to register a free function or member function as callback. Find code here https://cppinsights.io/s/58dcf235 #include <stdio.h> #include <iostream> #include <functional> #include <vector> using namespace std; class IEvent { public: int m_EventType; virtual ~IEvent() {} }; template<cl...
Your base declaration does not match your specialization. The base implementation has template <class...Args> while the specialzation wants template <int eventType, class...Args>. You also put an extra int that does not belong there in the declaration for the specialization here: template<int eventType,class...Args> cl...
70,213,317
70,213,660
Why does std::forward not work in the lambda body?
#include <utility> void f(auto const& fn1) { { auto fn2 = std::forward<decltype(fn1)>(fn1); auto fn3 = std::forward<decltype(fn2)>(fn2); // ok fn3(); } [fn2 = std::forward<decltype(fn1)>(fn1)] { auto const fn3 = fn2; auto fn4 = std::forward<decltype(fn3)>(fn3); ...
Clang is correct to reject it. decltype(fn2) gives the type of fn2, suppose the lambda closure type is T, then it'll be T. Function-call operator of the lambda is const-qualified, then std::forward<decltype(fn2)>(fn2) fails to be called. The template argument for std::forward is specified as T explicitly, then std::for...
70,213,785
70,213,886
Can I make a template function noinline or else force it to appear in the profiler?
I'm trying to profile with perf on Ubuntu 20.04, but the problem is that many functions do not appear in it (likely because they are inlined), or only their addresses appear (without names etc.). I'm using CMake's RelWithDebInfo build. But there are some template functions that I don't know how to bring to the profiler...
You could add -fno-inline to CMAKE_CXX_FLAGS. From GCC man page: -fno-inline Do not expand any functions inline apart from those marked with the "always_inline" attribute. This is the default when not optimizing. Single functions can be exempted from inlining by marking them with the "n...
70,214,133
70,216,826
libcurl - CURLOPT_TCP_KEEPIDLE and CURLOPT_TCP_KEEPINTVL
Please tell me what is the difference between the parameters: CURLOPT_TCP_KEEPIDLE and CURLOPT_TCP_KEEPINTVL ? CURLOPT_TCP_KEEPIDLE: Sets the delay, in seconds, that the operating system will wait while the connection is idle before sending keepalive probes. Not all operating systems support this option. CURLOPT_TCP...
TCP keep alive sends "keep alive" probes (small IP packages) between both endpoints. If no data has been transferred over the TCP connection for a certain period, the TCP endpoint will send a keep alive probe. This period is CURLOPT_TCP_KEEPIDLE. If the other endpoint is still connected, the other endpoint will reply t...
70,214,268
70,214,280
How to include multiple variables in max() function?
I have this simple but long code that outputs the electron arrangement when user inputs the atomic number of wanted element. #include<iostream> using namespace std; int main() { int n, s1, s2, p2, s3, p3, s4, d3, p4, s5, d4, p5, s6, f4, d5, p6, s7, f5, d6, p7; cout << "Atomic number: "; cin >> n; ...
You can use std::max with an initializer list: auto max_value = std::max({x, y, z}); Note that the elements will be copied into the initializer list and the function will return a copy of the element with the largest value. This can become important if you use large objects (that are expensive to copy) and if time is ...
70,214,360
70,223,000
How to programmatically go to the next screen in the MSI installer from a custom action?
I have a WiX custom dialog ConfigDlg with my own controls in it: <Fragment> <UI Id="My_WixUI_Mondo"> <Publish Dialog="ConfigDlg" Control="Back" Event="NewDialog" Value="CustomizeDlg">1</Publish> <Publish Dialog="ConfigDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">1</Publish> <...
Controls can have multiple ControlEvents (publish elements) and they are processed in order. What you do is have the custom action called first and have it set a SomeProperty to null or 1 then have two mutually exclusive events. publish DoAction CustomActionName Condition 1 (true/always) publish SpawnDialog CustomB...
70,214,523
70,426,953
Confusing output when updating a Texture2D (Unity) with OpenCV VideoCapture (C++) and displaying with Sprite Renderer
Backgroud: similiar issue here and i use code segments from the answer. However, it does not fix the issue in my case. I have to add that i am a beginner in Unity programming ! Goal: receive a video livestream through a opencv c++ script and access it from a unity script to display in a scene. Approach to display the l...
adding this code does the job (the code is taken from Programmer here): Mat resizedMat(height, width, _currentFrame.type()); resize(_currentFrame, resizedMat, resizedMat.size()); Mat argb_img; cvtColor(resizedMat, argb_img, COLOR_RGB2BGRA); vector<Mat> bgra; split(argb_img, bgra); swap(bgra...
70,214,584
70,217,603
Can flatbuffers parse json given a generated type?
After using flatc to generate a type, can I parse a string of JSON into this type? In documentation, we can see This works similarly to how the command-line compiler works: a sequence of files parsed by the same Parser object allow later files to reference definitions in earlier files. Typically this means you first l...
No, you currently can't. There's no JSON parsing code in the generated code. Parsing the schema is really quick though, and you can reuse the Parser object that has parsed the schema for multiple JSON files.
70,214,857
70,216,306
Boost serialization base_object unspecialized template - why does it work?
I am trying to understand why this minimal example compiles: https://godbolt.org/z/xYeo53GPv template <typename T> struct Base { friend class boost::serialization::access; template <class ARCHIVE> void serialize(ARCHIVE& ar, const unsigned int /*version*/) {} }; struct Derived : public Base<int> { frie...
Indeed, it's not "unspecialized" but "unparameterized" which is actually okay because of a language feature. This mechanism is known as class name injection and is specified by the standard. Like @康桓瑋 mentioned, the Base can be used without the template arguments within the class declaration. For some background, see e...
70,215,530
70,215,602
How to call private member function by using a pointer
Rookie question: So there is this class class A { private: void error(void); public: void callError(void); }; And I would like to call error from callError using a pointer. I can achieve calling a public function from main using a pointer. int main(void) { void (A::*abc)(void) = &A::callError; A test;...
Add a public method to your class that returns a pointer to the private function: class A { private: void error(void); public: void callError(void); auto get_error_ptr() { return &A::error; } }; int main(void) { void (A::*abc)(void) = &A::callError; A test; (test.*abc)(); voi...
70,215,743
70,219,748
Convert C-Source image dump into original image
I have created with GIMP a C-Source image dump like the following: /* GIMP RGBA C-Source image dump (example.c) */ static const struct { guint width; guint height; guint bytes_per_pixel; /* 2:RGB16, 3:RGB, 4:RGBA */ guint8 pixel_data[304 * 98 * 2 + 1]; } example= { 304, 98, 2, "\206\061...
Updated Answer If you want to decode the RGB565 and write a NetPBM format PNM file without using ImageMagick, you can do this: #include <stdint.h> /* for uint8_t */ #include <stdio.h> /* for printf */ /* tell compiler what those GIMP types are */ typedef int guint; typedef uint8_t guint8; #include <YOURGIMPIMAGE...
70,215,918
70,217,574
Wrong probability - OpenCV image classification
I am trying to learn image classification using OpenCV and have started with this tutorial/guide https://learnopencv.com/deep-learning-with-opencvs-dnn-module-a-definitive-guide/ Just to test that everything works I downloaded the image code from the tutorial and everything work fine with no errors. I have used the exa...
quoting from here : From these, we are extracting the highest label index and storing it in label_id. However, these scores are not actually probability scores. We need to get the softmax probabilities to know with what probability the model predicts the highest-scoring label. In the Python code above, we are conver...
70,216,166
70,218,458
C++ How to override class field with a different type (without template)?
So I am trying to write a simple interpreter in c++, but ran into some problems. I have a Token class, which holds an enum TokenType, and a TokenValue object. The TokenValue class is the base class of several other classes (TV_String, TV_Int, and TV_Float). Here is the code for the TokenValue and its children classes: ...
What you are attempting to do will not work, because TokenValue is a base class and you are storing it by value in Token, so if you attempt to assign a TV_String object, a TV_Int object, etc to Token::value, you will slice that object, losing all info about the derived class type and its data fields. To work with polym...
70,217,301
70,217,446
What will happen if I cast a byte array to an __attribute__((packed, aligned(2))) struct?
I have some c++ code that defines a struct: struct IcmpHdr { uint8_t m_type; uint8_t m_code; uint16_t m_chksum; uint16_t m_id; uint16_t m_seq; } __attribute__((packed, aligned(2))) I understand that this struct will always be aligned on an address divisible by 2 when allocated because a padding byt...
Avoid pointer punning as it almost always breaks strict aliasing rules. Alignment of your structure does not matter as your byte array does not have to be 2 bytes aligned. Use memcpy IcmpHdr header; memcpy(&header, byte_array, sizeof(header)); If you use modern optimizing compiler it is very unlikely memcpy to be ca...
70,217,808
70,219,191
Finding float/double in a line of a file
Straight to the point, I have a task -> program asks for a price input, then, in the given csv file, it compares the input price to the csv file price (last value of the line). Then the program should print out the lines in which the price is the same as input or LOWER. Note, that the csv file is as it is, some lines a...
You can do this without std::vector as shown below: #include <iostream> #include <sstream> #include <fstream> int main() { std::ifstream inputFile("input.txt"); std::string word1,word2,word3,word4,word5; float price;//price take from user std::cin >> price; float priceFile; //price read f...
70,217,872
70,218,199
How to use the map::find() method for a nested map?
I have a map<int, map<int,int>> mymap; How do I use the find() method for nested maps like this? If I have map<int,int> mymap, mymap.find(key) it gives a result. But what about nested maps for more than 1 key?
Also note that there is std::map::at. It throws std::out_of_range if a matching key doesn't exists, but the usage in your case is simple. auto value = mymap.at(key1).at(key2); If you are not sure keys exists you can catch this exception or go with approach in Remy's answer.
70,218,324
70,225,168
How to draw a QStaticText with a mnemonic underline in Qt?
For a custom widget, there are tabs which ban be accessed with the ALT + <C> shortcut where <C> can be any keyboard character key. In Qt, this is called a Mnemonic For this shortcut, it is needed to have that letter underlined in the label. I can see that QPainter::drawText has an argument for flags, which can be prov...
There seems to be a QT-BUG for this, almost 10 years old (it was created in 2012). QStaticText doesn't support text-decoration css property. Properties like font-weight, color, font-style do have an effect but the text-decoration does not. See the attached example program where is HTML string using a element to under...
70,218,338
70,218,399
How do I access a struct value that is in a set?
I am learning to code in c++ and I am learning to use sets currently, with the code (I will not use the specific code because of the length but will use an example) it wants me to use a struct and a set and with the things that needs to be done I need to be able to ​access and edit a variable in said struct while itera...
std::set ensures it's elements are unique by having them in order. By default, that uses <. You don't have a < for myStruct, nor do you make a set with a different order. The simplest fix would be to add bool operator< (const myStruct & lhs, const myStruct & rhs) { return std::tie(lhs.testVal, lhs.exVal) < std::tie...
70,218,400
70,218,478
No operator "[ ]" matches these operands C++
const DayOfYearSet::DayOfYear DayOfYearSet::operator[](int index){ if(index < 0){ cout << "Error! Index cannot be negative.." << endl; exit(1); } if(index >= _size){ cout << "Error! Index overflows the array size.." << endl; exit(1)...
You are trying to use operator[] on const DayOfYearSet &other, but that function is defined to only work on objects that are not const. You should correctly const-qualify this function. const DayOfYearSet::DayOfYear DayOfYearSet::operator[](int index) const // This function can be used on const obje...
70,218,662
70,218,977
Are function propotypes obsolete in c++
I am looking at an old book and it contains function prototypes. For example: #include<iostream> using std::cout; int main() { int square(int); //function prototype for(int x = 0; x<=10; x++) { cout<<square(x)<<""; } int square(int y) { return y * y; } return 0; } How...
For starters defining a function within another function like this int main() { //... int square(int y) { return y * y; } return 0; } is not a standard C++ feature. You should define the function square outside main. If you will not declare the function square before the for loop int squar...
70,218,962
70,219,002
expression cant be called as a function : error
I am facing a compile time error here. I tried to find solution to the error but cant reach a conclusion. It says "expression cant be called as a function" when I am trying to return value using parenthesis in a user defined function. My code is: template <class t1> t1 sum(t1 a, t1 b) { if (a != b) { re...
3(a+b) means nothing for a C++ compiler. If you are trying to multiply, use 3*(a+b). If 3 is a function, change its name, you can't use a number as a function name.
70,218,986
70,220,496
Const correctness with a std::map
How much const should you apply to a std::map? // Given a custom structure, really any type though struct Foo { int data; }; // What's the difference between these declarations? const std::map<int, Foo> constMap; const std::map<const int, const Foo> moreConstMap; What are the tradeoffs or differences between const...
There is no difference in case of std::map aside of them being distinct types. As variables are declared const, the state of map class itself cannot be changed. Only member functions you can call upon it are const-qualified member functions, e.g. const_iterator find( const Key& key ) const; Both const-qualified fi...