question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
72,338,226
72,338,287
Creating alpha channel opencv
I have a program in c++ and opencv2 that loads an mp4 file and gives me frame pixels. I have a problem opencv outputs 24 bits per pixel, and I need 32 to display in a window on winapi. Is it possible to create an empty alpha channel using standard opencv tools?
You can use cv::cvtColor to convert a 3 channel RGB/BGR image to a 4 channel image with an additional alpha channel. As you can see in the documentation link above, the 3rd parameter specifies the required conversion. cv::Mat img24; // initialized somehow // ... cv::Mat img32; cv::cvtColor(img24, img32, CV_BGR2BGRA); ...
72,338,378
72,407,467
QPushButton Postion does not update its positon after window resize
I'm currently using QT 5.14.2 and QT Creator 4.11.1. In my current project I placed a QPushButton in the ui, then in the cpp file I set the window size to maxsize so it would use the whole screen with the close/rezise/minimize buttons available. In the program I simply created a function that would create a popup menu ...
So to get your QMainWindow positon the following code should be used : QPoint point(ui->centralwidget->mapToGlobal(ui->centralwidget->pos())); //Initialising QPoint x and y with mapToGlobal which will display for us the x y based on where our window is on the screen. point.setY(point.y() + ui->dropButton->heig...
72,338,665
72,338,769
Modify maps by reference in template class
Hey guys! I have school project to make. In the project I have to create a map_storage template class that's able to store/ know what maps it's going to modify and do different operations on them. The main.cpp file was already created for me, so that I can check if my code was correct. Template class: #include <map> #i...
We cannot have vector of lvalue references. You could instead store pointers inside the vector as shown below: template<class Key, class T, class Compare = std::less<Key> > class map_storage{ public: //------------------------------------v--------------->pointer void add(std::map<Key, T, Compare>* temp_map){ ...
72,338,833
72,338,919
Why can't I pass operator to a function from an other in C++?
In my C++ homework (where I have to short different arrays with different methods), I run into a problem. I can't pass comp() from one function to another. Here is a simplified version of my code: template <typename T, typename Compare = std::less<T>> void fooFunction(T arr[], int arraySize, Compare comp = Compare{}) {...
I changed two things: in your call to fooFunction2(..), don't pass comp() but comp. If you add parantheses, you execute the comp-function, which fails because a comparing function needs arguments passed to it. Just passing comp instead will just tell it where to look for the function in question. place the definition...
72,338,886
72,338,939
How to return a variable from a destructor
So I have a struct called timer which determines how much time did a block of code take to execute and complete and I'm going to run few benchmarks on my sorting algorithm and take the average value of time it took for each sorting algorithm. struct Example{ std::chrono::time_point<std::chrono::steady_clock> start,...
You can't return anything from the deststructor but you can assign the value to a variable that you supply to Example upon creation. Example: #include <chrono> #include <iostream> template <class Clock = std::chrono::steady_clock> struct Example { std::chrono::time_point<Clock> start; std::chrono::duration<flo...
72,339,157
72,339,280
How to approach this coding challenge?
Source Create a function that performs an even-odd transform to an array, n times. Each even-odd transformation: Adds two (+2) to each odd integer. Subtracts two (-2) from each even integer. Examples: evenOddTransform([3, 4, 9], 3) ➞ [9, -2, 15] // Since [3, 4, 9] => [5, 2, 11] => [7, 0, 13] => [9, -2, 15] evenOdd...
I suggest that you take a std::vector<int-type> by reference and do the transformation on that instead since array sizes need to be known at compile time. Example: #include <algorithm> #include <cstdint> #include <iostream> #include <vector> void evenOddTransform(std::vector<std::intmax_t>& vec, unsigned times) { ...
72,339,931
72,340,007
"multiple definition of" while variable is not defined anywhere else in the scope
I have these three source files: test.h #ifndef __TESTH #define __TESTH #ifdef __cplusplus #define EXTERNC extern "C" #else #define EXTERNC #endif typedef struct { uint8_t value; } my_struct; EXTERNC void initialise(); EXTERNC void load(my_struct**); #endif t...
I think you would need to scope test.cpp's test variable to that file only, assuming your test pointer in main.cpp is different than test in test.cpp namespace { my_struct test; } See here
72,340,339
72,340,510
How to pass a name for convenient use of tuple?
I would like to improve the code so that it is convenient to interact with it. struct prototype { template <class... T1> prototype(T1&&... args) { auto p = std::tie(args...); std::cout << std::get<0>(p) << std::endl; if constexpr(std::tuple_size_v<decltype(p)> >= 3) { std::cout << std::get<2>(p)...
You can create a variable template out of a lambda. At the end of the day all you want is a compile time constant to pass to std::get: template <std::size_t N> constexpr auto option = [] (auto p) -> auto&& { return std::get<N-1>(p); }; This can be used as option<1>(p) Demo The familiar template syntax for lambdas ma...
72,340,344
72,340,486
How to transform 2D tuple [x][y] to [y][x] and call variadic function for each result set
I want to "rotate" the axis of a 2D tuple and call a variadic function for each of the result sets. All tuple elements have the same type, but the element items/attributes might have different type. Starting from constexpr auto someData = std::make_tuple( std::make_tuple(1, 2, 3.0), std::make_tuple(4, 5, 6.0), ...
Use nested lambdas, one to expand the index and one to expand the tuple constexpr auto someData = std::make_tuple( std::make_tuple(1, 2, 3.0), std::make_tuple(4, 5, 6.0), std::make_tuple(7, 8, 9.0) ); // someFunction(1, 4, 7); // someFunction(2, 5, 8); // someFunction(3.0, 6.0, 9.0); std::apply([](auto first_tu...
72,340,706
72,349,736
Unable to get my software C++ glsl implementation to behave correctly
so, I am writing a couple of functions so to run GLSL fragment shaders on CPU. I implemented all the basic mathematical functions to do so. However I can't even get the simplest stuff to execute correctly. I was able to trace it down to either of these functions: template<unsigned vsize> _SHADERH_INLINE vec<float, vsiz...
There are few things that may be the origin of the problems. Failing dot function After a bit of testing, it turned out that your dot function fails, because you are providing an integer value 0 as initial value in your call to inner_product, which results in wrong calculations. See this post for the reason: Zero inner...
72,341,025
72,341,264
Why does this code behave differently on C-stdio function overloads? (vfprintf vs. putchar)
I'm trying to define various functions with the same name as C stdio to prevent unwanted usage. I encountered an odd situation where the technique works on some functions, but not others. I cannot explain why A::fn calls the stdio version of vfprintf instead of the function definition in the A namespace. #include <st...
Replacing standard library routines is UB (citation to follow). See examples here and here for the kind of trouble this can cause. Edit: OK, here's the promised citation: The C++ standard library reserves the following kinds of names: ... names with external linkage ... If a program declares or defines a name in a co...
72,341,040
72,341,076
why does the getline() function does not work unless I call it twice in the function charmodifier
what's wrong if I use the get line function only once in the character modifier function the compiler will ignore it unless I call the function twice why cant I use it only once? I tried using other ways, it worked but I wanna understand this one I'm now just writing random things so the add more details error message...
The problem is that after entering an integer or a character as for example cout << "episode No." << endl; cin >> e; cout << "enter the name of the show:" << endl; charmodifier(); //... the input buffer contains the new line character '\n' that corresponds to the pressed Enter key. So the following call of getline rea...
72,341,290
72,347,075
How can I clear console to the right of the cursor in Windows NT command prompt with C++?
I need an output on the same line, like this: std::cout << "\rIt's " << leisure << " time!"; I want to make sure I do not see stuff like time!e! at the end of the line if the next value of leisure is shorter. \t does not overwrite the symbols (if run from cmd), so I still see time!e!. \033[0K is a VT 100 escape sequen...
I wanted to avoid additional coding for a single line terminator, but since there is seemingly no other solution, I resorted to Console Virtual Terminal Sequences as suggested in the comments: #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <string> static const bool enabl...
72,341,483
72,342,952
How can I generate a C++23 stacktrace with GCC 12.1?
In the release notes for GCC12, under the section "Runtime Library (libstdc++)", it says: Improved experimental C++23 support, including: [...] <stacktrace> (not built by default, requires linking to an extra library). What library do I need to link against to use <stacktrace>? I'm on an x86 Linux system, if that mat...
You need to link with -lstdc++_libbacktrace (as now documented here). In order for this to work, gcc needs to have been configured with --enable-libstdcxx-backtrace.
72,341,710
72,341,746
How to make two Forms access the same variables in C++Builder
I have two Forms, both are including the same .cpp file that has these global variables: static vector<News> allNews; static vector<user> allUsers; static admin appAdmin("admin", "adminpassword"); static int userIndex =0; The problem is that, when Form A adds News objects to the vector, the second Form B seems to be ...
both are including the same .cpp - never include .cpp files. Make a .h file with the content: extern vector<News> allNews; extern vector<user> allUsers; extern admin appAdmin; extern int userIndex; And then update the .cpp file by removing static: vector<News> allNews; vector<user> allUsers; admin appAdmin("admin", "a...
72,341,945
72,342,154
How does a compiler store information about an array's size?
Recently I read on IsoCpp about how compiler known size of array created with new. The FAQ describes two ways of implementation, but so basically and without any internal information. I tried to find an implementation of these mechanisms in STL sources from Microsoft and GCC, but as I see, both of them just call the ma...
Here is where the compiler stores the size in the source code for GCC: https://github.com/gcc-mirror/gcc/blob/16e2427f50c208dfe07d07f18009969502c25dc8/gcc/cp/init.c#L3319-L3325 And the equivalent place in the source code for Clang: https://github.com/llvm/llvm-project/blob/c11051a4001c7f89e8655f1776a75110a562a45e/clang...
72,342,270
72,343,567
Limited space iterators
I've implemented a tree (not a binary tree, every node can have several child nodes). For every node, we can access its level in the tree, its children and its parent node. The next phase is to implement 2 iterators for this tree but the catch is I can not save more than a constant amount of information to help complet...
Here's a sketch of the algorithm. Very inefficient, but satisfies your requirement of only using O(1) additional space. Node* GoRight(Node* c) If c is root (there's no parent), return NULL Let p be the parent of c. Find its child r immediately to the right of c (may need to do a linear search of p's child links). If f...
72,342,288
72,342,461
How to create loops and use push_back()
I am trying to have the user choose how many names they would like to add, and then use push_back() to add that many to the list. I am new to programming and very confused. Here is the code I have so far: int main() { int numNames; std::cin >> numNames; vector<string> names; numNames = read_integer("How...
When using the std::vector there is no need to have the user enter the number of names beforehand. That is the benefit of having std::vector handle the memory management for you. You simply read and validate the input and .push_back() to the vector until the user is done. Using getline() for input allows you to read na...
72,342,528
72,344,316
Question about the type of `&"hello"` and `"hello"`
As per the output of this code snippet, the type of &"hello" is const char(*)[6], so char* ptr = &"hello"; is inlegal for char* and const char(*)[6] are different types. And since char* ptr1 = "hello"; compiles with C++11 and latter, the type of "hello" is char*? If the type of "hello" is char*, then &"hello" shouldn't...
"Hello" is a string literal of type const char [6] which decays to const char* due to type decay. Now let's see what is happening for each of the statements in you program. Case 1 Here we consider the statement: char* ptr = &"hello"; As i said, "hello" is of type const char [6]. So, applying the address of operator & ...
72,342,770
72,342,855
What to pass as a Sender in a button OnClick method?
I have a function that creates a button dynamically void createBtn(News obj,TForm *Form1){ TButton *spam = new TButton(Form1); spam->Parent = newsCard; spam->Position->X = 280; spam->Position->Y = 256; spam->Text = "Spam"; } I need to assign an OnClick event to it, so I added the following line to ...
Your second approach doesn't work, because you are trying to call spamClick() first and then assign its return value to the OnClick event. Your first approach is the correct way, however you can't add parameters to the OnClick event handler. TButton has Tag... properties for holding user-defined data. However, since th...
72,343,016
72,343,310
Why is flatbuffers output different from C + + in Python?
I use the same protocol files, but I find that they have different output in Python and C++. My protocol file: namespace serial.proto.api.login; table LoginReq { account:string; //账号 passwd:string; //密码 device:string; //设备信息 token:string; } table LoginRsp { account:string; //账号 passwd:string...
Flatbuffers generated by different implementations (i.e. generators) don't necessarily have the same binary layout, but can still be equivalent. It depends on how the implementation decide to write out the contents. So taking the hash of the binary is not going to tell you equivalence.
72,343,660
72,369,546
Semicolon(;) After Class Constructors or Destructors
I am currently maintaining and studying the language using a Legacy Source,I want to clear up some confusion on the use of semi-colons inside a class. Here is the bit where confusion strikes me. class Base { public: Base(int m_nVal = -1 ): nVal(m_nVal) {} // Confused here virtual ~Base() {} // Confused here public:...
does the Semi-colon after the constructors or destructor tells something specific to the compiler? After (or before) a member function definition it does not.† After (but not before) a member function declaration it is mandatory. 'Probably just an oversight. †: Unless the definition has no body: struct A { A() = d...
72,343,995
72,344,555
How is OpenMP communicating between threads with what should be a private variable?
I'm writing some code in C++ using OpenMP to parallelize some chunks. I run into some strange behavior that I can't quite explain. I've rewritten my code such that it replicates the issue minimally. First, here is a function I wrote that is to be run in a parallel region. void foo() { #pragma omp for for (int i...
From the documentation of omp parallel: Each thread in the team executes all statements within a parallel region except for work-sharing constructs. Emphasis mine. Since the omp for in foo is a work-sharing construct, it is only executed once per outer iteration, no matter how many threads run the parallel block in m...
72,344,637
72,344,841
Is there any point in returning an object (e.g., std::string) by reference when the method has no parameters?
Take the following snippet of code #include <iostream> #include <string> class Foo { private: std::string m_name; public: Foo(std::string name) : m_name { name } {} const std::string & get_name() const { return m_name; } }; int main() { Foo x { "bob" }; x.get_name(); } Beca...
Yes, there is a point, you return by reference if you want to return a reference to some object. Why would you want to have a reference to some object? Exactly because you need to access it and not a copy of it. Reasons might vary, basic ones are that you do not want to make an extra copy - e.g. the get_name you posted...
72,344,698
72,344,817
A compilation error occurs when using clang in a Windows environment
I compliation the code with Vscode. The clang -v: clang version 14.0.3 Target: x86_64-w64-windows-gnu Thread model: posix InstalledDir: C:/msys64/mingw64/bin You can see I get clang form msys. The file I compliate use such header file: #include <windows.h> #include <windowsx.h> #include <tchar.h> #include <d2d1.h> T...
clang-cpp is the Clang preprocessor, not the C++ compiler. You should use clang++ for the C++ compiler front-end program.
72,344,701
72,345,736
different behavior for different "for"s in benchmark
We can write a simple benchmark using google benchmark or https://www.quick-bench.com/, static void range_based_for(benchmark::State &state) { for (auto _ : state) { std::to_string(__LINE__); } } BENCHMARK(range_based_for); We can also rewrite it with std::for_each, static void std_for_each(benchmark::...
The begin/end functions are documented with a warning: says "These functions should not be called directly" These functions should not be called directly. REQUIRES: The benchmark has not started running yet. Neither begin nor end have been called previously. end calls StartKeepRunning And what does StartKeepRunning d...
72,345,326
72,345,969
Allocation free std::vector copy when using assignment operator
When having two instances of std::vector with a primitive data type, having same size and capacity, is there a guarantee that copying via the copy assignment operator will not re-allocate the target vector? Example: const int n = 3; std::vector<int> a, b; // ensure defined capacity a.reserve(n); b.reserve(n); // mak...
Standard doesn't guarantee that there would be no allocations. According to the C++11 Standard the effect of b = a; is as if b.assign(a.begin(), a.end()) (with surplus b's elements destroyed, if any) which result is "Replaces elements in b with a copy of [a.begin(), a.end())". Nothing about allocations but with the C++...
72,346,114
72,346,191
Are explicit template instantiation definition for a function template allowed in header files
I was reading about explicit template instantiation when i came across the following answer: Assuming by "explicit template instantiation" you mean something like template class Foo<int>; // explicit type instantiation // or template void Foo<int>(); // explicit function instantiation then these must go in s...
From explicit instantiation's documentation: An explicit instantiation definition forces instantiation of the class, struct, or union they refer to. It may appear in the program anywhere after the template definition, and for a given argument-list, is only allowed to appear once in the entire program, no diagnostic re...
72,346,416
72,346,567
Why does vector of same size takes more memory than array in leetcode
I'm trying to solve Ones and Zeros question from leetcode and for the same code but using vector occupies ~3x more memory than using array of same size. Here is my code that uses 3-D vector: int findMaxForm(vector<string>& strs, int m, int n) { int S = strs.size(); vector<vector<vector<int>>> dp(S+1, vector<vec...
An array (I assume you used plain C arrays) uses only as much memory as its elements. A vector uses some memory to store some housekeeping information like the length and location of the data. Because you made a vector of vector of vectors, this housekeeping information is created for all of the nested vectors, which o...
72,348,126
72,348,264
Getting device twin in C Sdk - Azure IoT Hub
Is there a way to get the device twin of a device from Azure IoT-Hub, using Azure SDK for C? As far as I know, I am able to get the device twin using the Azure SDK for NodeJS. In nodejs we do it like. const Client = require('azure-iot-device').Client; cosnt Protocol = require('azure-iot-device-mqtt').Mqtt; var client =...
Is there any way to get the twin data for a device and get twinchange notification in Azure SDK for C i.e A callback function when there is a change in twin data? Yes, you can refer to example of callback function as per Get updates on the device side: Try the following code snippet taken from the document: static vo...
72,348,293
72,358,779
Deletion in array implementation of queues reduces capacity?
In all queue array implementations I have seen, when they 'pop an element from front', they basically change the front tag of the queue to the next element. but then the capacity of the queue is technically reduced (since array is used). How hasn't this caused problems yet or how is this considered valid? Edit : https:...
You are right with your concern about the C++ implementation given in the article https://www.softwaretestinghelp.com/queue-in-cpp/. With that implementation, basically when you dequeue an element, the pointer to the "first" of the queue shift 1 unit to the right (in the underlying array), and that reduce the capacity ...
72,348,328
72,348,648
how to fix on devc++ collect2.exe [Error] ld returned 1 exit status
It tells me error id returned 1 exit status when I try to run the code and have search it up from what i have seen is that you mostly get this error from misspelling main() function but that is not the case here. #include <iostream> #include <string> using namespace std; int main(){ ...
One of the mistakes you've made is that you haven't properly declared or defined you're functions. If you want to take the declare then define approach, you'll want to move you're declaration to the global scope and out of the main() function. Also because they don't return anything they should be declared void: #i...
72,348,680
72,348,776
what is wrong with this template metaprogram to find square root?
I was trying to code the O(N) solution to find the square root of a perfect square number using template metaprogramming in C++. Algorithm: algorithm sqrt(N, start): if(start*start == N) return start else return sqrt(N, start+1) i.e: template<int value, int N> struct sqrt { enum {...
sqrt<X,N> instantiates sqrt<X+1,N> and that instantiates sqrt<X+2,N> etc. it never stops. Both branches are evaluated by the compiler, even if only one of them is taken. The compiler is not clever enough to see that the condition is false at some point and then sqrt<value+1,N> does not need to be instantiated. You have...
72,348,805
72,348,894
the difference of automatic and dynamic variables rules in zero initialization
code like this, #include <iostream> class obj { public: int v; }; int main(int argc, char *argv[]) { obj o1; std::cout << o1.v << std::endl; // print 32766, indeterminate values obj *o2 = new obj(); std::cout << o2->v << std::endl; // print 0,but why? int v1; std::cout << v1 << std::end...
obj *o2 = new obj(); is value initialization meaning the object will be zero initialized and hence the data member v will be initialized to 0. This can be seen from value initialization: This is the initialization performed when an object is constructed with an empty initializer. new T () (2) 2,6) when an objec...
72,349,768
72,705,236
Convert steady_clock::time_point (C++) to System::DateTime (C++/CLI)
I need to convert C++ std::chrono::steady_clock::time_point to C++/CLI System::DateTime. Background: I am wrapping a C++ library with a C++/CLI interface, to be used by a .NET app. One of the C++ methods return a std::chrono::steady_clock::time_point. I thought it is appropriate to returns a System::DateTime from the C...
The approach is sound, but the code can be made shorter and easier to read with a couple small changes: template<typename Rep, typename Period> System::TimeSpan DurationToTimeSpan(std::chrono::duration<Rep, Period> const& input) { auto milliSecs = std::chrono::duration_cast<std::chrono::milliseconds>...
72,350,046
72,366,408
How to work with 2 HCSR04 Arduino Component?
Any ideas for the code of working with 2 different ultrasonic sensors? The idea is when either one of the sensors detects an obj in front of the sensor, it automatically turns on a buzzer. But for now, I only use the 2 ultrasonic sensors. This is my code, doesnt work as expected: #define trigPin1 3 #define echoPin1 2 #...
A better way to approach this problem would be to make a function that returns the distance long. The code would look like this: long duration, distance, RightSensor,LeftSensor; void setup() { Serial.begin (9600); pinMode(trigPin1, OUTPUT); pinMode(echoPin1, INPUT); pinMode(trigPin2, OUTPUT); p...
72,350,127
72,350,215
Incompatible two void functions declaration
I have a problem about declaring two void functions in my template "Wallet" class, which are going to remove and add existing template class "CreditCard" to the vector. Compiler writes that "declaration is incompatible" #pragma once #include<iostream> #include<string> #include"CreditCard.h" #include<vector> using names...
The problem is that CreditCard is a class template which is different from a class-type. So we have to specify the template argument list to make it a type. To solve this you can specify the template arguments to CreditCard as shown below: template<class T> class Wallet { protected: vector<CreditCard<T>>cards; pub...
72,350,241
72,350,390
Im trying to sort a list of Cities and their Temperature using a bubblesort
Im fairly new to C++ and im trying to convert an int "city.temp[4]" to a string and then adding that to an already existing string "city.name[4]" which would then sort the cities and their temperatures based on low to high. The user is the one to name all four cities and assign them a temperature. The bubbleSort is wor...
The good solution is to have a City-class with a name and a temperature and swap cities based on the order of the temperature with std::sort. The easy fix for now is to use std::swap to swap the temperatures and at the same time swap the names: if(city.temp[j] > city.temp[j+1]){ std::swap(city.temp[j], city.temp[j...
72,350,951
72,351,086
Why are finding elements most efficient in arrays in c++?
I need a fast STL container for finding if an element exists in it, so I tested arrays, vectors, sets, and unordered sets. I thought that sets were optimized for finding elements, because of unique and ordered values, but the fastest for 10 million iterations are: arrays (0.3 secs) vectors (1.7 secs) unordered sets (1....
Please remember that in C and C++ there is the as if rule! This means compiler can transform code by any means (even by dropping code) as long as observable result of running code remains unchanged. Here is godbolt of your code. Now note what compiler did for if (find(a, a + 16, rand() % 64) == a + 16) {}: .L206: ...
72,351,233
72,351,348
Why is it advantageous to return by reference?
I know that the rule of thumb is that we return by reference iff the returned variable exists in the caller. Say we have a function: int& f(int& a){ return a; } Now, in the caller, I can call in 2 ways: int a = 5; int b1 = f(a); // 1 int& b2 = f(a); // 2 The difference is that change in b1 or a in the caller, doesn'...
Frankly your argument is moot. Along the same line of reasoning you could argue that there is no advantage of using a reference in general, because it can be used to make a copy: int x = 42; int& ref = x; int y = ref; // makes a copy However, just because you can use a reference to make a copy does not decrease us...
72,351,798
72,351,834
How to force set in c++ to store values in descending order?
I have been stuck on an algorithm that requires unique values sorted in descending order. Since the need is unique, I thought set is the best data structure to be used here, but I guess set by default stores the value in non-decreasing order, how do I make it store in non-increasing order? Other than the fact that I ca...
How about using std::set<int, std::greater<int>> mySet{}? By default it's using std::less if I recall correctly.
72,351,917
72,354,444
OpenMP. Parallelization of two consecutive cycles
I am studying OpenMP and have written an implementation of shaker sorting. There are 2 consecutive cycles here, and in order for them to be called sequentially, I added blockers in the form of omp_init_lock, omp_destroy_lock, but still the result is incorrect. Please tell me how you can parallelize two consecutive cycl...
You seem to have several misconceptions about how OpenMP works. Two parallel sections don't execute in parallel. This is fork-join parallelism. The parallel section itself is executed by multiple threads which then join back up at the end of the parallel section. Your code looks like you expected them to work like pr...
72,352,743
72,353,040
Z3 Prover: Equivalent to Python Datatype in the C++ API
Is there an equivalent to the Python Datatype() API for C++? For example in Python you can do: >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.nil nil >>> List.cons(10, List.nil) cons(10,...
Yes. In general, everything you can do from the Python API (and other APIs), you can do from C/C++. The function you're looking for is called Z3_mk_datatype. See: https://z3prover.github.io/api/html/group__capi.html#ga34875df69093aca24de67ae71542b1b0 for details. Note that the C/C++ APIs are much lower level, so while ...
72,353,536
72,356,119
C++ code compiled with cygwin needs cygwin1.dll to run
I have no special code to share to ask this, but I wrote a C++ code (which could even be a simple Hello World program) compiled to an exe file, requires the cygwin1.dll available either via %path% or in the same folder as the exe to run (for runtime). If it were libstdc++-6.dll needed I could have done something like u...
As discussed in comments, the native gcc inside Cygwin targets Cygwin. You want the GCC targeting mingw32 not the one targeting Cygwin. While you can install that GCC inside Cygwin as a cross compiler, the native GCC from MSYS works just fine and I too would recommend that. Note that if you need a library that isn't av...
72,353,673
72,353,754
How to add variable to derived initialization list from base class initialization list?
I have a base class ShowTicket with parameterized constructor: //constructor ShowTicket(const char* Row, const char* SeatNumber): sold_status{false}, row(Row), seat_number(SeatNumber) {} I am creating a derived class, SportTicket that will take the same parameters as ShowTic...
The constructor of the class ShowTicket itself initializes its data member sold_status to false //constructor ShowTicket(const char* Row, const char* SeatNumber): sold_status{false}, row(Row), seat_number(SeatNumber) {} So in the derived class just remove the line sold_status{false} because it is ...
72,353,688
72,354,047
Iterator for Matrix Native class class
I wrote my own Matrix class with such fields (you can't use STL containers in it) template <typename T> class Matrix { private: T *data = nullptr; size_t rows; size_t cols; I also made an iterator for this class: public: class Iterator { friend Matrix; private: ...
I suggest that you let the iterator take a T* as argument. You can then supply data to the begin() iterator and data + rows * cols to the end() iterator. Example: template <class T> class Matrix { private: T* data = nullptr; size_t rows; size_t cols; public: Matrix(size_t Rows, size_t Cols) : d...
72,354,043
72,362,447
How to pass python lambda func to c++ std::function<> using Boost.Python
Just lets consider next example: #include <functional> class Model { function<bool(const vector<double>&, float, float, float)> q_bifurcate_pointer; } Now in c++ env I can simply assign lambda value to q_bifurcate_pointer: model.q_bifurcate_pointer = [](const vector<double>& a, float branch_lenght, float bifurca...
Lambda expression in pythone - this is byte code and C++ needs machine code. Just googled similar to mine but more general problem here: https://stackoverflow.com/a/30445958/4437603
72,354,800
72,379,101
Malloc error when trying to run node js server due to ibm_db module
I have a nodejs application, and configured to run on port 5001. When I try to run the node server using node server.js, it throws me an malloc error like below node(6080,0x1067aa600) malloc: *** error for object 0x7ffb503d2670: pointer being freed was not allocated node(6080,0x1067aa600) malloc: *** set a breakpoint i...
The issue was not related with X code or node version but it was related to one the npm package I was using which was ibm_db and only if you have the mac monterey os. Follow these step if you have this package installed to rectify the error. Delete ibm_db package from your project and delete package-lock.json as well....
72,355,184
72,355,211
Parallel version of the `std::generate` performs worse than the sequential one
I'm trying to parallelize some old code using the Execution Policy from the C++ 17. My sample code is below: #include <cstdlib> #include <chrono> #include <iostream> #include <algorithm> #include <execution> #include <vector> using Clock = std::chrono::high_resolution_clock; using Duration = std::chrono::duration<doub...
The thread-safety of rand is implementation-defined. Which means either: Your code is wrong in the parallel case, or It's effectively serial, with a highly contended lock, which would dramatically increase the overhead in the parallel case and get incredibly poor performance. Based on your results, I'm guessing #2 ap...
72,355,376
72,355,530
Plus sign "+" before wchar_t variable
I have found on the cpp reference website (link) the following code which I do not understend completely: void try_widen(const std::ctype<wchar_t>& f, char c) { wchar_t w = f.widen(c); std::cout << "The single-byte character " << +(unsigned char)c << " widens to " << +w << '\n'; } What I do not u...
Like all arithmetic operations, unary plus triggers integer promotion of its operand. This results in printing a numerical value of a character. Without it, a different overload of operator << could be chosen. << (unsigned char)c would print a character rather than a number. I believe std::cout << w would not compile.
72,355,415
72,355,497
How to set BaseClass variable from DerivedClass parameter
I have the classes Player and HumanPlayer. HumanPlayer is derived from Player. class Player { private: int id; protected: string name; public: Player(int id); ~Player(); } class HumanPlayer : public Player { public: HumanPlayer(int id, string name); } I want to make a constructor for HumanPlayer t...
For your understanding. class Player { private: int id; protected: std::string name; public: //Base class constructor, initialize Id. Player(int i):id(i) {} ~Player() {} //Test int GetId() { return id; } std::string GetName() { return name; } }; c...
72,355,450
73,317,668
Object generation from different id types slow compilation
I have a of templated class that can generate an object instance from an ID. The context is networking code with object replication. The code below shows a way that I can manage to do this, but it has the drawback of beeing very slow in compilation. Does anyone know a "better" way to achieve what my example shows. I'm ...
Basic solution Bring all the bases into scope via using: // a helper to avoid copy pasting `using`s template<typename... Registers> struct MultiRegister : Registers... { using Registers::create...; }; class MyRegisters : public MultiRegister< Register<ID_A, ABase>, Register<ID_B, BBase>, Register<ID_C, CBa...
72,355,478
72,357,013
Global Constants in .h included in multiple c++ project
I want to run a small simulation in c++. To keep everything nice and readable I seperate each thing (like all the sdl stuff, all the main sim stuff, ...) into it's own .h file. I have some variables that I want all files to know, but when I #include them in more then one file other the g++ compliler sees it as a redefi...
You can put the declarations for all the globals in a header and then define them in a source file and then you will be able to use those global variables in any other source file by just including the header as shown below: header.h #ifndef MYHEADER_H #define MYHEADER_H //declaration for all the global variables ex...
72,355,483
72,355,712
Calculate class Cylinder using class Circle
The constructor of class "Circle" allows the radius to be specified via a parameter, while it is not possible to create objects of the Circle type without specifying the parameter. Also, automatic conversion of real numbers into Circle objects must not be allowed. The Set method, which does the same thing as a construc...
Cylinder::Cylinder(double r_baze, double h) { baze.GetRadius() = r_baze; height = h; } In your Cylinder class, when your constructor is called, baze is implicitly initialized with a default constructor that does not exist. You want to use an initializer list to handle that initialization, at which point the code i...
72,355,676
72,356,023
Why does Bazel http_archive rule not download archive?
I'm a Bazel newbie and am working through the C++ guide here, trying to include an external testing library (gtest): https://bazel.build/tutorials/cpp-use-cases#include-external-libraries This is my file structure and WORKSPACE and BUILD file contents: $ tree . ├── gtest.BUILD ├── lib │   ├── BUILD │   ├── hello-time.c...
I think the problem has to do with your gtest build file. First, google test comes with a supported Bazel BUILD file already, so why write your own instead of using theirs? Second: cc_library( name = "main", srcs = glob( ["src/*.cc"], exclude = ["src/gtest-all.cc"] ), hdrs = glob([ ...
72,355,799
72,355,883
How do I actually delete the node(s)?
I am solving a question on LeetCode.com: Given the root of a binary tree, collect a tree's nodes as if you were doing this: a. Collect all the leaf nodes. b. Remove all the leaf nodes. c. Repeat until the tree is empty.                                      For the input root = [1,2,3,4,5] (image above), the outp...
Your placement of delete is correct, but since we don't know how root is allocated we can't be sure whether delete is logically correct. BTW, delete deallocates the memory but it doesn't remove the pointers themselves. You can do root->left = root->right = nullptr to take care of that. Also, have findLeaves take a refe...
72,356,247
72,356,633
Unicode to integer conversion visual studio bug
Im trying to convert a unicode character to an integer and encountered a bug in visual studio not sure if its a bug or something im doing wrong The project has unicode character set and not multibyte. #include <windows.h> #include <iostream> int main() { constexpr int a = L''; printf("%i\n", a); std::cout...
Wide characters in Visual Studio are only 16 bits, meaning they won't hold a value greater than 65535. You're getting the first half of the character encoded in UTF-16, which is d83e dd80.
72,356,735
72,356,814
Struct of array global scope
I need a struct of array[lenght] to be seen by all my methods(global). The problem I have is that the struct needs to be initialized with a specific length inside a specific function. To be more precise the initialization of struct with the length of size has to happen when importantFunction() is called and I need all ...
If using std::vector is not allowed, then you can use dynamic memory allocation either manually using new and delete or better would be to use smart pointers. But since you're not allowed to use std::vector, i suppose you're also not allowed to use smart pointers in your project. template<class A> class Table { public:...
72,356,820
72,357,195
Compiler can't find SDL2 classes. How to properly include and link them?
I just started venturing into C++. I download this simple helicopter game and I'm trying to compile it, but I don't know how to properly include and link the SDL2 dependencies. My first approach was trying to compile it with gcc. I got to the following command: gcc main.cpp ^ -I C:\code\SDL2\SDL2-2.0.22\include ^ -I C:...
The source code of the game is referencing the SDL not SDL2. There is a chance that the function names or implementations have changed since version 1. In fact, if you download SDL and SDL2 and look for the SDL_video.h files in both versions, you will see that SDL_DisplayFormat is in SDL_video header file of version 1...
72,356,890
72,357,086
How to define the different template structs with different enums
I've two enums as below: enum TTT {t = 2}; enum XXX {x = 2}; I'm trying to make some struct to help me get the name of an enum. Here is what I've done: template<TTT> struct StrMyEnum { static char const* name() { return "unknown"; } }; template<> struct StrMyEnum<t> { static char const* name() { return "tt";...
StrMyEnum identifies the name of the template. You can have a general declaration for it, and then some specializations. But you cannot have a second set of declaration + specializations (like you did with the set for XXX). What you can do is have one template parametrized with both the enum type and the enum value. Th...
72,356,992
72,357,450
Use multiple sampler2D over one input texture in OpenGL
Now I have a noise texture generated by this website: https://aeroson.github.io/rgba-noise-image-generator/. I want to use 4 uniform samplers in my computing shader to get 4 random rgba values from a single noise texture. My computing shader source codes look like: #version 430 core layout (local_size_x = 1, local_siz...
The type of the uniform is ìmage2D, not sampler2D. To load and store an image, you must bind the texture to an image unit using glBindImageTexture. See Image Load Store. e.g.: glBindImageTexture(1, tex_noise, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F); If you want to bind a texture to a texture unit you need to selec...
72,357,168
72,357,291
C++ Code doesn't output in Visual Studio Code when certain data structures are used
I'm running into a weird bug in Visual Studio Code - I'm writing code in C++ using standard extensions (C/C++ extension pack) and if I write a simple program like this, it works fine: int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif cou...
I tested your code, and it ran as expected. Some ideas: When ONLINE_JUDGE is not defined, freopen("output.txt", "w", stdout); makes the output redirected to output.txt. Maybe you forgot checking the file instead of the console the second time you ran your program. Besides, since you were using Visual Studio Code, mayb...
72,357,225
72,357,290
OpenCV C++ memory leak issue
Just see the below code snippet - # include "opencv4/opencv2/opencv.hpp" # include "iostream" int main() { while (true) { cv::Mat* mat = new cv::Mat(2000, 2000, CV_8UC3); std::cout << "mat size" << mat->size() << std::endl; mat->release(); std::cout << "mat size after" << mat->size()...
A cv::Mat object contains metadata (width, height etc.) and a pointer to the image data. As you can see in the link, the cv::Mat::release method frees the memory allocated for the cv::Mat data (assuming the ref-count is 0). It does not free the memory for the cv::Mat object itself (i.e. the instance of the class contai...
72,357,301
72,357,384
What exactly does most specialized class mean in C++?
Let's say we have the following: template<typename T1, typename T2> class A {} template<typename T1, typename T2> class A<T1*, T2*> {} template<typename T> class A<T, T> {} Now, I know that we need to select the most specialized class, but for A<double*, double*>, there is a ambiguity error for both specializations ...
First, regarding terminology: Each of these definitions are not definitions for classes. The first definition defines a primary class template. The other definitions define partial specializations of that primary template. It is not possible to categorize partial specializations by "levels" of specialization. The actua...
72,358,050
72,377,912
Avoid reusing thread ids in C++
I noticed that based on this, Linux reuses the thread ids of terminated threads instead of generating new ones. For some reason, I need to avoid this behavior. How can I make sure that newly created threads, will have a freshly generated thread id instead of reusing the old ones? (Update for interested people: I'm work...
There would be a way to avoid the stack allocation for terminated threads to be reused, you will have to self-allocate the stack memories. The pthread_attr_setstack could help. Notice that it add complexity to handle the buffer overflowed and the responsibilities now belong to API users Following is some tests that I h...
72,358,267
72,358,367
How to get the true disk usage of a sparse file on windows?
I am watching a book called "windows via c/c++". It says a programmer can create a sparse file with VirtualAlloc() on a FileMapping. And I can see that this sparse file taking 1MB in file's properties in the book. And the book say it only takes 64KB on disk actually . So how can I get the actual size of a sparse file...
You should check documentation rather than rely on the book. You create a file mapping backed by the normal file with PAGE_READWRITE|SEC_RESERVE options. File size is supposed to increase 4 MB to match size of mapping object: If an application specifies a size for the file mapping object that is larger than the size o...
72,358,544
72,358,860
Abstract class with template function issue
I have an abstract struct I with method a. B and B2 will inherit from it. X struct has an I type member and will instantiate it via createInsance template method based on type. I want to have on B2 an additional function b2Exclusive but I got compilation error that it is not present in A. error: ‘using element_type = ...
You can only call b2Exclusive if the template function use typename B2: one way to do so is to create the specialization for that type, such as this for example: struct X { void createI(); template <typename T> void createInstance() { //do something } std::string type ...
72,358,852
72,358,973
Int subtraction from a string
Why doesn't the code below give an error that says the array is out of range? #include <iostream> int main() { std::cout << "Hello, world!" - 50; return 0; }
It doesn't give an error because it's your job to make sure to honor array bounds. Like many other things this is impossible to always detect so it's left up to the user to not do it. Compiler have gotten better at warning about it though: <source>:4:36: warning: offset '-50' outside bounds of constant string [-Warray-...
72,358,922
72,372,395
Java, C++ JNI - java.lang.UnsatisfiedLinkError : No .dylib in java.library.path
I was trying to link java and c++ code using java JNI but when I ran the java file using dylib path, getting an error that no file was available. However, my lib file is available in the current working directory. Also, I tried moving same dylib to /Library/Java/Extensions but still the same error. Java File: JNIJava.j...
instead of using 'System.loadLibrary("")' use 'System.load("lib path")' and check if the library is working.then you can move it to the java library path. for example : (tested and working) try { String libPath = System.getProperty("user.dir") + System.getProperty("file.separator") + System.mapLibraryName("JNI_CPP")...
72,359,283
72,366,191
IntelliSense VSCode show "name must be a namespace nameC/C++(725)" on "using namespace nvcuda;"
Hi everyone actually I'm programming on Cuda and I'm testing a simple tensor core example, but i have a problem with intelliSense, practically its show me errore on this commands (see image) and I dont know why, because when i compile and run programm (with tasks) its work correctly, some ideas ? Errors: Entire code: ...
Set CUDA_ARCH variable in c_cpp_properties as follow: { "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**" ], "defines": [ "__CUDA_ARCH__=750" ], "compilerPath": "/usr/bin/gcc...
72,359,355
73,552,753
Extend display range of ArrayItems/IndexListItems using natvis
I am trying to visualize a memory content using natvis which is pointed by a pointer. I have also tried to declare the memory as a vector. But every time the problem I am facing is that, during debugging the visualizer can show only first 50 entry. I am giving here a very minimal example. Suppose, the pointer_array is ...
According to this release the problem is solved although there is still bug of displaying more than 1000 value using ArrayItems node. See this issue to get more information. This display range limitation is gone if IndexListItems is used. Following snippet could be used to see more than 1000 element <IndexListItems...
72,359,915
72,360,105
Is there a way to see what's inside the stdio.h or how it's implemented?
Is there a way to see what's inside the stdio.h or how it's implemented? I learned that the standard functions are declared in the stdio.h file and I can't find it in my computer plus I heard that there is another file where the body of the functions are all written, which is called the stdio.c file. Can anyone tell me...
As far as I know the c++ header files are stored in C:\Program Files (x86)\Windows Kits\10\Include\"some_version"\ucrt for Windows, and in /usr/include for linux. There you can find the stdio.h file and any other of the standard c++ header files. Otherwise looking on the internet for stdio.h source code is also an opti...
72,360,372
72,365,328
Including a C++ library into another?
I'm trying to build a c++ library, which will be using itself another library. I would like to output at the end a single .so file, so it is easily copied and used in any other project. In this library I am using another library, GLFW. Now, I can create my library fine, but when I am using it I am getting linking error...
From what I can deduce from your CMakeLists.txt, you should do something like this (I don't like vendoring, not an expert of this approach, so maybe there is something more elegant): cmake_minimum_required(VERSION 3.20) project(MyLib) # glfw static PIC set(CMAKE_POSITION_INDEPENDENT_CODE_SAVED ${CMAKE_POSITION_INDEPEN...
72,360,602
72,363,006
Fast 1D Convolution with Eigen C++?
Suppose I have two data arrays: double data[4096] = { .... }; double b[3] = {.25, .5, .25}; I would like a fast and portable implementation of convolution. To use NumPy syntax result = numpy.convolve(data, b, "same") Kernel size is small, 3 or 5 and I may have to convolve with a kernel with zeros (giving scope maybe ...
Armadillo should have you covered. An Eigen implementation may look like this: Eigen::VectorXd convolve(const Eigen::Ref<const Eigen::VectorXd>& in, const Eigen::Vector3d& weights) { const Eigen::Index innersize = in.size() - 2; Eigen::VectorXd out(in.size()); out.segment(1, innersize) = in....
72,361,092
72,361,743
Passing parameter pack in constexpr
i am trying to determine the size of all passed objects at compile time and then abort the build process via static_assert when a maximum size is exceeded. #include <iostream> template<class T> class Test { public: T value; constexpr size_t size() const { return sizeof(T) + 3; } }; template<typename ...T> con...
Function arguments are not constexpr expressions (for good reasons) even if part of constexpr or consteval functions. If you are willing to make Test::size static, independent of objects: #include <iostream> template<class T> class Test { public: T value; constexpr static size_t size() { return sizeof(T) + 3; ...
72,361,515
72,430,374
Getting huge random numbers error while trying to get the maximum element in array - C++ error
I am making a program in which the program takes 3 numbers as input: "l", "r" and "a". I get all the values of "x" between l and r, (l and r inclusive). example, l = 1, r = 3, x values are 1, 2, 3. so now I have a function, f(n) = ((x/a) + (x % a)),(note: [x/a] is rounded down to an integer). so I have implemented this...
Request from Levi to post my comment as answer: The point is that one of the successes of C++ is that it started from C, but it moved on quite a bit and the code in your question is still mostly C-code. Here is an example how it could be handled in C++ with more knowledge needed but less chance for errors: #include <io...
72,361,930
72,362,064
why are elements of unordered_set not unique for custom equal_to
I am trying to understand unordered_set better. Mainly, to my understanding elements in an unordered_set should be unique up to equal_to operator. Therefore, I decided to test that by a small piece of code #include <iostream> #include <unordered_set> using namespace std; struct m_int { int x; }; // template specia...
Unordered containers have the following requirements for their hash and key equality functions: If two Keys are equal according to Pred, Hash must return the same value for both keys. This is not true for your container. 1 and 4, for example, compare equal but they'll (almost certainly) have different hash values. Th...
72,362,234
72,362,470
How to use QHash::removeIf(Predicate Pred)
Qt 6.1 introduced the method removeIf(Predicate Pred) to a number of its collection classes: QByteArray, QHash, QList, QMap, QMultiHash, QMultiMap, QString and QVarLengthArray. But how do I write a predicate? Let's take a QHash example: struct MishMash { int i; double d; QString str; enum Status { Inact...
From the documentation... The function supports predicates which take either an argument of type QHash<Key, T>::iterator, or an argument of type std::pair<const Key &, T &>. That being the case, you should be able to use a lambda something along the lines of (untested)... myHash.removeIf( [](QHash<QString, MishMa...
72,362,615
72,420,796
Is it really impossible to suspend two std/posix threads at the same time?
I want to briefly suspend multiple C++ std threads, running on Linux, at the same time. It seems this is not supported by the OS. The threads work on tasks that take an uneven and unpredictable amount of time (several seconds). I want to suspend them when the CPU temperature rises above a threshold. It is impractical t...
I want to suspend them when the CPU temperature rises above a threshold. In general, that is putting the cart before the horse. Properly designed hardware should have adequate cooling for maximum load and your program should not be able to exceed that cooling capacity. In addition, since you are talking about Turbo, ...
72,363,129
72,363,576
Wrapping std::getline()
I am struggling with the problem of reading input from file on a per-line basis, in a cross-platform way. Different platforms use different sequences of characters to represent a new line/end of line. std::getline doesn't deal with these in a cross platform way. What do I mean by this? std::getline changes its behavio...
You should take the stream by reference because streams typically cannot be copied. Also the string should be passed by reference because you want to write to it. To be generic you can use the same interface as std::getline does. As you want to use specific delimiters, they need not be passed as arguments. If you make ...
72,363,664
72,365,018
Embedding Python to C++ Segmentation fault
I am trying to track the execution of python scripts with C++ Threads (If anyone knows a better approach, feel free to mention it) This is the code I have so far. #define PY_SSIZE_T_CLEAN #include </usr/include/python3.8/Python.h> #include <iostream> #include <thread> void launchScript(const char *filename){ Py_In...
After testing and debugging the program for about 20 minutes I found that the problem is caused because in your example you've created the second std::thread named second before calling join() on the first thread. Thus, to solve this just make sure that you've used first.join() before creating the second thread as show...
72,363,792
72,364,162
Eigen: Comparing each element of vector with constant
is there a way how to compare each element of a vector with a constant? So far, I am comparing 2D vector Eigen::Vector2d with a constant double tolerance like this: if (x(0) > tolerance && x(1) > tolerance) { ... } I have found the function isApprox() but it did not worked somehow. Is there is a nicer...
One way to do this is to use the array method of the Vector class. Like this: #include <Eigen/Dense> #include <iostream> int main(int argc, char * argv[]) { Eigen::Vector2d A{ 7.5, 8.2 }; std::cout << A << '\n'; auto res = A.array() >= 8.0; std::cout << res << '\n'; if (res.all()) { std::c...
72,364,063
72,364,848
C++ functions declaration with macros
I am asking about a way to improve code readability I was able to make a macro like this for a small library I'm making #define fun(name, arg1, arg2) void name(int arg1, int arg2) NOTE: int is an existent class, but I replace it with int so anyone can run it This would allow me to use this code to create a function: f...
As you already discovered: technically it can be done, but not in a #define fun name(arg1, arg2) and I think that's a good thing because you want to hide the fact that you're using macros while that should be clear enough. Also fun doStuff(arg1, arg2, bin) looks like a regular function declaration with empty parameter ...
72,364,329
72,376,327
boost::beast ssl tcp stream: gracefully disconnect and then reconnect
I have a boost::beast ssl stream data member: class HttpsClient { ... asio::ssl::context _ssl_ctx; beast::ssl_stream<beast::tcp_stream> _stream; }; At construction I initialise the stream with an asio::io_context and an ssl context as follows: namespace ssl = boost::asio::ssl; ssl::context sslContext() { ...
This issue relating to websocket, but possibly the ssl stream has similar requirements, says to recreate the entire stream... suggests reusing a disconnected stream is not possible. Certainly recreating the stream does work, which suggests this is indeed the case
72,365,350
72,365,403
Can I test the value of a preprocessor directive?
I have a preprocessor directive that I do not set, so I cannot change it, it is either true or false. Normally I would have done : #ifdef DIRECTIVE // code #endif But this will always run, since DIRECTIVE is always defined. Is there a way that I can do basically the equivalent of: #if DIRECTIVE #endif I guess I could...
The preprocessor has an #if statement, so you can do things like: #if DIRECTIVE, which (just like in C normally) tests as false if the value of he expression is zero, and true if the value of the expression is non-zero. Although it's not clear whether it provides a real advantage for you, there's also a kind of interme...
72,365,688
72,461,717
wxChoice not visible in wxPanel
I need to add a drop down box to a panel but it doesn't seem to show up when I add it. WeldProfileDialog::WeldProfileDialog(cMainWindow* parent, wxWindowID id) : wxDialog(parent,id, "Weld Profile Editor") { wxBoxSizer* mainSizer = DBG_NEW wxBoxSizer(wxHORIZONTAL); this->SetSizer(mainSizer); wxBoxSizer*...
As spotted by @Igor: The problem was that my control was a child of the window instead the panel, which placed it under the panel. this: wxChoice* selectProfileType = DBG_NEW wxChoice(this, wxID_ANY); into this: wxChoice* selectProfileType = DBG_NEW wxChoice(sidebar, wxID_ANY);
72,366,296
72,366,365
Count how many times class member was printed
I need to count how many times class members were printed using function Print which is inspector. Constructor should set private elements of class. #include <cmath> #include <iostream> class Vector3d { double x, y, z; mutable int count = 0; public: Vector3d(); Vector3d(double x, double y, double z); void...
You need to overload copy constructor and copy assign operator for Vector3d class. Now you are copying state of count field into v2 object, therefore it starts from 3 not from 0. #include <cmath> #include <iostream> class Vector3d { double x, y, z; mutable int count = 0; public: Vector3d(double x, double y,...
72,366,669
72,366,986
struct fwd-declared in member-function parameter list not nested in enclosing struct
I was trying to forward-declare nested type struct A::impl and run into this issue. The following code snippet compiles fine: struct A { struct impl; // `struct impl` fwd declaration void f(impl); // A::f declaration }; struct A::impl {}; // definition void A::f(impl) {} However, if I move the forward-declara...
Yes, there's a difference in what the forward declaration means here. C++ Standard [basic.scope.pdecl]/7 reads: The point of declaration of a class first declared in an elaborated-type-specifier is as follows: for a declaration of the form        class-key attribute-specifier-seqopt identifier; the identifier is dec...
72,366,851
72,367,118
Why does operator==(std::variant<T, U>, T) not work?
Consider the following: #include <iostream> #include <variant> int main () { std::variant<int, float> foo = 3; if(foo == 3) { std::cout << "Equals 3\n"; } } Godbolt demo here This does not compile because of the foo == 3: <source>:7:12: error: no match for 'operator==' (operand types are 'std...
Neither parameter of that operator== overload is an undeduced context. So template argument deduction for the overload will fail if it fails in either parameter/argument pair. Since int is not a std::variant, deduction will fail for the corresponding parameter/argument pair and so the template overload is not viable. I...
72,367,123
72,367,153
What is a call to `char()`, `uint8_t()`, `int64_t()`, integer `T()`, etc, as a function in C++?
I've never seen this call to char() as a function before. Where is this described and what does it mean? This usage is part of the example on this cppreference.com community wiki page: https://en.cppreference.com/w/cpp/string/basic_string/resize: short_string.resize( desired_length + 3 ); std::cout << "6. After: \""; ...
It's the constructor† for char; with no arguments it constructs '\0'. Rarely used since primitives offer other ways to initialize them, but you initialize them with () just like you would a user-defined class, which ensures they get initialized to something; char foo; has undefined value, while char foo = char(); or ch...
72,367,571
72,379,812
Seg fault while calling glfwSwapBuffers
It seems that I am having a seg fault while using GLFW and OpenGL on ArchLinux, DWM (fully updated and patched). I retraced the code and it is having the segFault in the glfwSwapBuffers(window). Here is my code : main.cpp #include <iostream> #include "gui/window.h" int main(int, char**) { Window window("Test GL", ...
Your problem occurs in Window.cpp, at this line: //... glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); GLFWwindow* window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); //<--- if (!window) { //... You've redeclared window as a local variable to this constructor, and as a result, the pointe...
72,368,147
72,368,244
How does "to_string" work in array of string?
I want to combine the first 4 characters of each line in txt file and compare it with the keyword I have, but when I combine the characters, I get the sum of these 4 characters' ascii numbers(whatever). How can I solve this problem. My code is here: When I debuged, I saw the string search(variable) was 321. int main() ...
line[0], line[1], and line[2] are chars, not std::strings. char is an integer type, so adding two chars together results in a single integer that is the sum of the two operands. It does not produce a std::string that is the concatenation of the two chars. To get a substring of a std::string use the substr member func...
72,369,144
72,371,888
Iterate an array from json using jsoncpp
I have the following json: { "laureates": [{ "id": "1", "firstname": "Wilhelm Conrad", "surname": "Röntgen", "born": "1845-03-27", "died": "1923-02-10", "bornCountry": "Prussia (now Germany)", "bornCountryCode": "DE", "bornCity": "Lennep (now Remscheid...
I can't realize how to iterate and show the values without hardcoded it. I think the problem is that you don't have a great handle on recursion or the key->value nature of JSON, because when you have an array like "prizes", you could have a nested Json object, such as an array inside an array. You could use a recursi...
72,369,308
72,369,874
c++ const ref vs template concept
I'm studying the c++20 specifications for templates, in detail the concepts. Currently for passing parameters to functions I use the const ref: void writeMsg(const std::string& msg) { std::cout << "msg = " << msg << "\n"; } I have only now discovered that templates can also be used, and with concepts I can control t...
As you presented it: types which are convertible to std::string wouldn't need to be converted before the call to std::cout (potentially saving memory [de]allocations). It's the only big advantage I can see looking at your code. However, flipping a bit or two: template <class T> concept String = std::is_convertible<T, s...
72,369,593
72,376,158
Does vkQueuePresentKHR prevent later commands from executing while it is waiting on the semaphore?
This is kind of a follow-up question for this question, and it is also based on the code provided by the same Vulkan tutorial. Here is a simplified example: // Vulkan handles defined and initialized elsewhere VkDevice device; VkQueue queue; VkSempahore semaphore; VkSwapchain swapchain; VkCommandBuffer cmd_buffer; // R...
In the above example, will the commands in cmd_buffer also have to wait until semaphore is signaled? Only if you use the semaphore as a waitSemaphore for the later submit. This is because the vkQueuePresentKHR command waits on that semaphore and it must begin before later commands in the queue begin (due to implicit...
72,369,737
72,372,146
How do we display pixel data calculated in an OpenCL kernel to the screen using OpenGL?
I am interested in writing a real-time ray tracing application in c++ and I heard that using OpenCL-OpenGL interoperability is a good way to do this (to make good use of the GPU), so I have started writing a c++ project using this interoperability and using GLFW for window management. I should mention that although I h...
From your second para you are creating an OpenCL context with a platform specific combination of GLX_DISPLAY / WGL_HDC and GL_CONTEXT properties to interoperate with OpenGL, and you can create a vertex buffer object that can be read/written as necessary by both OpenGL and OpenCL. That's most of the work. In OpenGL you ...
72,369,740
72,370,003
Operator overloading not working as intended for class pointers
I've made a very simple program trying to understand operator overloading in C++. However as you too will see, the result of the dimention d3 is not updated even though the appropriate values are returned from the operator overloading. #include <iostream> using namespace std; class dimention{ protected: int ...
I think you misunderstand the way methods operate on an object. Consider the assignment operator: dimention& operator = (const dimention &d){ dimention *temp = new dimention; temp->height = d.height; temp->width = d.width; return *temp; } You are never editing the object itself (this) that is being a...
72,370,293
72,370,674
How is modification order of a variable defined in C++?
I've read this Q&A: What is the significance of 'strongly happens before' compared to '(simply) happens before'? The author gives an outline of an interesting evaluation that was not possible until C++20 but apparently is possible starting C++20: .-- T3 y.store(3, seq_cst); --. (2) | ...
The modification order for an object is the order a thread would see if it was spinning in a tight loop running while(1) { y.load(relaxed); }, and happened to see every every change. (Not that that's a useful way to actually observe it, but every object has its own modification order that all threads can always agree ...
72,370,312
72,370,598
C++ what happen if I convert pointer type?
When we allocate a piece of memory, such as: double* ptr = new double[10]; It gives me a pointer that points to the 1st location of 10 continuous memory location of double Now if I do: unsigned char* ptr2 = (unsigned char*)ptr; does it create another unsigned char pointer that points to the 1st location of ptr, then ...
A C-style cast of a pointer type (type *)ptr does nothing at all to the bit pattern. It simply tells the compiler to consider the pointer to be of the new type. Something that is rather dangerous as in most cases using the result is just UB. Now char is a special case because it is used to access the raw memory underly...
72,370,560
72,370,697
How to get the next line in a recursive function
I'm trying to create a recursive function, that will go through a file, and for each line, will create an instance of an object, give this object a name, list of attributes, and a previous name (all names are unique, so I don't need to worry about similarities). Here's the code: void getTags(string prevname){ ...
Your first problem is that your recursion has no base case (i.e. terminating condition), and so getTags is being called until you fill up the call stack, at which point you get a segmentation violation. The way to fix this is to create a terminating condition which, in this case, would be when you exhaust all of the in...