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
63,576,614
63,576,743
Can we use only one virtual inheritance in diamond inheritance pattern?
Suppose I have some classes: Base, Derived1, Derived2, ...etc. All the derived classes are derived from Base. Now, I want to add some functionality for all derived classes, but these classes can not be modified. So I came up with the following approach: Create a class Additional using virtual inheritance like this: cla...
Why must we use two virtual inheritance for diamond inheritance case? Virtual inheritance is a contract that a class has to enter into willingly. The class is basically saying that it's willing to share its base sub-object with an instance of another deriving class. It affects object layout and access to the base in ...
63,576,955
63,578,652
`wide-exec-charset` dose not change the charset of `wchar_t`
Here is the simple C++ code. #include <iostream> #include <locale> int main() { std::wcout.sync_with_stdio(false); std::wcout.imbue(std::locale("")); std::cout << std::locale("").name() << std::endl; // C.UTF-8 wchar_t s {L'\xd0b8'}; std::wcout << s << std::endl; // expected: и // actu...
man gcc says -fwide-exec-charset=charset Set the wide execution character set, used for wide string and character constants. The default is UTF-32 or UTF-16, whichever corresponds to the width of "wchar_t". As with -fexec-charset, charset can be any encoding supported by the system's "ic...
63,577,032
63,587,644
Problem with website using QNetworkAccessManager Investing.com
I am trying to read automatically some information from investing.com using QNetworkAccessManager. I can read from other sites but this site gives some webmaster tools which I want to access. https://www.investing.com/webmaster-tools/ I use this query which works in a browser. Here is my request code class InvestingAPI...
By default Qt Network does not handle redirects like other tools, so that is why you get an empty data (if you check the "Location" header you will see the redirected url). In this case it is to enable the redirection: Request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
63,577,103
63,577,511
What is an equivalent replacement for std::unary_function in C++17?
Here is the code that's causing me some issues, trying to build and getting the error: 'unary_function base class undefined' and 'unary_function' is not a member of std' std::unary_function has been removed in C++17 so what is an equivalent version? #include <functional> struct path_sep_comp: public std::unary_funct...
std::unary_function and many other base classes such as std::not1 or std::binary_function or std::iterator have been gradually deprecated and removed from the standard library, because there is no need for them. In modern C++, concepts are being used instead. It is not relevant whether a class inherits specifically fro...
63,577,921
63,580,270
Maze generation algorithm design (Recursive Division)
I am trying to include a maze generation in my pathfinding visualization solution in order to generate mazes on what the current application can work on. I found a very well structured website, there are bunch of maze generation algorithms, but I primarily focused on one: http://weblog.jamisbuck.org/2011/1/12/maze-gene...
In contrast to the link you were inspired from, your walls take a space of one cell. The easiest way to avoid your problem would be that your walls can only be placed on one column/row out of two. This is what would a maze with "thin walls" produce And here's the equivalent with thick walls (what you're using) As you...
63,578,209
63,583,572
(C++) Win32 API sample code returning "undefined reference to `WinMain@16'" using g++
I am using the G++ compiler with notepad++. I am following a tutorial by windows, the code that I am using is the example code from the windows tutorial (https://learn.microsoft.com/en-us/windows/win32/learnwin32/your-first-windows-program) I pasted this into my notepad and attempted to compile it, but I was greeted wi...
in the line int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) I changed wWinMain to WinMain and I changed PWSTR to LPSTR and now it works. I have no clue why. Hope it helps anyone with the same problem (-:
63,578,410
63,579,348
Query about local copy of object and working of copy constructor
I have few confusions about what exactly happens when you pass the object by value, and about working of copy constructor. To practice the concept, I wrote the following code. #include <iostream> using namespace std; class Cat { public: Cat(); Cat(Cat&); ~Cat() { cout << "Destructor called\n";} int itsage; ...
The main problem is, the "copy" constructor Cat::Cat(Cat &) doesn't copy the value of itsage but sets it to an arbitrary value. Thus, passing a Cat object by value and returning it will yield strange results since the received objects don't resemble the original object. Details: The parameter Frisky of the function myF...
63,579,667
66,566,341
Adding Arbitrary Texts to fmt's User-defined Type Formatter
I'm wondering what's the correct way of adding some arbitrary text to fmt::formatter::format. Basically, I want to have a title for my object. The current implementation works but I'm not sure whether it can be done better, also I've a feeling my vertical alignment hack can be done nicer. namespace fmt { template <> ...
You can copy the text via the output iterator returned by ctx.out(): template <typename FormatContext> auto format(const Experiment& e, FormatContext& ctx) { auto out = ctx.out(); auto text = std::string_view("Experiment:\n\t\t\t\t"); out = std::copy_n(text.data(), text.size(), out); ret...
63,579,775
63,580,056
An issue about what's the type of a declaration which is surrounded by parentheses
In the section dcl.meaning, it says: Thus, a declaration of a particular identifier has the form T D where T is of the form attribute-specifier-seq opt decl-specifier-seq and D is a declarator. Following is a recursive procedure for determining the type specified for the contained declarator-id by such a declaration. ...
You have to continue to the next section. Bullet 6 is just one case, which does not apply here because your declaration is not of the form T (D1). It is of the form T D with T = int and D = *(ptr). D = *D1 (matching here with D1 = (ptr)) is handled by [dcl.ptr]: In a declaration T D where D has the form *attribute-spe...
63,579,830
63,596,382
C++ Class template with functions from inherit parents
Lets assume this class using C++14 (and QtRO system in origin). https://pastebin.com/EVT4XJiz #include <iostream> #include <functional> #include <memory> class QTRO_1Source { public: void hvEnabledChanged(bool) {}; virtual bool hvEnabled() const = 0; }; class QTRO_1SimpleSource : public QTRO_1Source { publi...
ReplicaType gets deduced from 4 different arguments, and the results of deduction are conflicting. See compiler output: note: candidate template ignored: deduced conflicting types for parameter 'ReplicaType' ('QTRO_1' vs. 'QTRO_1SimpleSource') You can workaround it by employing 3 additional template parameter for cla...
63,579,843
63,579,958
expected primary-expression before ‘m_Buffer’
This is my first question so excuse me if it's not clear. I am trying to run this code using my first implementation with smart pointers; But it results to an error that i'm not understanding. I needed to put (void) because if not, it shows me a message saying that it's not possible to convert from char to void*. Error...
(void) std::unique_ptr<char> m_Buffer(new char[m_Size]); The (void) needs to go. You have added it because of a completely unrelated error. Now, to fix that error, you need to realize that memcpy accepts a void*, not a char*. The cast exists and is implicit, but you need to get the raw pointer from the smart pointer v...
63,579,997
63,592,408
Tracking hand rotation with RotatedRect
I'm using OpenCV for a project to detect hand gestures, I managed to isolate the hand and drawing the convexes the hand is appearing very clearly now. My goal is to detect if the hand is rotating or moving left or right. I used RotatedRect to figure out if the hand is rotated or not, but it seems like the RotatedRect i...
Here is an approach using PCA You can find the code here Result: Note: if the hand shape doesn't change and you have a reference angle, you'll be able to get it's rotation angle accurately.
63,580,718
63,580,995
QComboBox not aligning to right
I have a QHBoxLayout and i want to add some children to the right, and other to the left: label = new QLabel(...); layout->addItem(label); layout->setAlignment(label, Qt::AlignLeft); select = new QComboBox(...); layout->addItem(select); layout->setAlignment(select, Qt::AlignRight); However select is not been aligned t...
QHBoxLayout * layout = new QHBoxLayout(this); QLabel * label = new QLabel("this is label"); layout->addWidget(label, Qt::AlignLeft); layout->setAlignment(label, Qt::AlignLeft); QComboBox * select = new QComboBox(this); layout->addWidget(select); layout->setAlignment(select, Qt::AlignRight);
63,580,846
63,583,443
call a callback function in a pthread function
I'm learning about callback functions in C++ and I'm trying to call a callback function in a pthread function wherein I'm passing the function as argument to pthread_create using reinterpret_cast and then cast it back inside pthread function. This is my code #include <iostream> #include <atomic> #include <algorithm...
Can somebody tell why this difference? Casting between a pointer-to-function and a pointer-to-object types is not portable. Compilers might accept it, or they might reject it. See C++ Standard expr.reinterpret.cast GCC is a bit inconsistent here: up to but excluding gcc 4.9, you get a warning with -pedantic about thi...
63,580,898
63,581,126
convert vector<int> to const unique_ptr<const int[]>
how to convert/copy a vector to unique_ptr<int[]> ? this is what I want to achieve (the vector originates in another context and will be deleted after copying to the unique_ptr. unique_ptr is of fixed length and thus can be allocated more efficiently). std::vector<int> vv {1, 2, 3}; struct U { U(std::vecto...
There are several problems with what you are doing. First you have two copies instead of one (in the U constructor), then as you need to get the actual iterator on your u, not u itself. For the const correctness, you can just have an intermediate unique pointer that allows the data to be changed. The final code you hav...
63,581,288
63,581,352
Why is operator!= synthesized from operator==, but not the other way around?
In c++20, if I provide an operator== for a type, then the compiler synthesizes an operator!=, but not the other way around. Here's some code: struct A {}; bool operator==(A const&, A const&); struct B {}; bool operator!=(B const&, B const&); int main() { if (A{} != A{}) {} // error in c++17 ...
Because this adds complexity to the language for no benefit. The primary operation is equality. C++20 lets you just define operator== to get the full complement of equality operations (== and !=). Likewise, the primary ordering operation is <=> and C++20 lets you just define that and get the full complement of ordering...
63,581,507
63,581,593
Problems when trying to replace a sub-string of unequal length
I have a function that replaces a sub-string with another: std::string replaceAll(std::string data, std::map <std::string, std::string> dict){ for(std::pair <std::string, std::string> entry : dict){ size_t start_pos = data.find(entry.first); while(start_pos != std::string::npos){ data.replace(star...
The second argument to replace needs to be the count of characters from the original string that you want to replace. So you need: data.replace(start_pos, entry.first.length(), entry.second); // ^^^^^^^^^^^^^^^^^^^^ length of original string
63,581,715
63,589,773
How does the MFC PropertyGrid control work in the dialog editor in visual studio?
In the visual studio dialog editor i can add a MFC Property Grid control to the dailog. How can i customize its content, and set options like allowing the user to edit the contents of it when the program using it is running, or how i can change the contents of it using c++? When i add something like a button or and edi...
Simple tutorial of CMFCPropertyGridCtrl: 1.Create a dialog-based MFC project, drag a CMFCPropertyGridCtrl into it, and adjust the size. Then change the ID for the control to IDC_MFCPROPERTYGRID_TEST, and use Add Varible to add a variable m_propertyGrid to the control. Change the setting of Notify to True. Description ...
63,582,032
63,582,173
Content of string is different from expected content
the task is to read an input file, store the content of the file in a string variable and perform some operations on it. I have a problem by removing all new line characters from the string. Reading the content of the file and storing it in a string variable works fine, but somehow trying to remove the new line charact...
Your file has Windows newlines \r\n. When you remove \n, you get line 1\rline 78\rline 3. \r in output is treated as caret return, i.e. move next output position to the beginning of the line. Thus line 78 rewrites line 1 and line 3 rewrites first 6 chars of line 78. You get line 38. The simplest solution buffer.erase(s...
63,582,175
63,582,504
Why doesn't my compiler recognize #include <thread> (c++)?
I wrote this as a simplified version of a multithreading example to get a feel for it, but am running into some issues when compiling. My compiler says that thread is not a member of std and prompts me to add #include <thread> to my code even though I have already done so. I've been unable to find any similar problems ...
MinGW-w64 by default comes with native (Win32) instead of POSIX threads support, and unfortunately there is currently no Win32 gthreads implementation (the threading subsystem of libstdc++), hence no threading functionality in GCC. You need to switch from x86_64-w64-mingw32-g++-win32 to x86_64-w64-mingw32-g++-posix pac...
63,582,240
63,583,174
npz file as input in pybind11
I'm trying to wrap a npz file with pybind11. I have the following arguments in python, where the function pathlookup is in c++ : import testpy_path sourcefile1 = np.load('data1.npy') sourcefile2 = np.load('data2.npz') testpy_path.pathlookup(sourcefile1, sourcefile2) //error at sourcefile2 In C++ with pybind11, I'm t...
I am not very experienced with numpy, but this is what I found in the manual: When you use load() with npz files then numpy.lib.npyio.NpzFile instance is created, that's not an array instance. Here is important part from manual about NpzFile: A dictionary-like object with lazy-loading of files in the zipped archive pr...
63,582,440
63,584,680
14 Bit conversion in HEX - MCP2515 and MAX31855
Referring to the MAX31855 board, the signed value of the temperature is given by 14bits bits [31:18]. Those 14 bits are sent out MSB first, and the first bit is the sign bit. Those are the example values: Temperature data format I would like to place the value in the first two slot of a 8 slot array, that will be sent ...
I'm not sure what do you mean by "already converted in decimal format" and why would you need that. Here is how you can shift the the value from the board and put it into first two bytes of your array (fr your 1,000C example): unsigned char data[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; int temp = 0b0011...
63,582,751
63,582,894
How to erase a row like erasing an element in 2D vector
I am new to C++ vector and wanna ask a question about it. I built a 2D vector below: 1 2 3 4 5 6 7 8 9 and erase the 4 with these codes... #include <vector> #include <iostream> using namespace std; int main() { vector<vector<int>> v; for (int i = 0; i < 3; i++) { vector<int> r; for (int j...
The clear method only removes all elements from the vector but not the vector itself. You can achieve this with v[1].clear(); v.erase(v.begin() + 1); I will explain it in more detail: v.begin() returns an iterator pointing to the first element of the outer vector. v.begin() + 1 advances this iterator by one pointing t...
63,582,797
63,583,135
uniform_int_distribution with zero range goes to infinite loop
For unit tests I implemented a mock random number generator. I believe that this is a valid implementation of UniformBitGenerator (the mock actually uses google mock to set the return of operator(), but it behaves the same). struct RNG { using result_type = size_t; static result_type min() { return 0; } sta...
The standard says ([rand.dist.uni.int]): A uniform_­int_­distribution random number distribution produces random integers i, a ≤ i ≤ b, distributed according to the constant discrete probability function   P(i|a,b)=1/(b−a+1) . . . explicit uniform_int_distribution(IntType a = 0, IntType b = numeric_limits<IntType>::ma...
63,583,242
63,583,600
Are these float attributes macros specific to GCC?
I am using GCC and my compiler defines those macros : __FLT_RADIX__, __FLT_MANT_DIG__, __FLT_MAX_EXP__, __FLT_HAS_INFINITY__, __FLT_HAS_QUIET_NAN__, __FLT_HAS_DENORM__, ... Are they specific to GCC or are they in the C++ standard ? I mean wether they are defined or not, I know their values are implementation-specific. ...
Are they ... in the C++ standard ? No. Are they specific to GCC They are not in GCC documentation, so they are not guaranteed to be in (future releases of) GCC either. They are for internal use (probably for portable implementation of the standard macros and std::numeric_limits). where can I find their equivalent ...
63,583,291
63,584,266
Trying to implement Durand-Kerner-Method in C++ using Matrices
My implementation of the Durand-Kerner-Method (https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method) does not seem to work. I believe (see following code) that I am not calculating new approximation correctly in the algorithm part itself. I cannot seem to be able to fix the problem. Very grateful for any advice. ...
Your problem is that you do not transcribe the new values into the next data record with index col+1. Thus in the next loop you start again with a data set of zero entries. Change to P[col+1][row] = P[col][row] - g; If you want to use the new improved approximation immediately for all following approximations,...
63,583,468
63,583,650
Plane Equation From 3 Points Not Returning Correct Values
As part of a raytracer experiment I'm working on in my high school classes, I need to make it so that I can get the 4 parts of a plane equation from 3 different points. By 4 parts i mean in the equation Ax + By + Cz = D I need to find A, B, C, and D. I understand the math behind this as its relatively simple vector m...
Since in your example, you get the values for A, B, and C correct, the first place to look is in the calculation of D. In your calculation of d, you use parts of three different vectors. This is not what the equation for D says to do. You want to use the three parts from one vector. d = a * A.getX() + b * A.getY() + c ...
63,583,843
63,584,038
Printing array of doubles gives unexpected results
In a program I am writing I am experiencing unexpected output when printing data from an array. I have tried with float and double. Here is the code: #include <iostream> int main() { double vector[3]{ 193.09375 , 338.5411682 , -4.0 }; double pVecX{ 193.09375 }; double pVecY{ 338.5411682 }; double pVecZ...
An Arrays index starts at 0. So when you say vector[3] you are actually going out of bounds. You only have 0, 1, and 2 indices or subscripts. Although you do have 3 elements. 0 would refer to your first element, 1 would refer to your second element, and 2 would refer to your 3 element, and so on and so forth. (Like I m...
63,583,888
63,587,324
Eigen sparse solver wrong results
I am trying to solve a sparse linear system Ax=B with the Eigen library in C++, however the following trivial example seems to give an incorrect solution: #include <Eigen/SparseCholesky> #include <Eigen/Dense> #include <Eigen/Sparse> #include <iostream> #include <vector> using namespace std; using namespace Eigen; in...
Here's documentation for SimplicialLDLT solver: This class provides a LDL^T Cholesky factorizations without square root of sparse matrices that are selfadjoint and positive definite. When the matrix stores real numbers in the elements, self-adjoint == symmetrical. Your matrix is clearly not symmetrical. Also, not eve...
63,584,337
63,587,082
Do I need an atomic if a value is only written?
Suppose I have several threads accessing the same memory location. And, if at all, they all write the same value and none of them reads it. After that, all threads converge (through locks) and only then I read the value. Do I need to use an atomic for this? This is for an x86_64 system. The value is an int32.
According to §5.1.2.4 ¶25 and ¶4 of the ISO C11 standard, two different threads writing to the same memory location using non-atomic operations in an unordered fashion causes undefined behavior. The ISO C standard makes no exception to this rule if all threads are writing the same value. Although writing a 32-bit integ...
63,584,341
63,584,416
Multiplying float with double overflow in C++
I am a bit confused of the point of having this warning: Arithmetic overflow: Using operator '' on a 4byte value and then casting the result to a 8byte value. Cast the value to the wider type before calling '' operator to avoid overflow. #include <iostream> using std::cin; using std::cout; using std::ios_base; int m...
The warning is because of this multiplication: 10 * c_MILLION. There can be some values of c_MILLION where some precision is lost that would not have been lost if c_MILLION was first converted to a double. Since the result of this multiplication is converted to double, a mistaken programmer might assume that no precisi...
63,584,356
63,584,601
import header files into c++ using cmake 3.10
I have a project structured as such -project -CMakeList.txt --bin --cmake --lib ---models ----object1 -----object1.h -----object1.cpp ----object2 -----object2.h -----object2.cpp ----... --src ---main.cpp ---CMakeList.txt I am trying to import and use objects from the models folder in the main.cpp file using cmake 3.10...
Keep it simple. Put a CMakeLists.txt in lib/models: add_library(models STATIC object1/object1.cpp object2/object2.cpp ) target_include_directories(models PUBLIC object1 object2) and in your main CMakeLists.txt, target_link_libraries(main models) The PUBLIC include directories will be propagated to the main target....
63,584,532
63,584,670
How to partially fill in a C++ Template Template Parameter without creating a new class
Is it possible somehow to "partially" fill in the parameters for a template template parameter, without introducing a new class or using statement for every size? My code: #include <vector> #include <array> #include <tuple> struct A { int a = 1; }; struct B { int b = 1; }; struct C { int c = 1; }; template<template<c...
The old rubber duck struck again. Suddenly I found the answer. It still requires a single extra class, but I don't need a new one for every size! template<size_t N> struct MyArray { template<typename _T> using Type = std::array<_T, N>; }; Foo<MyArray<16>::Type,A,B,C> fooA16; // works! Foo<MyArray<256>::...
63,584,661
63,584,736
Initialize pointer of strings without new keyword in c++
I am using c++. I want to initialize pointer of string. I have been doing it using : string *strPtr = new string("abcd"); But I don't want to use heap memory. Use somthing like this : string *strPtr; // initialize with "abcd" How can I do it using stack memory?
You can declare a string on the stack and then take the address of it: std::string str{"abcd"}; std::string* ptr_str = &str; But I'm sure it would be more convenient for you to handle a reference, a smart pointer, or maybe a std::string_view. Raw pointers should be used in some very specific cases nowadays.
63,584,828
63,621,734
making HTTPS request using cpp-httplib
I'm trying to send an HTTPS request in c++ using Cpp-httplib but I'm getting various errors and warnings building their example: #include "stdafx.h" #include <httplib.h> #include <Windows.h> #include <iostream> #define CA_CERT_FILE "./ca-bundle.crt" #define CPPHTTPLIB_OPENSSL_SUPPORT 1 using namespace std; int main(...
Try this. The definition must be before including the library. #include "stdafx.h" >>> #define CPPHTTPLIB_OPENSSL_SUPPORT #include <httplib.h> #include <Windows.h> #include <iostream> #define CA_CERT_FILE "./ca-bundle.crt" using namespace std; int main() { #ifdef CPPHTTPLIB_OPENSSL_SUPPORT httplib::SSLC...
63,584,832
63,584,900
Check if given string is palindrome c++ iterative method
#include<iostream> #include<string> using namespace std; int main(){ string str; cout << "Enter a string: "; getline(cin, str); int length = str.length(); string temp; int k = 0; for(int i = length-1; i>=0; i--){ temp[++k] = str[i]; } cout<<temp; return 0; } Actually, i want to find out whether t...
You defined an empty object of the type std::string string temp; So you may not use the subscript operator with the empty object in the loop. int k = 0; for(int i = length-1; i>=0; i--){ temp[++k] = str[i]; } Using your approach you could just write string temp( str.rbegin(), str.rend() ); without usin...
63,585,641
63,585,894
Understanding clang loop-optimization
I've got this piece of code #include <cstdlib> #include <time.h> int sum () { srand (time(NULL)); unsigned long extra = rand() % 10; int sum = 0; // #pragma nounroll. <<<< This makes no difference for (int i = 0; i < 16 + extra; ++i) { sum += i; } return sum; } and with -O3, clang optimized it ...
The code does call rand, which is sufficient. The return value will be held in the rax register. If you **divide 2³² by 1717986919 you get 2.499999999126885 which is quite close to 10 / 4... the constant is used, with shifts, to calculate the % 10 without having to use the expensive idiv opcode. After that, the result ...
63,585,933
63,586,097
Call a function from its address via a templated function
Assuming I have the runtime memory address of a function in an Application and I know the return type of said function, is it possible to call the function, knowing the functions return type, its arguments and calling convention, using a variadic template? The templated function has to support both void and non-void re...
the answer is yes, but doing it with variadic template is dangerous . to enforce the compiler to cast the address to a function pointer you need to use reinterpret_cast or a c cast . note : you are improperly casting an integral address to a pointer because you are really trying to cast the address of the variable cont...
63,586,128
63,586,269
Conversion of std:string to char*
I'm trying to convert a result string that I get by doing some data manipulation, eg: std::string result = std::string(/* num_max */, '0').append(myDataModule->getId().c_str()); I'm getting an id from getId() (which returns an AnsiString) on my TDataModule, converting that to a std::string using AnsiString::c_str(), a...
When I run the code, an error appears when I call this function: candidate function not viable: no known conversion from 'std::string' (aka 'basic_string') to 'char *' for 1st argument You did not show the actual code that is trying to pass the std::string to the receiver() function, but the error message is very c...
63,586,198
63,586,532
Can std::isfinite(IntegralType) ever return false?
According to the documentation of std::isfinite, the overload bool isfinite( IntegralType arg ) always casts arg to double and calls bool isfinite( double arg ). How would this be different from saying "bool isfinite( IntegralType arg ) always returns true"? In other words, under what scenario would bool isfinite( Inte...
Most (all?) other functions in <cmath> also accept integers and automatically convert them to doubles. std::isfinite likely does it for consistency. In theory it could return false if the conversion to double overflowed, but in practice we don't have large enough integral types. In fact, GCC & Clang with -O3 (targeting...
63,586,246
63,921,207
Do GNU GCC compilers only accept "<filename>.a" files as libraries?
So, basically what I am asking is, if GNU GCC compilers recognize only ".a" files as library files, the reason why I am asking this is because, I have linked 3 library files in my codeblocks cpp project, two of the library files have ".a" extension, the last has a ".lib" extension. When I try to build the project, this...
the .lib is presumably a visual studio static library which wont work with gcc anyway found this in one of the comments, which means, visual studio used .lib libraries and gcc uses .a libraries
63,586,288
63,587,824
Why can I read a dereferenced pointer, but can't write it in C, but can in C++?
I needed to patch a program, so I made a dll that I can inject and on inject it patches one byte of the instruction. The code is pretty simple, the only thing that this time I wanted to write it in C, instead of C++, just of curiosity. But when I load my dll it's thread crashes in place of writing to that pointer. The ...
The thing wasn't in the C or C++, it was about page protection. So the error was pretty descriptive at itself. After this confusing try and pray sequence I've decided to look up my C++ code once again and I had found out that my original C++ code had VirtualProtect calls in the other file, which I surely haven't checke...
63,586,631
63,586,873
What does this `randfloat()` do?
I saw some C++ code: float randfloat(float a, float b) { uint32_t val = 0x3F800000 | (rng.getU32() >> 9); float fval = *(float *)(&val); return a + ((fval - 1.0f) * (b - a)); } The complete code is on a Github gist. It seems to first bitwise OR the binary number 111111100000000000000000000000 with an...
0x3f800000 is the binary representation of 1.0f when stored in the IEEE-754 binary32 single-precision format. This format has 23 stored significand (mantissa) bits. These bits are filled with the 23 high order bits returned by a 32-bit PRNG, resulting in a pseudo random number in [1, 2). Subtracting 1.0f from the resul...
63,586,747
63,587,221
What are the differences between libfmt and std::format?
I am aware that the c++20 format proposal is a formalization of parts of libfmt, and that libfmt is a compliant implementation of that formalization. However, it's my understanding that libfmt provides additional functionality beyond that specified in the c++20 standard. What are the additional features? Additional, ar...
There are a bunch of things in libfmt that are not in C++20 format: fmt::print() to print directly to stdout. This is proposed in P2093. fmt::printf() also exists but is not proposed in that paper. fmt::memory_buffer as basically a dynamically sized container that you could format into via fmt::format_to(buf, ...). Su...
63,587,018
70,812,274
QLabel "break" word if too long
are there ways to allow QLabel breaks words if those words are too long? I've seen q_label->setWordWrap(true) but it works with spaces, but if a single word is too long, then it will overflow... I would like something like word-break: break-all for web development I've also seen QTextDocument but it does not allow to ...
Just put Zero-width space between each char from PySide2 import QtWidgets app = QtWidgets.QApplication() label = QtWidgets.QLabel() text = "TheBrownFoxJumpedOverTheLazyDog" label.setWordWrap(True) label.setText("\u200b".join(text)) # The magic is here. label.show() app.exec_() Or you can write your own QLabel from P...
63,587,405
63,588,383
Making The Edit Control Transparent WinAPI (win32)
This is the relevant part of my code: case WM_CTLCOLORBTN: case WM_CTLCOLOREDIT: case WM_CTLCOLORSTATIC: SetBkMode(HDC(wParam),TRANSPARENT); return LRESULT(HBRUSH(GetStockObject(NULL_BRUSH))); It makes the background all the controls transparent, including the edit ones. But when some text is typed, it overwri...
I realized that once the control is hidden and shown again, it fixes the visibility as intended. case WM_COMMAND: if(HIWORD(wParam)==EN_CHANGE) { ShowWindow(HWND(lParam),SW_HIDE); ShowWindow(HWND(lParam),SW_SHOW); SetFocus(HWND(lParam)); } break; case WM_CTLCOLORBTN: case WM_CTLC...
63,588,228
63,588,288
Minimizing the scope of objects for a lambda expression
I was wondering if there is some tool in C++ that I don't know yet that can minimize the scope of my objects and functions in the following simple example where I fill a vector with random dice rolls: std::vector<int> dice_samples(10); std::mt19937_64 m_gen; std::uniform_int_distribution<int> dist(1, 6); std::generate...
You can use a capture with an initializer (but the lambda then has to be mutable, because the generator can't be const): std::vector<int> dice_samples(10); std::generate(dice_samples.begin(), dice_samples.end(), [m_gen=std::mt19937_64{}, dist=std::uniform_int_distribution<int>{}]() mutable { return dist(m_gen); })...
63,588,902
63,598,686
In Bazel, how to prevent some C++ compiler flags from passing to external dependencies?
Our project is written in C++ and uses gRPC as a dependency. We are using clang as compiler. We set up the C++ toolchain file with -Wall -Werror, but this is causing issues with the warnings raised by gRPC itself. Is there a way to prevent Bazel from applying the Werror flag to the gRPC files, but still apply it elsewh...
You can define toolchain feature such as: warning_flags_feature = feature( name = "warning_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-Wall",...
63,589,878
63,590,520
`std::back()` like function in C++
I can create begin and end iterators using std::begin() and std::end(). e.g: int arr[4][4] = <something here>; auto begin_it = std::begin(arr); auto end_it = std::end(arr); However, why do we not have std::front() and std::back(). Is there any specific reason for them to be ommitted? Are there any similar functions I ...
Is there any specific reason for them to be ommitted? Is there any specific reason for them to be included? Things are not thrown into the standard library just because they can be. The standard library is intended to consist of useful functions, templates, and the like. The "burden of proof" lies with the person who...
63,590,011
63,590,300
Given a string S consisting only of '(' and ')', find out the length of the longest valid substring
I know there's already question on stackoverflow for this but my code is different. So i used stack to solve this question but somehow my output is not coming out right, but when i try to solve this on paper using the input testcase which gives wrong output I'm able to get the right answer, what am i missing in the cod...
In this piece of code: if(!store.empty() && store.top() == '(') { count+= 2; store.pop(); } else if(count>max) { max = count; count = 0; } consider what happens when the longest valid substring is at the end of the string: you never hit the false branch, and so you never update max. A minimal chang...
63,590,084
63,682,384
Should conversion operators be considered for function template argument deduction?
Consider the following code: template<typename> struct S { operator S<int&>(); }; template<typename T> void f(S<T&>); int main() { f(S<int&&>{}); // gcc ok // clang error } gcc uses the conversion operator on the temporary argument, returning S<int&> which is matched by S<T&>, and ac...
GCC is certainly wrong here: T& and T&& are different rows in [temp.deduct.type]/8 and are thus incompatible. Why it does so is not clear. It would make more sense to err in the other direction: if the parameter were declared as S<T&&> and the argument were of type S<int&>, there would at least be a T (i.e., int&) su...
63,590,249
63,601,383
Bullet Physics resetting rigidbody origin after manually setting
Working on a character controller in Bullet Physics engine that uses a rigidbody, specifically crouch functionality. I've run into an issue where Bullet is resetting the origin of the world transform for the body back to what it was before I set it manually. This appears to be happening when stepSimulation() is called....
Resolved this by completely removing, resetting, and readding the rigid body to the dynamics world via the following: if (this->input.keyLeftControl && !this->crouching) { this->crouching = true; this->crouchNeedFall = true; //Set scale btVector3 scale = this->clientBody->getCollisionShape()->getLocalS...
63,590,336
63,593,146
Is lazy evaluation efficient/optimizable?
I've found many uses for lazy evaluation, such as a tool for optimization (e.g. matrices). Another use is syntactic sugar. But before I go overboard and make my code look at lot cleaner at the cost of runtime overhead, do compilers know how to optimize this kind of stuff? Or should I just only use it when the potential...
The compiler can do a lot more than you may think. I'm not sure what you were going for in your example, but consider the following piece of code: template <typename TLazyChar> struct lazyUpperImpl{ TLazyChar in; lazyUpperImpl(TLazyChar in_):in(in_){} char constexpr operator()(){ auto c = in(); ...
63,591,168
63,591,322
How can the C++ constructor be used in expressions if it does not return anything?
#include <bits/stdc++.h> using namespace std; class vec{ public: int x; int y; vec(int a, int b) { x = a; y = b; } vec operator+(vec that) { vec ans(0, 0); ans.x = this->x + that.x; ans.y = this->y + that.y; return ans; } }; int main() { vec a(...
The constructor is a special function that initializes the object in memory. The object may be on the stack or the heap. Calling the constructor will initialize the memory. Note that the constructor is c++ syntactic sugar. vec x(0, 1); // creates the object named x of type vec on the stack vec *px = new...
63,591,555
63,605,686
How to synchronise threads without using any synchronisation methods?
I was asked in an interview that it is required to print numbers 1 to 3 in a sequential order by 3 threads without using any synchronisation techniques. I think that we can access the thread id to find out which thread it is and keep a flag associated with this thread in a structure which can be set to true this thread...
Create thread A Thread A prints '1' Thread A creates thread B and exits Thread B prints '2' Thread B creates thread C and exits Thread C prints '3' and exits No explicit synchro required, prints 1,2,3 in order using three threads, is a totally pointless exercise.
63,591,950
63,593,107
Casting a Generic Class Handle to Base Class (i.e. interface) with multiple inheritance
I'm developing a c-api wrapper for a c++ library. I'm also the maintainer of the c++ library. My basic strategy, which is working so far, is to have an opaque handle for every c++ class in the library. I'm declaring the handles as structs: struct Handle_; typedef struct Handle_ *Handle; Then in my c-api wrapper header...
I think, static_cast<>() and reinterpret_cast<>() simply aren't capable of this kind of transformation you request, since you have a multiple inheritance. Casting a class to its base classes involve some displacement magic if there are multiple base classes. My advice would be to use a static_cast<>() to cast to the co...
63,592,118
63,592,432
OpenMP thread initialization and de-initialization before doing work
I am using an API that needs to be started and stopped for every thread in which it is used. So if I want to do something with the API in a specific thread I have to call api_start() (and api_stop() afterwards). Now I have a very trivial problem I can solve in parallel which I want to try with OpenMP. Consider the prob...
You can call the functions manually at the beginning/end of the first/last iteration, respectively, or use something as std::call_once. However, this would add some overhead into each iteration (branching). EDIT: Actually, this wouldn't work since only a single thread would call those functions. You would need to defin...
63,592,184
63,592,218
what is the specific usecase for !! in C++
Came across using !! in C++ during condition check if ( !! (flag != 0 )){.. } This could be directly used like if( flag != 0 ){.. } Is there any specific corner use case in C/C++ or is it just a form of coding style ?
In this case, it's superfluous, but in general this style is used to convert the actual expression value to an integer type in C. a boolean type in C++.
63,592,191
63,592,285
Use Shared Object (.so) in a C++ project develop in Windows with Visual Studio for Linux using WSL
For a task I have I must develop C++ code for Linux but from Windows. I'm using Visual Studio 2019 with WSL 2 and the tests I've run worked well, it compile .out/.so/.a and giving me the ability to debug the code as if it was a regular project. The problem is when I need to link external .so to my project. In regular W...
Ask your boss permission to install Linux on your work computer (e.g. some genuine Linux distribution such as Debian or Ubuntu in some separate disk partition). This is -in terms of effort and your time- the cheapest route to follow. Read of course Advanced Linux Programming, syscalls(2), How to write shared libraries,...
63,592,334
63,592,454
Why does this code output different results for the same inputs?
I wrote a simple program to find the longest sub-string with distinct characters in a given string in C++. My code works for certain inputs, but doesn't for others. Moreover, it gives me different outputs for the same inputs. Where am I going wrong? int main() { int t; cin >>t; while(t--){ string s;...
The problem is that there is no check that j remains less than n, so you start checking characters beyond the end of your string, leading to in unpredictable results. Try while (isDist && j < n) That should help but I haven't checked the rest of your code for errors. You could also consider using s.at(j) instead of s[...
63,592,404
63,592,469
How is this C++ expression evaluated?
I came across this piece of code in Leetcode and was wondering how this works. I read here that Conditional expressions have right-to-left associativity, so shouldn't the order of evaluation be from right to left in which case it cause exception first if the stacks s1 and s2 are initially was empty? stack<TreeNode*> &s...
The expression is grouped as s1.empty() ? s2 : (s2.empty() ? s1 : ((s1.top()->val < s2.top()->val) ? s1 : s2)) (Note that this is the grouping for C, C++, C#, and Java. PHP have it the other way round!) In terms of evaluation, ? acts as a sequencing point, and only one of the ternary conditional branches is evaluated....
63,592,844
63,593,240
How to get correct file size only on the completion of a detected file change, not at the beginning?
I'm using libuv's uv_fs_event_t to monitor file changes. And once a change is detected, I open the file in the callback uv_fs_event_cb. However, my program requires to also get the full file size when opening the file, so I would know how much memory is to be allocated based on the file size. I found that no matter I u...
One approach is to have the writer create an intermediate file, and finish I/O by renaming it to the target file. e.g. this is what happens in most browsers, the file has an "downloading.tmp" name until download is complete to discourage you from opening it. Another approach is to write/touch a "finished" file after wr...
63,593,018
63,593,434
No match for function call when splitting circularly dependent CRTP class headers
So I have a CRTP class for matrices (still fresh in this topic), with a Matrix_Base and a derived Dynamic_Matrix class (and also a Static_Matrix derived class). Minimal example included: Matrix_Base is defined in cml.h: #ifndef _CML_H_ #define _CML_H_ #include <assert.h> #include <math.h> #include "dynamic_matrix.h" ...
In the compiler message, I also get this message. note: passing 'const CML::Dynamic_Matrix<double>*' as 'this' argument discards qualifiers So that means it has nothing to do with templates or CRTP, it is just other is const reference but operator() is not marked as const. So just put const qualifier to it. ...
63,593,094
63,617,667
rqt_image_view as input in opencv
i'm new to ros and opencv. However i want to know, is there any way to get the rqt_image_view output, so i can use it directly on opencv. Normally to get picture from file it will look like this image = imread("image.jpg", CV_LOAD_IMAGE_COLOR) but now, can i somehow change "image.jpg" to output from rqt_image_view wit...
As already mentioned in the comments, you need the cv_bridge package for this. Some additional information: The rqt_image_view node subscribes to an image topic to display the image/video stream, in your case the image topic is /video_192_168_20_105_5000. cv_bridge lets you directly convert the images published to the ...
63,593,102
63,593,485
Passing a struct pointer as paramater in C#
I need to include a .dll which contains the following C/C++ function prototype and struct definition: typedef struct { unsigned short us1; unsigned short us2; unsigned short data[16]; } myStruct; int myFunc(myStruct *MYSTRUCT); To use this Function i created a new Class: static class DLL { public struct My...
You might need to specify the packing of the struct (depending on the default packing used by the C++ code). You can also specify a fixed-sized array for the marshalling to take care of using [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]. You also don't need the C# implementation to use a struct and indeed for ...
63,593,246
63,594,377
For unit tests, is there a hackish way to change the value of a const variable?
I have a C++ 11 header which has a const value declared as my_const_value. And a function called GetValue that runs a complex logic using the const value and returns an expected value. I want to unit test GetValue with different values of my_const_value. I know this is not advisable but for writing a unit test for GetV...
I know you are looking for a way how to cast the const away, but I probably would go a different way. You say in your comment: Well. I have given my reason. I am testing the logic in GetValue. I have declared my_const_value as a const but that can be changed from 5 to something else in future when someone changes the ...
63,593,743
63,594,352
Process returned -1073741819 (0xC0000005) execution time : 2.049 s
This one is really frustrating, I have no idea where it is coming from. A little backstory I am working on my chess game in c++, and currently I'm on the chess engine part. Everything is going on well, suddenly, at this very specific position of pieces on the board, this error comes Process returned -1073741819 (0xC000...
If you're on linux and have command line executable, you can follow below steps Run your executable inside gdb ( gdb ./your_executable ) Start running your executable by run command This will crash your program inside gdb env. Now enter where command to know full back trace of crash You can also apply break point to t...
63,593,756
63,594,959
How to set a fix string at first of QLineEdit?
It's possible to set a fix string at first of QLineEdit? something like this: Which in here $ is constant and user could not remove or edit it.
use the input mask in the object: e.g. ui->lineEdit->setInputMask("$ 000.000.000.000 "); will look like
63,593,773
63,594,520
Read multiple variables from a text file in C++
I am assigning each variable for the moment using seperate text files. I have something in this form: double ft_means[3]; double ft_std_dev[3]; inputFile.open("mean.txt"); if (!inputFile) cout<< "Error"; count=0; while(!inputFile.eof()) { inputFile >> ft_means[count]; count++; } count= 0; ifstream inputFile2; ...
Assuming you have different blocks in your file, you can use the following structure: std::string line; // output variables std::vector<double> means; std::vector<double> stddevs; std::vector<std::string> expressions; // part one: means while (std::getline(inputFile, line) && !line.empty()) { double mean; std...
63,594,125
63,594,185
Function operating on each type of a variadic template typelist
I have defined a typelist like this: template <typename ... Types> struct typelist {}; using my_list = typelist<int, double, bool, float>; Now I have a function template, e.g. template<typename T> void foo() { std::cout << typeid(T).name() << std::endl; } and want to call this for every type in the typelist: foo...
template<class... Types> auto foo_foreach(typelist<Types...>) { return (foo<Types>(), ...); } int main() { foo_foreach(my_list{}); } For a real oldschool, well, use template recursion you've attempted before: void foo_foreach(typelist<>) {} template<class Head, class... Tail> void foo_foreach(typelist<Head,...
63,594,339
63,595,520
MinMax element of multiple attributes in an object C++
I have a C++ class with floating point attributes and I want to find the minimum and maximum for all of them. class Block { public: Block(); protected: float x; float y; float width; float height; } I could just use a for loop if I desire O(N) behavior. float x_min = __FLT_MAX__, y_min = __FLT_MAX__; float width...
It seems to work only with pairs. This is not correct. std::minmax_element works with any forward iterators. Also it takes a comparator that lets you define how to compare the elements. You could write: auto minmax_x = std::minmax_element(blocks.begin(),blocks.end(), [](cosnt Block& a, const Block& ...
63,594,363
63,596,182
Is there a way to convert Armadillo vector to a string in C++?
I was wondering if there is a way to convert an Armadillo vector to a std string. For example if I have this vector: arma::vec myvec("1 2 3"); //create a vector of length 3 How can I produce: std::string mystring("1 2 3"); from it?
Use a combination of ostringstream, .raw_print(), .st(), .substr(), as below. // vec is a column vector, or use rowvec to declare a row vector arma::vec myvec("1.2 2.3 3.4"); std::ostringstream ss; // .st() to transpose column vector into row vector myvec.st().raw_print(ss); // get string version of vector with ...
63,594,465
63,597,249
How to draw the outline of a thick line?
I want to draw the outline of a thick line, that was drawn with a geometric pen. The line can be a polygon or a curve, but for simplicity I'm using a straight line. Given two POINT variables A and B, the following code draws a black 16-pixel wide line with round endcaps between A and B: LOGBRUSH lb = {BS_SOLID, clBlac...
Use WidenPath after defining the path: The WidenPath function redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the given device context.
63,594,555
63,594,702
Max and Min is coming out as true instead of a number, what do I do?
I need the minimum and maximum number out of an array but it is telling me that the address of function will always come out to true instead of a number. I can't figure out what to change. #include <iostream> using namespace std; int main() { double num1[10] {0.61, 1.70, 0.52, 1.34, 0.25, 1.20, 0.46, 1.10, 1.68,...
You are not printing a maximum here, you are printing a function pointer which is implicitly converted to bool. It is never nullptr, so it is true. // These two lines are actually forward-declarations of two functions // called max1 and min1. double max1(double num1); double min1(double num1); cout << "Maximum is " <<...
63,594,614
63,594,756
Generic Eigen Matrix/Vector object transfer to a custom matrix/vector container
So I have a custom made matrix/vector container (denoted MyContainer for simplicity) suited to a special purpose, and want to implement functionality for transferring the data of Eigen objects (Matrices, fixed, dynamic etc..) to my custom container. Thus I want to create a function similar to (illustrated with Eigen::M...
It should be as simple as changing the definition to this: template<class T, typename TEigenType> void assign_eigen_object(MyContainer<T> &lhs, const TEigenType &rhs) { ... However, with the correct memory layout of MyContainer, you may be able to do even better and replace the nested loops with a single std::copy. E...
63,595,389
63,596,506
How would you design a function that attaches children of a Component class to an Object class if the components can hold different data?
In my program, I have an Object class to which we can attach components that all derive from a base Component class. Since a component can have data that are initialized through it's constructor, when we call Object::addComponent() we need to pass the data for this particular component #include <vector> class Componen...
Here is a possible solution. Note the use of std::unique_ptr instead of regular c-pointers. #include <memory> #include <vector> struct Component{}; class Object { public: Object() {} template <typename TDerivedComponent, typename... TArgs> TDerivedComponent * addComponent(TArgs&&... args){ au...
63,595,572
63,600,183
Howard Hinnant's date library: Only load part of the IANA Time Zone Database
I'm working on an embedded system with limited RAM. Also, the used toolchain currently supports C++17 at the most. I have to convert UTC timestamps to local time stamps for displaying data to the user. The time zone that is supposed to be used is retrieved from another system. This all works excellently with Howard Hin...
Caution: These tips have not been tested recently! 1. Temporal Window src/tz.cpp has: // These can be used to reduce the range of the database to save memory CONSTDATA auto min_year = date::year::min(); CONSTDATA auto max_year = date::year::max(); The idea when I wrote this 5 years ago was that you could set min_year...
63,595,622
63,596,398
My code to find all pairs of numbers such that x^y > y^x producing the wrong output
The problem is: given two arrays of positive integers of lengths m and n find all pairs of (x, y) such that x^y > y^x. (Raising the left operand to the power of the right) I have followed the following logic: if x = 1 then no ordered pairs satisfies the conditions. if y = 1 and x != 1, the condition is satisfied for...
You're counting both (2, 4) and (2, 3), since those cases end up in the last condition. The simplest way to treat them as exceptions is to make sure that you handle all "2 cases" at once: if (a[i] == 2) if (b[j] >= 5) count++; or if (a[i] == 2) count += b[j] >= 5; When your code is supposed to mak...
63,596,125
63,607,745
Why does the different order of mutexes for std::scoped_lock affects performance?
Note: this is not a practical problem(I have never locked more than 2 mutexes with scoped_lock), I am mostly curious why implementations of scoped_lock apparently have a relatively big performance hit when locking mutexes in different order. Example code below, godbolt link. #include<mutex> #include<thread> #include<ch...
As others have stated, it is tied to the implementation. But the implementation can do better than gcc's persistent implementation of trying the same thing over and over again. Peristent Lock the first lock and then try_lock the rest. If any of the try_locks fail, unlock everything and try again. This algorithm wor...
63,596,395
63,597,747
How to do bit-wise AND between multi-dimensional arrays using armadillo in C++?
My task is to rewrite the codes is_valid = (DoG == DoG_max) & (DoG >= threshold); in matlab using armadillo with C++. The DoG and DoG_max are multidimensional arrays with the same size 907 x 1210 x 5, and the threshold is a scalar. According to the documentation of armadillo, the bit-wise equal operator == is built-in ...
The && operator is implemented in Armadillo, but strangely it's not documented. Try this as a translation of your Matlab code: ucube is_valid = (DoG == DoG_max) && (DoG >= threshold); In case you want a scalar output, try this: bool is_valid = all(vectorise((DoG == DoG_max) && (DoG >= threshold))); There is some conf...
63,597,142
63,597,194
Number pattern in C++
I want to print a number pattern: 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 ... 10 . .. . . This is my code: #include <iostream> #include <conio.h> using namespace std; int main() { int cols, row, num=1; for(row=1; row<=10; row++) { for(cols = row; cols <= row*10; cols = cols + row) { ...
To make that pattern you only really need the number of rows. The number of columns in each row happens to be equal to the row number, and the values are integer-multipliers of that row number. #include <iostream> int main() { const int rows = 10; for (int row = 1; row <= rows; ++row) { for (int co...
63,597,495
63,597,782
"Lambdas are cheap" - Really? Under what circumstances?
This article declares using C++ Lambdas to be "cheap": Lambdas aren't magic - part 2 They demonstrate how to pass lambdas to existing std functions / templates. One article demonstrates how to use "auto" as return type of a function to return a lambda without using std::function. No article I saw demonstrates making yo...
Lambdas are just objects that overload operator(). You can conceptually think of them as equivalent to: class Lamba { public: auto operator()(...) const { /* ... */ } }; So, they are no more expensive than a similar function call. std::function is not necessary to use lambdas. You can use type deduction to store/p...
63,597,934
63,598,442
Handling an error condition in the compare function of std::qsort
I am trying to figure out a way for qsort to throw an exception or indicate an error condition if the compare function finds that the elements are, for some reason, invalid for sorting. For example, in this compare function, I need to indicate an error condition that my sorting is invalid if the return value of some_fu...
C++ allows you to throw whatever you need, not only exceptions but also other types, you could do something like throw an int if it suits your purposes and catch where you call the function with a try-catch block. For what you need I think you can use STL exception library: Demostrative example: #include <iostream> #in...
63,598,209
63,598,412
Will a modern C++ compiler optimize away false constexpr conditionals?
All throughout my code I have debugging conditionals in the form of: if (Globals::DEBUG_MODE) std::cout << "debugging info" << std::endl; DEBUG_MODE is a constexpr bool in a global constants header file. My question is, when I get ready to release my software and I do some final optimizations, can I just turn that DEB...
If by discard, you mean remove from the final output binary, yes, most compilers will do that optimization (Dead code elimination) for if and better yet, if constexpr. Do verify that with your compiler-generated asm if you want to be sure. However, if you're planning on having code that will not compile in release mode...
63,598,840
63,599,389
C++ - Windows - catch process exit from Task Manager
I need to stop a service when our program has been killed with the task manager. I tried with std::signal(...) and _onexit(...) but it does not work. I tried running ProcessMonitor so check a sort of signal I can catch, but I did not find one. I tried with a: auto serviceStopThread = QThread::create([](){ :...
While the process is still alive, find the PID, and open it with OpenProcess. You’ll need at least SYNCHRONIZE permission. Then wait for the handle to become signaled. For example, you can launch a new thread, and call WaitForSingleObject with INFINITE timeout. The handle becomes signaled as soon as the process quits, ...
63,598,984
63,599,895
Random and replacement characters in c++ output
I am writing a program to reverse a string and insert random characters in between. Here is my code: main.cpp #include <iostream> #include <chrono> #include <thread> #include "encrypter.cpp" using namespace std; int main(int argc, char *argv[]) { char message[256]; this_thread::sleep_for(chrono::milliseconds(1000)...
You have missed two important things: when you declare an array it's values are not defined (whatever is in memory) strlen counts to the first occurance of '\0' character In order for your code to work you must initialize char arrays, which means change those two lines: char strreved[256]; char strenc[1024]; to: cha...
63,599,073
63,599,209
Copy struct to array with const values
I'm trying to replace a struct value that has a const value in a non const array but it fails to compile with: Object of type 'Foo' cannot be assigned because its copy assignment operator is implicitly deleted Here is an example: struct Foo { const int id; int value; Foo(): id(-1), value(-1) {} Foo(int ...
C++ treats const very strictly. Copying such a struct will be painful if possible at all (without UB). Perhaps what you are really looking for is "readonly" instead? In that case you can make fields private with public getters/setters: struct Foo { public: Foo(): id(-1), value(-1) {} Foo(int id): id...
63,599,636
63,599,861
Algorithm for the cube root Find in C++
Iam Beginner in programming and i have a question. how make algorithm for cube root finding in C++ without using functions like pow(). The user enters the number and the number of decimal places. My code: My do while isn't working double number; cout << "Enter number = "; cin >> number; int x; int y = number / 3.; int ...
Your algorithm is nearly fine. You just need to change your variables to float/double. Here is the edited code : #include <iomanip> #include <iostream> #include <limits> using namespace std; int main() { double number; cout << "Enter number = "; cin >> number; double x; double y = number / 3.; ...
63,599,794
63,599,889
Why this program is not able to merge 2 Linked List in Sorted order?
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* temp = l1; w...
In your while loop, you always assume that a->next is not null because you call a->next->next. However, a->next will be null when a points to the last element in the list. Also, you appear to be trying to implement bubble sort, but that requires multiple iterations of the list to work properly. The input 10->20->30, 1-...
63,600,072
63,600,321
c++ Template specialization with derived class
I am having problems trying to specialize a template method of a class to accept a derived class. I've tried with pointers as well and end up with many more issues than this iteration. #include <iostream> using namespace std; class Json { public: Json(){} virtual ~Json(){} template <class T> bool Ge...
That's not how templates work. Template deduction is always on the exact type, in this case JsonError, so the specialization for Json& is not matched. If you still want to make it work, you can overload the template function with a member function taking Json&. The template function will still be a better match for a d...
63,600,246
63,600,263
Polymorphism C++: field of base pointer not using value given by derived class constructor
I'm running into an issue with this code (it's a simplified version from a personal project): #include <iostream> class Piece { public: Piece() : art('=') {}; char art; }; class Pawn : public Piece { public: Pawn() : art('p') {}; char art; }; int main() { Piece* piece = new Pawn; // piece->art ...
You need to call the base class constructor like this: class Pawn : public Piece { public: Pawn() : Piece('p') {} // ^^^^^ not 'art' }; See the reference for member initializer lists, which explains how this works. If you have a std::vector<Piece*> it can store pointers to objects to derived types, such...
63,600,627
63,601,571
Segmentation fault in vector of vector
I am practicing a dynamic programming problem called the gold mine problem on GeeksForGeeks My code #include <iostream> #include<vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int test,i,max_rows,max_columns,temp; cin >> test; for(i=1;i<=test;i++) { ...
else if(row==0) add = max(v[row][column+1], v[row+1][column+1]); The problem specification clearly states that it is perfectly valid to have only one row. But this code assumes that there are at least two rows. This can (and likely will) crash if the input is 1 1 3 1 2 3, which is p...
63,600,709
63,630,051
How to monitor a CAN signal continuously using CAPL?
There is a signal named 'A' which counts from 0 to 20 of a specified occurrence. The signal will reset to 0 after it counts 20. The time interval between each occurrence is 20 ms. I need to monitor this signal A for 200 times. Whenever the counter skips a value ,say for example: 0,1,4,5..20 ,I need to to store that par...
When running in a test node there are several methods available for reacting on signals. Their names all start with testWaitForSignal. You can simply check CANoe's documentation for details. For your particular use case, you could use testWaitForSignalMatch(<signal>, <expectedValue>, 20) The call will return latest af...
63,600,714
63,602,683
How to build BLAS and LAPACK for use in C++ on Linux cluster?
I have a large computational problem I am working on. To decrease the computation speed of a set of linear equations in a square matrix, I have made use of lapack and blas. To get the libraries on my laptop (Ubuntu 2020) I ran the following command sudo apt-get install libblas-dev liblapack-dev Then I linked the code ...
BLAS Download the latest version of BLAS Open a terminal and go to the directory where you have it saved tar -xvf blas-3.8.0.tgz # unzip the blas source files cd BLAS-3.8.0/ make mv blas_LINUX.a libblas.a mv *.a path/to/lib # move the blas lib to the library you will be including at compile LAPACK Download t...
63,600,776
63,748,417
C++/CUDA weird behavior with large arrays
I try to implement some sort of an Jacobi Algorithm and measure the time taken for different grid sizes. For having the same amount of Iterations, regardless, how large the grid is, I don't use some sort of residuum, but let the Algorithm run 4000 Iterations always (but with different size of the arrays). That works ex...
In CUDA, when specifying the kernel execution configuration arguments, the grid configuration comes first, followed by the block configuration. Therefore, given the definition and usage of the variables dimGrid and dimBlock, this is incorrect: Jacobi<<<dimBlock, dimGrid>>> it should be: Jacobi<<<dimGrid, dimB...
63,601,103
63,601,208
error - 'expected primary expression before...' in function definition (C++)
Trying to run this in an online compiler I get the error - 'expected primary expression before '.' ' in function definition on all 4 structure members: height, width, length, volume. In Visual studio the error is ' 'box' illegal use of this type as an expression. What could be the cause? #include <iostream> using name...
In the display function you have to change box, which is the type, with amazon, which is the object void display(box amazon) { cout<<"Box height: "<<amazon.height; cout<<"Box width: "<<amazon.width<<"Box length: "<<amazon.length<<"Box volume: "<<amazon.volume; }
63,601,328
63,601,819
Why do STD implementations of mt19937 have double sizeof as boost version?
I have this simple C++ program with unexpected output: #include<random> #include<iostream> #include "boost/random/mersenne_twister.hpp" #include "boost/random/uniform_int_distribution.hpp" int main(){ std::cout << sizeof(std::mt19937) << std::endl; std::cout << sizeof(std::mt19937_64) << std::endl; std::co...
This is the standard definition: mersenne_twister_engine< uint_fast32_t, // element of the buffer 32, 624, // size of the buffer 397, 31, 0x9908b0df, 11, 0xffffffff, 7, 0x9d2c5680, 15, 0xefc60000, 18, 1812433253> The issue is that GNU chose that std::uint_fast32_t is a 64 bit...
63,601,379
65,441,454
Erroneous Results with random two state benchmark
I ran this code for a preliminary benchmark, which compares the time taken to generate a certain number of random states using the scale a double random value and using a Bernoulli distribution. The code is below: int main() { std::random_device s; std::mt19937 engine(s()); std::bernoulli_distribution bernp50(0...
Resolved: I actually used long int for the counters as well, but the problem was with the loop range iterator which was a 4-byte integer. The loop was actually messing up.
63,601,477
63,601,567
typecasting of pointers in cpp
Can anybody tell me what's going on with the following code: int compareX(const void* a, const void* b) { Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->x - p2->x); } I have taken this code from geeks for geeks, the closest pair of points. can anyone explain to me the similar code in a much si...
FLT_MAX is a constant defined here and the logic if used to find the Point with the lowest distance between all the pair of points in the array, the idea of setting the variable min with a FLT_MAX is to define a threshold limit value that can be exceeded by the 1st comparison of the 1st 2 Points...
63,601,496
63,603,158
Linking Boost Thread: No rule to make target ".../libpthread.so"
I am trying to cross-compile a project on my Linux Ubuntu 18.04 WSL for the Raspberry Pi. I have installed the toolchain via sudo apt install gcc-arm-linux-gnueabihf, so it's located unter /usr/bin/. Now in my CMake File I've set the following: set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR arm) s...
Okay, I have found my mistake, thanks to @squareskittles. When I used rsync to copy the root file system of my Raspberry Pi to my WSL, it "broke" all the links. So in this case /usr/lib/arm-linux-gnueabihf/libpthread.so pointed to the absolute path of the library, namely /lib/arm-linux-gnueabihf/libpthread.so.0. Howeve...