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,350,518
63,606,351
How can i translate SecCertificateRef cert object to openssl's x509 certificate object in C++
i've a SecCertificateRef cert. I need to get Expiry date from it in C++. I've found this SecCertificateRef: How to get the certificate information? but it seems like it does it for swift. Closest equivalent I thought I can do in c++ is : CFDataRef data = SecCertificateCopyData(cert); const unsigned char *certificateDa...
in C++ you can get byte pointer from Apple's API and pass it d2i_X509 , CFDataRef data = SecCertificateCopyData(cert); auto dataBufferPointer = CFDataGetBytePtr(data); X509 *certificateX509 = d2i_X509(NULL, &dataBufferPointer, CFDataGetLength(data));
63,350,848
63,351,104
Is there any way to optimize c++ string += operator?
English is not good, but please understand. string str; string str_base = "user name = "; string str_user_input; string str_system_message; ... str = str_base + str_user_input + "\n [system message :]" + str_system_message; cout << str << endl; I'm using the existing code like this, is there a way to optimize string...
Your question says +=, but you're not using += anywhere. You are using only +. "+" is probably the most efficient way to concatenate strings. There are other ways, but it is unlikely that + is worse. As John Bollinger said, If all you need to do is output the concatenated result, then output the pieces directly: cout <...
63,351,363
63,351,410
Compose initialize class in c++
I'm not sure if this is called compose initialization.Basically what I want to know is: How the objects foo in main is initialized Are there some rules for this kind of initialization because I found it failed sometimes. Given the following code: #include <iostream> #include <string> #include <vector> class Base { p...
This is aggregate initialization, Foo is an aggregate type. Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list. Given Foo foo1{{"base2", 2}, 1, 2, 3,...
63,351,768
63,352,033
How a local variable can be taken in this C++ lambda expression?
In the following code: #include "Simple_window.h" #include "Graph.h" int fac(int n) // factorial(n); n! { int r = 1; while(n>1) { r *= n; --n; } return r; } double term(double x,int n) { return pow(x,n)/fac(n); } double expe(double x,int n) // sum of n terms for x { double sum = 0...
Your post is not close to a Minimal Reproducible Example Here is an example for Minimal Reproducible Example. In Graph.h Function takes a variable of Fct. Where Fct is typedef double Fct(double);. According to this post, lambda expression doesn't translate to function automatically, unless it doesn't create closure obj...
63,351,837
63,351,945
Overloading insertion << operator
Hello I am trying to overload the insertion operator but there is an error in my compiler when initializing it. In the .h file class Zfraction{ public: friend std::ostream& operator<<(std::ostream& display, Zfraction const& b); } in the .cpp std::ostream& Zfraction::operator<<(std::ostream &display, Zfraction const& b...
The header in the .cpp file is wrong. By using the scope resolution operator, ::, you're indicating that the operator that you're overloading is a member function of the Zfraction class. This is not true. Although friend declarations must take place inside of the class that they are establishing friendship with, they a...
63,351,841
63,352,041
Why does GCC delete my code on O3 but not on O0?
Recently i have been trying to learn about rvalues and perfect forwarding. While playing around with some constructs i came across some peculiar behavior while switching compilers and optimization levels. Compiling the same code on GCC with no optimization turned on would yield expected results, however turning on any ...
Why does GCC delete my code on O3 Because GCC is very smart, figures out that your program doesn't depend on any runtime input, and thus optimises it to constant output at compile time. just cannot figure out what exactly is going wrong and whats causing the discrepancy between the two compilers. The behaviour of t...
63,352,132
63,353,445
dynamic array in modern C++
For a performance oriented library, we currently employ std::arrays, whose length are depending on the problem. As a result, the whole code is templated with <int N1, int N2>, where N_1,N_2 are the unrelated length of the arrays being used, leading to long and memory intensive compilation, for probably little performan...
If allocations in your code are performed ones, startup time of the application doesn't matter, and the size of the biggest size of the vector are known, than maybe a simple solution with std::vector and reserve will do. But it seems what you need is a kind of Small String Optimization (SSO) that is used for std::strin...
63,352,544
63,353,740
How do I save recoded data?
I want to save the received recoded data to another file so that it can be decoded back. But for now I want to encode a jpg image to the same jpg format without changing the ascii code As a result, I want to get the same image even though it was passed through encoding and saved separately. here's my code: static const...
So I'm not clear why you can't figure out the file output operations when you clearly have the file input operations. But anyway here is the code std::ifstream in("test.jpg", std::ios::binary); std::ofstream out("test.jpg.out", std::ios::binary); for (unsigned char c; in.get((char&)c);) { std::cout << (int)ascii_en...
63,352,911
63,353,004
Why are global and static objects stored in the section of bss
I'm studying the sections of a binary file. I used the c++ code below: // test.cpp struct Test { int i; Test(int ii) : i(ii) {} Test() {} }; Test t0{5}; Test t1 = Test(5); Test t2; static Test t3; static Test t4{5}; int i = 1; int j; static int k; static int l = 1; int main() { return 0; } I compil...
.data is only used for variables that are initialized with literal data. The Test objects are initialized using the constructor method. So the memory is allocated in bss, then during startup the constructor is called to fill in the contents.
63,353,157
63,353,256
printing global variable in local block
#include <iostream> using namespace std; int x=15; int main() { int x=10; { int x = 5; cout<<::x; // should print 10; } return 0; } Is there any way to print x=10 without changing variable names, variable values and position of cout?
I assume this is an academic question (puzzle) because nobody should write code like that. In the same spirit, here's a way to make it print 10 instead of 15 without changing variable names, variable values and the position of cout: #include <iostream> using namespace std; int x=15; int main() { int x=10; { ...
63,353,242
63,353,776
shared_ptr is getting deleted early
I modified the code used in @Timo's answer to try to understand how shared_ptr and custom deleter works. Here is the link to new code, or right here: #include <memory> #include <vector> #include <iostream> #include <string> class TopicPointer { public: TopicPointer(int x) : _x(std::move(x)) { } ...
I see the problem here: std::unique_ptr<Topic>&& createTopic(std::string name, int y) { auto topicPtr = new TopicPointer(y); return std::move(std::unique_ptr<Topic>(new Topic(move(name),std::shared_ptr<TopicPointer>(topicPtr, Deleter())))); } You are returning the reference to the temporary object that wou...
63,353,626
63,353,986
QHash behaving different in different qt version
I am compiling below code in QT version 4.8 as well as in 5.12.9 . QHash<QString, int> m_userDataHash; m_userDataHash.insert("white", 1); m_userDataHash.insert("yellow", 3); m_userDataHash.insert("lightblue", 5); m_userDataHash.insert("darkblue", 7); m_userDataHash.insert("pink", 9); m_userDataHash.insert("red", 11); m...
QT documentation states that: When iterating over a QMap, the items are always sorted by key. With QHash, the items are arbitrarily ordered. That is an expected behavior for a hash function. They do not store items in any order, but instead you can get any item fast enough O(1). Maps store the keys the tree, you can ...
63,354,135
63,354,176
What is the meaning of (*) in template<typename T> using L = T(*)(T);?
I've been using this snippet of code for some testing and I understand what it does but it just occured to me I have no idea what (*) is supposed to do in this situation... template<typename T> using L = T(*)(T); I've tried removing it and the code runs perfectly fine without it. I think it might have something to do...
Yes, it's a pointer type. T(*)(T) is a pointer to function T(T), which takes T and returns T. Without it, i.e. T(T) is a function type. You said it works too, because in many cases it could decay to pointer to function as T(*)(T). For example, if you define T(T) as the function parameter type, which would be adjusted t...
63,354,157
63,354,393
Reading bits from the bin value
What is the order one has to read the bits from the bin value? Having for e.g. this official MS doc site regarding the lParam of the WM_CHAR message, they explain what bits have what meaning. Taking the bits 16-23 for the scan code value should I read the bits from right to left or vice versa?
The page you linked to uses LSB 0 bit numbering so you can extract bits 16-23 with lParam & 0b00000000111111110000000000000000U // | | | | // bit 31 23 16 0 // MSB LSB Note: The 0b prefix for binary numbers requires C++14. In ...
63,354,933
63,355,327
error: non-member function ‘int indice_max(const std::vector<double>&)’ cannot have cv-qualifier
I have an the error "cannot have a cv qualifier" for the function indice_max and I don't understand why, I don't modify at any time the vector v #include <iostream> #include <vector> #include <algorithm> using std::vector; int indice_max(const vector<double> & v) const{ int indice =0; double max = v[0]; f...
The const qualifier (after the function signature) is used when the class member-function promises not to change any previously assigned value to a data member. In the given code, there's no class and its private data members. Thus, there's no meaning of using it in this case and a type qualifier isn't allowed on a non...
63,355,199
63,364,180
Why are x86-64 C/C++ compilers not generating more efficient assembly for this code?
Consider the following declaration of local variables: bool a{false}; bool b{false}; bool c{false}; bool d{false}; bool e{false}; bool f{false}; bool g{false}; bool h{false}; in x86-64 architectures, I'd expect the optimizer to reduce the initialization of those variables to something like mov qword ptr [rsp], 0. But ...
Compilers are dumb, this is a missed-optimization. mov qword ptr [rsp], 0 would be optimal. Store forwarding from a qword store to a byte reload of any individual byte is efficient on modern CPUs. (https://blog.stuffedcow.net/2014/01/x86-memory-disambiguation/) (Or even better, push 0 instead of sub rsp, 8 + mov, al...
63,355,617
63,355,870
Using a user defined class vector inside the class file
I have a class called Account with below parameters: Account::Account(string ibanCode, string paramOwner, double amount) {} I have created a vector consisting of class Accounts inside main function: accs.push_back(Account(fullName, iban, value)); I want to write a function to print all the Account values in my vector...
I think making it a member would be extremely complicated, the best option should be using a normal function that can access the parameters. #include <iostream> #include <vector> using namespace std; struct Account { Account (string ibanCode, string paramOwner, double amount) : _amount...
63,355,635
63,360,235
A post-increment operator that allows one to increment at a specified step
Which is worse? Creating copies #include <vector> #include <algorithm> template<class T> std::vector<T> range(const T start, const T stop, const T step) { int leaps = ((stop-start)/step); std::vector<T> output(leaps > 0 ? leaps : -leaps); std::generate(output.begin(), output.end(), [i = start, step] () muta...
In C++20, I'd write it lazily: template <class T> auto range(const T start, const T stop, const T step) { return views::iota(0) | views::transform([=](int i) -> T{ return i * step + start; }) | views::take_while([=](T cur){ return cur < stop; });...
63,356,135
63,368,968
Getting system language UWP C++/WinRT
I wanted to get the system language (not the input language, but the overall system language) in the C++/WinRT app, but can't find a way for doing such. I googled and found that in Unity this can be done using System.Globalization.CultureInfo.CurrentCulture structure, which is not available in C++ code. Anybody's famil...
Getting system language UWP C++/WinRT You can use the Language Class to get the system language. First, you need to include the header files it needs. For example: #include <winrt/Windows.System.UserProfile.h> #include <winrt/Windows.Globalization.h> void MainPage::ClickHandler(IInspectable const&, RoutedEventArgs...
63,356,376
63,356,756
Why does lambda capture by reference is still working with dangling references?
To my surprise, the following C++ program: #include <iostream> #include <functional> int main() { std::function<void(void)> f; { int x = 1; f = [&x]() { std::cout << x; }; } //std::cout << x; // error: use of undeclared identifier 'x' f(); // no error! return 0; ...
Why does lambda capture by reference is still working with dangling references? This is undefined behaviour so there can be any reason for why it is working the way it is working. If you compile the code with: Try here: https://godbolt.org/z/5dd5sM clang++ -O3 -fsanitize=address You will immediately get: ERROR: Addr...
63,356,378
63,368,993
How to generate the respective protobuf files in Visual Studio during the compilation process automatically?
I have several protobuf messages in a folder which I'd like to automatically convert into the respective header/cc files and then continue the compilation process inside of Visual Studio. The best solution that I could comeup sofar was to define a Pre-Build Event through Propertise>Build Events>Pre-Build Event and spec...
I suggest you could refer to the following steps: 1,Modify the properties of the .proto file:Item Type:Custom Build Tool 2,Configure project properties: Properties -> Custom Build Tools -> General command line:$(SolutionDir)Dependencies\include\protobuf\bin\protoc.exe --proto_path= .\proto %(Filename).proto --cpp_out=$...
63,356,443
63,357,322
c++ : Is there a faster way to get the intersection of map/unordered_map?
Is there a faster way to the following in c++, so that i can outperform the python's implementation? Get intersection of two map/unordered_map keys For these intersected keys, compute the pairwise difference between elements of their respective set/unordered_set Some info that might be useful: hash_DICT1 has about O(1...
You do a lot of copying where you should be using const&. You don't save search results. You should use find instead of count and then use the result. push_back to a vector may be made faster by reserve()ing the number of elements you need to store if you know the number in advance. Fixing these issues could result i...
63,357,023
63,357,232
Print double data type with a precision upto 4 decimal places - Armadillo
I am trying to use the armadillo library in c++ to do the following. Whenever I print out a matrix (arma::mat), it is always printed in the following form:- 1.0594e+03 1.0439e+04 0.3425e+04 1.0232e+03 12.0319e+04 0.1225e+04 11.5044e+03 1.231e+04 0.3424e+04 I wanted to know if there was a way to remove the e...
A bit of googeling takes me to http://arma.sourceforge.net/docs.html#raw_print which says: Similar to the .print() member function, with the difference that no formatting of the output is done; the stream's parameters such as precision, cell width, etc. can be set manually And shows this example: mat A = randu<mat>(5...
63,357,498
63,576,259
Using keyword in a C++ interface declaration
I'm porting Direct2D d2d1_1.h header file to Delphi and I'm stuck with a declaration. I don't understand clearly (Line 1522 in d2d_1.h): interface DX_DECLARE_INTERFACE("e8f7fe7a-191c-466d-ad95-975678bda998") ID2D1DeviceContext : public ID2D1RenderTarget { STDMETHOD(CreateBitmap)( D2D1_SIZE_U size, ...
When porting from C++ to Delphi, the methods declared with "using" keyword must simply be ignored.
63,357,637
63,359,656
Compilation error when trying to remove adjacent duplicates from a template typelist
The result that i am trying to achieve is: removeduplicates<TMPArray<8, 8, 9, 9, 10, 11, 11>>::type results in the same type as TMPArray<8, 9, 10, 11> So far my solution looks like this: template<int... I> struct TMPArray {}; template <typename Arr1, typename Arr2> struct concat; template <int Ts, int... Us> struct ...
The problem I see is that, in three points of your code, you have to add a typename to say the compiler that whats follows is a typename. I hope this answer can explain why. You have to add two typename here template<int Head, int Sec, int Third, int... Tail> struct makeremoveduplicates<false, TMPArray<Head, Sec, Third...
63,357,996
63,366,532
Does capture by reference turn into capture by value when the reference goes out of context in Javascript?
The following Javascript program: function f() { function g() { console.log(x); } let x = 0; g(); // prints 0 x = 1; g(); // prints 1 return g; } let g = f(); g(); // prints 1 outputs: 0 1 1 So it seems that g first captures x by reference (since inside f, g() prints 0 then 1 when x is rebound), which...
In short You are almost correct except for how it works when it goes out of scope. More details How are variables "captured" in JavaScript? JavaScript uses lexical environments to determine which function uses which variable. Lexical environments are represented by environment records. In your case: there is a global ...
63,358,192
63,358,398
QT gives error when I try to initialize QSerialPort outside the mainwindow.cpp
I am trying to make an USB communication in QT. But when I write the codes: #include "usb.h" #include "mainwindow.h" #include <QtSerialPort> #include <QSerialPortInfo> #include <QtSerialPort/QSerialPortInfo> #include <QtSerialPort/QSerialPortInfo> #include <QSerialPort> USB::USB() { QSerialPort *serial; seria...
You should declare the USB class as follows: class USB : public QObject { Q_OBJECT public: USB() : serial(new QSerialPort(this)) {} private: QSerialPort *serial; };
63,358,220
63,358,352
why Is it possible to use std::thread without #include thread in c++?
I tried the following code from https://en.cppreference.com/w/cpp/thread/get_id in visual studio, and noticed it runs even without #include thread, but not without #include mutex (after commenting out the lines where it is used): #include <iostream> #include <thread> #include <chrono> #include <mutex> std::mutex g_di...
One of the headers in your compiler's standard library is internally including a header that defines std::thread (in your case, <mutex> is including this). The C++ standard only guarantees which definitions will be visible for any #included header -- but it does not control or prevent the implementation from either int...
63,358,696
63,358,877
QStrings isNull out of QSettings is wrong
I notice that QSettings is not able to store the isNull property of a QString. In other cases (QTime) the QSettings works as expected. Do I something wrong? #include <QTime> #include <QString> #include <QSettings> #include <iostream> int main(int argc, char *argv[]) { QString str; QTime time; std::cout << "...
Note from the documentation: "Qt makes a distinction between null strings and empty strings for historical reasons." I would assume it is better not to rely on this distinction. Instead of setting a null string you would be better off to not set the option at all (or explicitely unset it). The practical reason for QSet...
63,358,947
63,359,040
How to search for const pointer in a collection of non-const pointers?
I have a member variable std::set<T*> m_associates;, i.e., a collection of non-const raw pointers, and simply want to check for existence of another pointer. To maintain const correctness my function looks like this: bool MyClass::is_associated(const T* x) const { return (m_associates.find(x) != m_associates.end())...
The reason your current code fails is that the default Compare for std::set<T> is std::less<T>; which forces both arguments to be a T for comparison -- in this case, non-const T* types. Since const T* cannot be converted to T* without casting away the constness, this is causing your compile errors. If you are using C++...
63,359,274
63,359,506
defining operator + for double and string data types in cpp
I am trying to define operator + for string and double using the following function string operator + (const double& b,const string a){ return to_string(b)+a; } When I am doing the following operation, it works well double c = 100.256; string d = "if only"; cout<<c+d<<"\n"; but when i pass const char instead of s...
According to the C++ 17 Standard (16.3.1.2 Operators in expressions) 1 If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 8. In this expression c+"sff" (where c is a scalar value of the type...
63,359,348
63,359,550
Using QProcess with only arguments
I am trying to compile another .cpp code with QProcess. I use this code in my program. QStringList arguments; arguments << "g++"; arguments << "-o"; arguments << QDir::toNativeSeparators(exePath); //path and exe path to future .exe arguments << QDir::toNativeSeparators(mainPath); // path to main.cpp QProcess proces...
I dont want to set program as I can see you want to use g++ and that one is the program so QStringList arguments; arguments << "-o"; arguments << QDir::toNativeSeparators(exePath); //path and exe path to future .exe arguments << QDir::toNativeSeparators(mainPath); // path to main.cpp QProcess process; process.s...
63,359,359
63,359,684
Ambiguous call when inheriting multiple times from generic base class
I want to clone a data structure containing std::lists of several types and simultaneously move some iterators to point to the new std::list's elements. For this, I created a generic type Translate<T> represents the mapping from std::list<T>::iterators in the old list to those in the new list. I then have a new class i...
This code is ill-formed. If the operator() is not available in the derived class, then name lookup only considers the base class if there is exactly one base class. If there are multiple base classes, then none of the base classes are considered in name lookup. As you've mentioned, you can copy the implementations of o...
63,360,248
63,360,383
Where is std::future::then() and the concurrency TS?
When seaching for std::future::then on google, the top result is a stackoverflow question about the status of the function in c++17. Now that c++20 has been finalized and Clang and GCC is well into implementing c++20, I am left wondering what is the status of the function and the Concurrency TS generally? It isn't ment...
Has the Concurrency TS been dropped? Yes. P1445 discusses this, SG1 voted to withdraw the TS. Note that atomic smart pointers, latches, and barriers are in C++20. As far as improving future goes, the direction there is called executors and the design currently being iterated on is P0443, which allows for lazy composi...
63,360,817
63,360,927
Computing fibonacci in c++ function and throwing compile-time error
I need to write this function fibo. If the number is too big it should be shown as compile error (the last line of main function) The main function should stay like it is. Any suggestions? #include <iostream> int fibo(int n) { if (n <= 1) return n; //if (n>=300) throws ... ? return fibo(n - 1) + fi...
You can make fibo a constexpr function, and then throw if the argument is invalid. The throw in a constexpr function will lead to a compile time error if fibo is evaluated at compile time, and a run time error otherwise: constexpr int fibo(int n) { if (n >= 300) throw; if (n <= 1) return n; return fibo(n-1...
63,361,240
63,361,582
convert std::u16string to NSString
In my Native Library I used to have this function to return a NSString out of a std::string: - (NSString*)return_my_cpp_string { NSString* result = [NSString stringWithCString:my_cpp_string.c_str() encoding:[NSString defaultCStringEncoding]]; return result; } I now need to update this function so that it rathe...
Use stringWithCharacters:length instead of stringWithCString:encoding. stringWithCharacters takes a pointer to a C-style array of UTF-16 code units as input. std::u16string is a UTF-16 encoded string, so you can use its data as-is, eg: - (NSString*)return_my_cpp_string { const unichar *pchars = (const unichar *) my...
63,361,338
63,361,640
Trouble understanding the memory allocation of two seperate struct pointers of same type. Works in one example but not the other
I'm having real difficulty understanding what is going on with memory allocation two specific scenarios that are producing different result but functionally appear identical to me when applying my naive wisdom. I created a simplified anologous code example below to demonstrate the issue I am encountering. I appreciate ...
The first version works by sheer misfortune. It's an Undefined Behaviour. In return_item_details you accept std::list by value, which means the list and all its elements are copied and will be destroyed once the function finishes. You then return address of one of those temporary elements and try to use it (but the ele...
63,361,580
63,362,856
Image selection region stretching to rectagle
Currently working on one issue, which is illustrated on represented image. On the left hand side source image is represented. I have selection region, which could be a polygon of 4 points. On the right hand side result of image cutting is represented. As it can be seen pixels appeared in selection region were stretche...
The process could be performed with Qt using the following functions: QTransform::squareToQuad: create the transformation matrix Creates a transformation matrix, trans, that maps a unit square to a four-sided polygon, quad. Returns true if the transformation is constructed or false if such a transformation does not ...
63,362,025
63,362,630
Is there any advantage if virtual destructor is not defined with shared_ptr
When we use shared_ptr with polymorphic classes we don't need virtual destructors due to type erased deleter. But does it makes sense to define a destructor in simple cases. What can be the advantages of not declaring a destructor at all? Consider the below code struct Base { ...
Yes, of course there are advantages to not having a virtual dtor even for a polymorphic type: Removed dynamic dispatch, allowing for more efficient static dispatch or even easy inlining. Making the compiler prove it and reduce dynamic to static dispatch on its own is non-trivial. Removed the entries for deallocating-...
63,362,053
63,362,136
Reversing a singly linked list in C++: pointer in the stack
I have a single linked list made up of Nodes, a class with 2 members: Node* next; int val; The list is as follows: [head:0] -> [1] -> [2] -> [3] -> nullptr I wrote a function to reverse this list. void reverseList(Node* head) { Node* m = head->next; head->next = nullptr; while (m) { Node* n = m; ...
I know that Node* n gets deleted once the While loop is exited, since n is allocated on the stack. But by setting head=n; shouldn't the memory that n points to still be in the heap even after the While loop is exited and hence head still points to valid memory? Pointers are just like variables, when it comes to passi...
63,362,155
63,362,801
Equivalence of find_if and bind2nd to lower_bound, upper_bound
I'm tasked with removing bind2nd from some code. I have a sorted (ascending, with possible duplicates) vector<double> m_x say, and a value x which is a double type. Are std::vector<double>::const_iterator it = std::find_if(m_x.begin(), m_x.end(), std::bind2nd(std::greater<double>(), x)); std::vector<double>::const_it...
Are std::vector<double>::const_iterator it = std::find_if(m_x.begin(), m_x.end(), std::bind2nd(std::greater<double>(), x)); std::vector<double>::const_iterator it = std::find_if(m_x.begin(), m_x.end(), std::bind2nd(std::greater_equal<double>(), x)); Equivalent to std::vector<double>::const_iterator it = std::uppe...
63,362,556
63,362,641
Correct way to validate the creation of multiple folders and files in C ++
I am working on a personal project, one of the first steps that my program executes is to create some folders and files when the user applies a command through the console. For example. The user executes the command emi -start through the console, this triggers the creation of the following files and folders: emi_base...
If fs::create_directory is std::filesystem::create_directory, then fs::create_directory(<path>) throws an exception if the directory cannot be created, you don't need to check its return value: The overload that does not take a std::error_code& parameter throws filesystem_error on underlying OS API errors, constructed...
63,362,701
63,362,875
Base64 implementation with bit shifting
I try to implement a base64 encoder. I have this algorithm: while (len--) { char_array_3[i++] = *(data++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 252) >> 2; //This line. char_array_4[1] = ((char_array_3[0] & 3) << 4) + ((char_array_3[1] & 240) >> 4); char_array_4[2] = ((...
May I remove the number 252, 3, 240 etc.? No, not all of them. In case of right shift and binary mask 252, 240 and 192 they are redundant and you can remove them. But 3 15 and 63 are not redundant, as you would propagate bits that you should not to.
63,363,017
63,363,132
Access violation when calling copied function
This is a program that copies a function onto the heap, sets it as executable and calls it. #include <iostream> #include <iomanip> #include <csignal> #include <Windows.h> using std::cout; #define RET 0xC3 void printBytes(void* start, uintptr_t numBytes) { std::ios_base::fmtflags savedFlags(cout.flags()); cout...
There is absolutely no reason to expect this to work. Whether or not anyone can think of a reason it wouldn't work, there is simply no reason to expect it to work. No standard or reference says that this should work, and expecting it to work is, to be blunt, crazy. As just the most obvious ways it can fail: What if an ...
63,363,036
63,363,792
why am i getting: "cannot seek vector iterator after end"
So I am trying to solve josephus problem using c++ First input is number of people and second is position for killing next person I am getting run-time error as: "cannot seek vector iterator after end" code: // josephus.cpp : This file contains the 'main' function. Program execution begins and ends there. #include <i...
The program has undefined behavior because according to the requirements for sequence containers the argument of the member function erase shall be a valid dereferenceable iterator. However due to this statement index += pos - 1; the value of index can be greater than or equal to the value of the expression 2 * ( curr...
63,363,482
63,363,588
How to replace non zero values with a particular integer using CUDA library?
I want to replace all the non zero elements of a device vector with integer 1. I specifically want to use only CUDA libraries to perform this operations. Is there any thrust function that helps me out to achieve my result?
Given a device vector: thrust::device_vector<int> X; you can use one of the thrust algorithms like this: thrust::transform(X.begin(), X.end(), X.begin(), [](int n) { return n ? 1 : 0; }); or thrust::replace_if(X.begin(), X.end(), [](int n) { return n != 0; }, 1);
63,363,525
63,363,717
At what point will the atan2 function reach a domain error for a zero value in c++?
If I have a function similar to this: c=atan2( a, 0 ) I am trying to figure out what the a value should be limited to in order to ensure atan2() does not result in any domain errors. So the question is how close to zero can a get before a domain error is raised. Can this atan2 function compute a number as small as 0.00...
The best way to find out is to try it yourself! #include <iostream> #include <stdio.h> #include <limits> #include <math.h> using namespace std; int main() { int powers[12] = {10, 11, 12, 13, 14, 15, 20, 22, 24, 26, 28, 30}; for (auto i : powers) { try { double a = pow(10...
63,364,134
63,366,081
I'm getting error 127 when trying to get function address
When I try and get a proc address for a function called print, it is able to load the ManualLinking.dll but not the function. The error code that windows gives is 127. The client app is almost a direct copy paste from windows. DLL: #include"pch.h" #include<string> #include<iostream> __declspec(dllexport) void __stdcal...
You need to replace DLL code with: #include"pch.h" #include<string> #include<iostream> extern "C"{ __declspec(dllexport) void __stdcall print(std::string data) { std::cout << data << std::endl; } } If you still have same error, please, check if the executable can actually find the .dll /*...*/ if (hinstLib != ...
63,364,222
63,364,255
Where does member variable get created when object is created on heap?
I am having a little confusion about memory allocation. Where does member variable get created (on stack or heap?) when object is created on heap? For example, say we have class Cat as follows. class Cat { public: int itsage;}; Now suppose we have following line of code in main function. Cat * Frisky= new Cat; Now I ...
itsage is a subobject of Cat which means it is part of the the Cat object itself. Therefore, it exists as part of the heap-allocated Cat object. new Cat creates the Cat object and any subobjects, all within the same allocation. If it were a pointer, this would still be true. The pointer value would be part of the Ca...
63,364,253
63,364,631
Is there a need to dereference when performing a memcpy using pointer to typedef fixed length array? Why or why not?
Ok - so I'll preface this by saying I'm not entirely sure how to describe the question and my current confusion, so I'll do my best to provide examples. Question Which of the two approaches to using the typedef-ed, fixed-length array in a memcpy call (shown below in "Context") is correct? Or are they equivalent? (I'm s...
This code is, IMO, plain wrong. I'd also accept the alternative view "the code is very misleading" //Included from library: //typedef uint8_t msgdata[150]; //const msgdata* IRead_GetMsgData (void); uint8_t mBuff[2048]; void Foo() { const msgdata* myData = IRead_GetMsgData(); if(myData != nullptr) { std...
63,364,804
63,364,889
Organizing library files
I am kind of new to C++ (finished my first book a couple weeks ago) and I am just starting to use libraries (like OpenGL), but I am not really good at organizing files, so my directory structure is quickly looking very messy. I have a C++ directory where I want to keep all my files related to C++. I use Visual Studio 2...
That depends on how independent you want your projects to be. In general making each project depend on a set of shared files seems like a good idea. However, in practice, specially if you are just starting out, it is better to keep separate copies. The reason is that when you are learning, you will be improving your co...
63,364,918
63,985,023
clang says call to void consteval function is not a constant expression
clang(trunk) gives an error for the following code: consteval void f() {} int main() { f(); // error: call to consteval function 'f' is not a constant expression // note: subobject of type 'void' is not initialized } while gcc(trunk) compiles this without error. I feel this is probably a clang bug, s...
This was a Clang bug that was both introduced between version 10 and version 11, and fixed last month. The implementation of consteval in Clang is mostly, but not entirely, complete, and this bug arose after one of the patches adding more complete consteval support. Details: the top-level entry point into Clang's const...
63,364,995
63,366,882
C++ _Tchar units szTestString[] How to assign a string value
Please help me how to assign a value! I don't know how to translate from String to TCHAR for writing to the reg_sz registry string par = "1234.32.23"; _TCHAR szTestString[] = _T(pra); Full Code string par = "1234.32.23"; HKEY ProxyServerKey; RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\Current...
You can't use the _T() macro to convert data at runtime. It only works on char/string literals at compile-time. The best solution is to just use a std::wstring instead. You can pass its data directly to RegSetValueExW(), there is no need to copy it into a _TCHAR[] buffer at all, eg: wstring par = L"1234.32.23"; H...
63,365,146
63,365,765
C++ wxWidgets Sizer issue (beginner)
I'm new to wxWidgets and sizers. I've created the following structure inside of a frame constructor wxBoxSizer *frameSizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer *deckListLeftSizer = new wxBoxSizer(wxVERTICAL); wxBoxSizer *deckListRightSizer = new wxBoxSizer(wxVERTICAL); wxBoxSizer *logOutputSizer = new wxBoxSizer...
@GeoffL, First - there is no blue Static Text only the Red one. Second - wxALIGN_* options as you can see work only in the major direction, i.e. the one you pass to the wxBoxSizer() constructor. What you probably want is (untested): logOutput = new wxStaticText(this, wxID_ANY, "Output Terminal", wxPoint(-1, -1), wxSize...
63,365,152
63,366,381
Why is advertising with ADV_DATA producing Invalid Parameters
I'm trying to write some BlueZ code using the Management API but I can't seem to get BlueZ to advertise arbitrary data on the advertisement system I have 2 tests one in C++ and one using the btmgmt tool that BlueZ has released When I run this command it fails this way btmgmt add-adv -d 8C33 1 Add Advertising failed wit...
Looking at the source for btmgmt, these are the options available: static void add_adv_usage(void) { bt_shell_usage(); print("Options:\n" "\t -u, --uuid <uuid> Service UUID\n" "\t -d, --adv-data <data> Advertising Data bytes\n" "\t -s, --scan-rsp <data> Scan Response Data...
63,365,894
63,366,189
How to push a value inside a vector which in a c++ pair?
I have come across a scenario where I am not able to find a way to push a value in the vector which is in the pair. I have made a priority_queue of pair<int, vector<string>> and I want to push values in the vector, for example: priority_queue<pair<int, vector<string>> pq; I want to know how to push elements in this p...
You don't have access to the underlying container of a std::priority_queue, so you can't access any of the std::vector elements you store in it, other than the top() element, eg: priority_queue<pair<int, vector<string>> pq; pq.push(...); pq.emplace(...); ... // use pq.top().second as needed... You can iterate the stri...
63,366,405
63,366,768
Saving to a file actual window name
Hello i have simple code which is printing actual window name but i cant save output to the .txt file code i know wprintf is used to print it on the screen. #include <iostream> #include <Windows.h> #include <conio.h> #include <fstream> using namespace std; HWND ActualWindow; fstream LogFile; int main() { while ...
You are printing the return value of wprintf(), not printing the content of NewName. You need to replace LogFile << wprintf(NewName) with LogFile << NewName. However, then you would be writing a wchar_t-based string to a std::fstream that expects char-based strings, so there is no operator<< defined for wchar_t string...
63,366,596
63,367,120
Maintain window motion and close actions while socket recv is blocking awaiting data?
I have an SDL2 c++ program that generates an SDL_window, while also employing a socket server that receives data through recv. I noticed that whenever recv is blocking and expecting data, the SDL window actions like window motion with a mouse, or minimizing and closing the window by clicking the corner buttons are disa...
Turns out, the solution to my problem was simply to add a 100 millisecond timeout to recv DWORD timeout = 100;// millisecond timeout for receiving data setsockopt(ClientSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); then, in case if no data is received, I skip the part of the code that expects non...
63,367,595
63,367,816
Timer countdown even when program is not running QML
I am trying to have a 24 hour countdown on my user interface in a QML/Qt project. The time should update every second like 23:59:59 then 23:59:58. Additionally, I need the time to continue going down even when the application is not open. So if the time is 23:59:59 when I close the app, if I open it two hours later it ...
You need to store somewhere timer's end time according to system clock or equivalent information. So at each moment you can tell timer's value by taking difference between system clock's now() and timer's end. Just use std::this_thread::sleep_until to wait to the exact moment you need to update the time for the next se...
63,367,640
63,368,143
Issue with Picking (custom unProject() function)
I'm currently working on a STL file viewer. This one use an Arcball camera : To provide more features on this viewer (which can handle more than one object) I would like to implement a click select. To achieve it, I have used picking(Pseudo code I have used) At this time, my code to check for a any object 3D between 2...
I have found what's wrong, the return vec3 should be made by dividing each component by the perspective instead of being multiply by it. Here is the new UnProject function : glm::vec3 UnProject2(float winX, float winY,float winZ){ glm::mat4 View = GetViewMatrix() * glm::mat4(1.0f); glm::mat4 project...
63,367,796
63,367,832
Automatic promotion of arithmetic operations
Please see the following code: #include <type_traits> int main() { using T = short; auto x = T(1) + T(1); static_assert(std::is_same_v<decltype(x), T>); } It seems that the above static_assert fails for all of gcc, clang, and msvc and I can't see why. The assertion still fails if I change short into any of...
Yes, this promotion from short to int is required. From https://en.cppreference.com/w/cpp/language/operator_arithmetic: If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes in...
63,367,798
63,368,075
What differences are there between Visual Studio CE 2019 and Visual Studio CE 2015 when building C++ projects?
I opened a solution file in VS CE 2019 and tried building the solution and ended up with a lot of C2039 errors saying that certain things weren't members of std namespace. Those were able to be solved by adding the proper include statements. When I opened the same solution in VS CE 2015 (specified by the README of this...
This happens when the code relied on indirect inclusions between library header files, which are not mandated or guaranteed by the standard, and can change from version to version. From What's new for C++ in Visual Studio 2019: Optimized the standard library physical design to avoid compiling parts of the standard lib...
63,367,867
63,379,897
After copping a Point Cloud using pcl::CropBox filter, can't visualize that cropped Point Cloud
I have been trying to understand pcl::CropBoX filter and that's why have been experimenting with that. However, while doing so, I came across this issue: I'm creating a Point Cloud having a cube shape Visualizing it Cropping the original Point Cloud using pcl::CropBox filter Trying to visualize cropped Point Cloud Bu...
It seems you have set Min twice: box_filter.setMin(Eigen::Vector4f(0.25, 0.5, 0.25, 1.0)); box_filter.setMin(Eigen::Vector4f(1.25, 2.0, 0.75, 1.0));
63,368,262
63,384,405
Qt-Based C++ Project Works If Run From cmd.exe But Not From Within Qt Creator
I am writing a very minimal C/C++ Qt-based application for Windows (only Windows -- not cross platform at all) that uses a VISA library (visa64.dll) to talk to some external hardware. That library, in turn, uses some other libraries: (screenshot from Dependency Walker a.k.a. depends.exe) Originally I wrote it in Visua...
TL;DR: The kit I was using to compile in Qt Creator had a different PATH set than my system PATH. To fix this, I did echo %PATH in cmd.exe and copied all the stuff that had to do with the drivers I'm trying to use into the PATH for the kit I'm using in Qt Creator. More details below. I got this to work this morning. As...
63,368,322
63,368,337
How should I read words and put them into vectors in C++?
So the user needs to input the number of words and then input the words themselves. How should I read these words and put them into a vector ? #include <iostream> #include <string.h> #include <vector> using namespace std; int main(){ int n; vector<string>words; string word; cin >> n; for (int i =...
The error is coming not from reading the words, but from printing them on this line: cout << words; There is no overload of operator<< for std::cout that takes a std::vector<std::string>. You need to write the loop yourself: for (auto const & word : words) std::cout << word << " "; Also, please don't use using nam...
63,368,646
63,368,836
Fastest way to remove an element from an array?
I've coded an algorithm designed to produce a list of the closest triplets from three sorted arrays (one element contributed by each array). The algorithm finds the closest triplet, removes those elements, then repeats the process. The algorithm itself runs quite fast, however the code I'm using to "remove" the element...
Fastest way to remove an element from an array? Note that there is no way to erase elements from an array. The size of an array cannot change. So to be clear, we are considering algorithm where the resulting array contains the elements excluding the "removed" value at the beginning of the array, with some irrelevant ...
63,368,914
63,496,858
Is it possible to open 2 microphones in Android at same time with Oboe library?
I'm trying to open 2 microphone streams with google's Oboe library like this, for each microphone: oboe::AudioStreamBuilder builder; builder.setChannelCount(channelCount) ->setDirection(isInput ? oboe::Direction::Input : oboe::Direction::Output) ->setSharingMode((oboe::SharingMode) sharingMo...
Android doesn't allow you to capture audio from more than one thread most of the time. It doesn't matter how many input sources your phone has or which library do you use. You can't open two audio streams at the same time. Even two separate ordinary applications don't have access to the input sources simultaneously and...
63,369,084
63,369,114
Cannot use protected constructor in a derived class
I need to set the 3 values in the House class which is derived from Dwelling class but it gives me the error that cannot call protected constructor class Dwelling { int bedrooms; protected: Dwelling(){bedrooms=0;}; Dwelling(int _b){bedrooms=_b;}; }; class House : public Dwelling { int storeys; bool...
The error has nothing to do with calling the protected constructor, because this line: Dwelling(room); is not a call to the base class constructor at all. It's just a declaration of a variable named room of type Dwelling with a pair of redundant parentheses around the declarator. (c++ syntax can be strange sometimes,...
63,369,164
63,369,241
error: non-static reference member - can't use default assignment operator
I have a problem where.. Well, I'm not sure. I really don't know what it means. I have used this same paradigm illustrated below, where I create an object within a class and give that object a reference to the class. This design is used as an event handler. I added a very unrelated piece of code where I loop through a ...
What does this error mean? It means what it says literally. The assignment operator of A and consequently Handler cannot be used. Important points: References are not assignable. The class contains a reference member, and no user defined assignment operator. Therefore the class is not assignable. You attempt to assi...
63,369,361
63,373,228
How to define a concept of a object that is can be structured binding?
I want to define a concept that can detect whether the type T can be structured binding or not: template <typename T> concept two_elements_structured_bindable = requires (T t) { auto [x, y] = t; }; but this cannot be compiled. Is there a proper way to define a concept like that?
No. There are three cases in structured bindings: Arrays. That's easy enough to detect. Tuple-like. You can easily check if std::tuple_size<E>::value is valid, and then check if std::tuple_element<I, E>::type is valid as a type for all the right types. But the get case is harder since you have to deal with member vs ...
63,369,486
63,369,602
C++ can't access a public attribute in a class that is returned by the vector's iterator
So I have this class called order, and when a user places an order i invoke that class. I have another class called orderbook, it is a vector of orders. I wanted to try to traverse the orderbook upon receipt of a new order to check if there are duplicates, but right now i am stuck traversing the vector. I am using the ...
When you write *it.symbol since the operator precedence for . is higher than *, so the expression becomes: *(it.symbol) and the error says that an iterator doesn't have a member named symbol which is true. You can force the precedence by doing: (*it).symbol or even better, by using the appropriate operator: it->sym...
63,369,513
63,369,717
Why does only backtracking work in this scenario?
I am solving this question on LeetCode.com: In a gold mine grid of size m * n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions:- (a) Every time you are located in a cell you will collect all t...
All your recursive calls might modify the grid, and don't restore it. That means that the first visit to a cell will block it for all other subsequent attempts. For instance, if dig(grid, i+1, j) is evaluated first, none of the cells that were visited during that computation are available when you do the other three di...
63,369,749
63,369,834
Circular queue Display
In void Queue::displayQueue() { if (front == -1) { printf("\nQueue is Empty"); return; } printf("\nElements in Circular Queue are: "); if (rear >= front) { for (int i = front; i <= rear; i++) printf("%d ",arr[i]); } else // Why do I need two loops in this else? { for (int i = front...
The implementation you've discussed about...in that queue elements can be in two manner: linear manner like [4, 3, 1, 2, <empty_pos>, <empty_pos>, <empty_pos>] or circular manner like [1, 2, <empty_pos>, <empty_pos>, <empty_pos>, 4, 3] In the latter case, 4 is the front of the queue and 2 is the last element of queue...
63,369,910
63,369,941
How to write merge function for mergeSort in C++?
I'm learning C++ and trying to write the merge function that will take two sorted lists and combine them into one sorted list. This should run in O(n) time. Below is my code: LinkedList<T> LinkedList<T>::merge(const LinkedList<T>& other) const { LinkedList<T> left = *this; LinkedList<T> right = other; LinkedLis...
After the main while loop where it has the condition to run until both arrays contain elements. So when one of them is empty it exits and one of the arrays might still contain the left-over elements. You need to add a while loop outside also to go thru remaining elements add to the result array. Here is the sample: whi...
63,370,203
63,373,974
how to print ptype of polymorphic objects in gdb
Consider the simple class shown below: When we print the ptype of either b or d in a gdb session, it will print the base class(as expected). But logically it is incorrect. Is there any way to print the actual type of objects(based on the polymorphic behaviour)? E.g:- $ ptype b type = class Base { public: virtua...
You can use set print object on, then your output will look like this: (gdb) set print object on (gdb) ptype b type = /* real type = Base * */ class Base { public: virtual void display(void) const; } * (gdb) ptype d type = /* real type = Derived * */ class Base { public: virtual void display(void) const; }...
63,370,473
63,370,603
Zombie process is not cleanup with waitpid call
I am watching the processes with htop and I see that child process stays as zombie even though I clean up with waitpid call. Any idea why this might happen? Thank you very much! #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> ...
waitpid glibc implementation comments If PID is (pid_t) -1, match any process. If the WNOHANG bit is set in OPTIONS, and that child is not already dead, return (pid_t) 0. The while loop clearly exits immediately as 0 > 0 is false. Change the else and the signal to SIGKILL } else { const int mercy_period = 3; ...
63,371,504
63,371,719
Write on the same line in TextEdit in Qt
When we use ui->TextEdit->append("...") the text entered will be shown in a new line in the TextEdit section. What I want to do is to write on the same line... I've tried this code: ui->textEdit->append("My name is:"); ui->textEdit->append("\b bla"); but it seems that "\b" isn't recognised by Qt
Maybe an option is to do the append outside of the QTextEdit to avoid having a new paragraph created: QString text = ui->textEdit->text(); text.append("bla"); ui->textEdit->setText(text);
63,371,527
63,371,838
Is safe call qWarning("%s", qUtf8Printable(key));
The Qt manu said The char pointer will be invalid after the statement in which qUtf8Printable() is used. This is because the array returned by QString::toUtf8() will fall out of scope. So does qUtf8Printable(key) will fall out of scope when call qWarning("%s", Utf8Printable(key));?
This is safe. Temporary values used as argument survive until the end of the function call.
63,371,807
63,371,910
Why is type deduction on const char[] different to const char *?
In the first call, when I pass a char const [] into a template function with a parameter of T const a, T is deduced as char const * which is reasonable because const refers to the decaying pointer. However, when the parameter type is changed to T const & a, T is deduced as char[7]. From the point of view above, why doe...
why doesn't the const qualify the whole array type Because for array type, (emphasis mine) Applying cv-qualifiers to an array type (through typedef or template type manipulation) applies the qualifiers to the element type, but any array type whose elements are of cv-qualified type is considered to have the same cv-q...
63,372,134
63,372,981
What type of std::function to I need to be able to assign it to either std::upper_bound or std::lower_bound
I have a std::vector<double> m_x; At some point I either need std::lower_bound(m_x.begin(), m_x.end(), x) for a double x, or std::upper_bound(m_x.begin(), m_x.end(), x) What I want is some sort of std::function<std::vector<double>::const_iterator(std::vector<K>::const_iterator, std::vector<double>::const_iterator, doub...
You have applied the answer to the duplicate the wrong way. // assuming function template<typename K> using Iterator = decltype(m_x.begin()); using Overload = Iterator(*)(Iterator, Iterator, const K&); auto me = bound ? static_cast<Overload>(std::upper_bound<Iterator>) : static_cast<Overload>(std::lower_bound<...
63,372,140
63,372,260
C++ output vector contents that is an object type
Within my main .cpp file, I have a vector holding elements of type Band. Band is the name of a struct in my implementation.cpp file. My main file is shown below: int main(int argc,char* argv[]){ std::vector<Band> bandsVec = readbandFile(argv[1]); } I have a corresponding .h file for this line of code: struct Band ...
You need to define an overloaded operator std::ostream& operator<<(std::ostream&, const Band&); C++ doesn't know how to print any old struct automatically. For instance std::ostream& operator<<(std::ostream& out, const Band& b) { return out << b.bandName << ' ' << b.listOfMembers; } If you know how to interpret it...
63,372,416
63,372,485
Multiple Syntax Errors When Referencing Another Class in Include File
Have two files: CIoHandler.h #pragma once #include "CSession.h" class CIoHandler { public: CIoHandler(); ~CIoHandler(); void AuthenticateUser(); void ConvertUnicodeToAscii(); void DoNTLMAuth(); void GetAndSetSocket(); void GetElevatedToken(); void GetH...
You have a cyclic include dependency. To break the cycle replace #include "CIoHandler.h" with a forward declaration. class CIoHandler;
63,372,427
63,373,435
"no user-provided default constructor" warning only with gcc
The following code issues a warning when compiling with gcc, but only with version <= 9.3 #include <array> #include <iostream> template <std::size_t size> struct A { using atype = std::array<double, size>; template <std::size_t index = 0> static constexpr void fill_array(atype& res) { std::get<index>(res) = 1; ...
it just looks like a bug in older version of static analyzer, which couldn't detect fact that you assign values to the elements and were warning you about using an uninitialized class and message can't be avoided by compiler flags - disabling pedantic mode and all warning doesn't remove it, as res supposed to be a retu...
63,372,489
63,372,622
Parallel class hirarchy c++ ends up in abstract class
Why does this simple class hierarchy end up in a abstract class B? I don't know a buzz word to search for in this case. (Maybe Diamond-Problem?) class I_A { virtual void foo() = 0; }; class I_B : public I_A { virtual void bar() = 0; }; class A : public I_A { void foo() override {} }; class B: public A, p...
Looks like B inherits from A, which inherits from I_B, which inherits from I_A. B also inherits from I_B, which inherits from I_A. The diamond inheritance problem is the keyword to search, since you're inheriting the same thing two different ways. Stroustrup mentions this along with examples for what to do.
63,372,778
63,372,952
base class reference to derived object - strategy pattern
Below is a simple strategy pattern implemented using the base class references to a derived object. The solution does not produce an expected result (12 and 2). When base class reference is switched to pointers, it works. Can someone explain what is happening behind the scenes with references here? The issue is in the ...
You are trying to reassign a reference, but references cannot be reassigned. It assigns to Strategy object being referred to instead. If you make Strategy non-copyable/assignable that re-assignment through reference will fail to compile. Use a pointer instead: class Context { Strategy* strategy; public: Context...
63,373,400
63,373,748
How to print generic std::list iterator?
I want to be able to print any std::list iterator by printing its value. My initial code looked like this: template<typename T> std::ostream& operator<<(std::ostream& os, const typename std::list<T>::const_iterator& x) { return os << "&" << *x; } Which did not work, since the compiler can not determine the paramet...
You can constrain the type as iterator or const_iterator of std::list. E.g. template<typename It> std::enable_if_t<std::is_same_v<It, typename std::list<typename std::iterator_traits<It>::value_type>::iterator> || std::is_same_v<It, typename std::list<typename std::iterator_traits<It>::value_type>::con...
63,374,334
63,374,698
Is converting decltype's expression from constant l-value into an r-value discards `const` too?
Here I want to know how type specifier decltype works: const int& rci = 5;// const ref bound to a temporary decltype (rci) x = 2; decltype (rci + 0) y = 10; // ++x; // error: increment of read-only reference ‘x’| ++y; // why does this work std::cout << typeid(x).name() << std::endl; // i std::cout << typeid(y).name() ...
> Why y has only type int rather than const int? Because (rci + 0) is a prvalue, and prvalues of primitive types have const stripped. > Does converting a constant lvalue into an rvalue discards in addition to reference operator, const qualifier too? For non-class types, const qualifier is discarded. From the standard: ...
63,374,746
63,375,953
Sending cursor coordinates to C++ and storing them in a structure and append to main.qml
I am able to drag an image widget at some (x,y) positions, I am able to get these coordinates and see them on console with the functionally of console.log() What I need is that sending these (x,y) coordinates to C++ and store them in a structure. My task is to append (x,y) coordinates values of image widget in main.qm...
Here is an example for guideline. Implementation: when you moved mouse on the window, takes the x,y coordinate values of mouse cursor send X and Y values to C++ side store the values in an array inside struct When you clicked the test button, it shows the array elements stored. main.cpp #include <QGuiApplication> #in...
63,375,208
63,377,957
What does the operator"" do in C++?
How do you call this operator? Can you use it for things other than the creation of custom literals? Example usage: (see cppreference) constexpr long double operator"" _deg ( long double deg ) { return deg * 3.14159265358979323846264L / 180; }
The primary usage of this operator"" is the creation of user-defined-literals. From the reference: Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix. You can call this operator as you would any other overloaded operator: std::cou...
63,375,217
63,375,576
How can I make C++ infer template type parameters from a lambda?
This is my code: #include<iostream> struct Item { int val; }; struct XItem { int val; }; void transform(const Item &i, XItem &target) { target.val = i.val; } template<typename T> void show(const T &v) { std::cout << v.val << std::endl; } template<typename ParamsType, typename ResultType> void handleRequest...
The problem is, implicit conversion (from lambda to function pointer) is not considered in template argument deduction, which fails deducing the template parameters. Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens l...
63,375,241
63,375,433
How can I convert const char* to integer in c++?
I have these variables. static constexpr int size{70}; const char* str; std::array<int_least8_t, size> digits; if str is "1110" I want it to be in digits [1,1,1,0] int i=0; while (*cci) { digits[i]=*cci; // I need some method to convert it +cci; i++; }
I made example for you here #include <iostream> #include <array> #include <string> #include <algorithm> static constexpr int size{70}; const char* str = "1110"; std::array<int_least8_t, size> digits; int main() { int i = 0; for(auto c = str; *c; ++c, ++i) { digits[i] = *c - '0'; } std...
63,375,702
63,382,062
fread is reading garbage in file
I am working on my assignment and faced a problem with fread() in C++. When I modify the name in my file it modifies it perfectly as I want but the problem occurs when I try to read the file after that, it reads the whole file but it does not stop after that it's running total 146 times whereas there are only 3 names. ...
Here are three ideas based on our discussion. I'll start with free functions for reading and writing a person object since it looks like you're at that stage right now. I'll move on to adding member functions in your person class and end with adding stream operators for convenience. An example of free (non-member) read...
63,375,963
63,403,619
Eigen ConditionType array: Efficient way to broadcast instead of looping
I have a performance critical piece of code, where I need to check one array for values below a threshold and then conditionally set the values of two other arrays. My code looks like this: #include <Eigen/Dense> int main(){ Eigen::ArrayXXd a (1, 100), b (2, 100), c (3, 100); a.set...
You can try the following: Define your array types with fixed number of rows and dynamic number of columns, i.e., you can replace Eigen::ArrayXXd with Eigen::Array<double, 1/2/3, Eigen::Dynamic>. Use fixed-size version of block operations (see https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html), i.e.,...
63,375,987
63,376,266
pointers to member functions with move semantics
When you have a pointer to a non-static member function of an object on the stack, what exactly happens when the object changes its location because of an move? Does the pointer still point to the location of the moved-from object and thus is invalid/dangling?
Pointers to member functions do not hold a reference to any instance of the class. This is true even for pointers to non-static member functions. Such a pointer can be constructed without having an instance of the class: class star { public: void shine(); }; void (star::* smile)() = &sun::shine; And an instance n...
63,376,094
63,376,484
C++ STL priority queue customer comparator does not work
I have written almost similar code in the past and it worked (I remember vaguely). It seems that comparator is not working here?? Any clues? #include<iostream> #include<vector> #include<queue> #include<iterator> #include<algorithm> using namespace std; typedef pair<vector<int>::iterator,vector<int>::iterator> PR; ...
The begin() and end() iterators you get from the copy of the vector in for(auto e : A) will be invalid after the iteration ends and the temporary vector e is destroyed. Use a reference to the inner vector instead: for(auto& e : A) { // "auto& e" makes "e" a reference to the existing vector if(e.size()>0) PQ.emplace...
63,376,389
63,376,667
Formatting `nullptr` on out stream as hexadecimal address, instead of `0`
How can I format a null pointer of any type, preferably including immediate nullptr, on out stream so it prints out like 0x000000000000 or even just 0x0 but something resembling an address value instead of a senseless 0 or terminate or whatever non-address-like? //(nil) or (null) I could accept too if not using printf....
You can make a pointer formatter, which can do the formatting in whatever way you prefer. For example: #include <cstdint> #include <iomanip> #include <ios> #include <iostream> #include <sstream> #include <string> static auto Fmt(void const* p) -> std::string { auto value = reinterpret_cast<std::uintptr_t>(p); ...
63,376,683
63,377,419
What's wrong with this function that I wrote to find calculate NCR?
I tried using this relationship to recursively find the value of nCr: nCr = (n - r + 1) / r * nC(r-1) int comb(int n, int r){ if(r == 0) return 1; return ((n - r + 1) / r) * comb(n , r - 1); } For a call of 6C2 I get 12 instead of 15. I have tried to trace, but I'm getting the right answer. Any input is app...
Consider what happens when you do comb(6, 2). In the first recursive call, the return expression becomes: return (5 / 2) * comb(6, 1); The (5 / 2) is going to do integer division and give 2 which is not correct. Since the final answer of nCr is actually guaranteed to have a result that is an integer, you can fix the e...
63,376,747
63,389,414
Qt: mouse cursor flickering due to fast screen sampling
Hello i use this code to quickly (about 60 times/second) sample the screen and find its average color: samplerWorker::samplerWorker(int newId) { this->id = newId; this->screenWidth = GetSystemMetrics(SM_CXSCREEN); this->screenHeight = GetSystemMetrics(SM_CYSCREEN); this->hDesktopWnd = GetDesktopWindow()...
Refer: Raymond Chen Discusses the Case of the Disappearing Cursor These translucent windows, known as layered windows, are not normally included by the BitBlt function when reading pixels from the screen. In order to get them, you have to pass the CAPTUREBLT flag. The mouse cursor is just another composition object an...
63,376,756
63,376,798
Unexpected answer for a simple stack problem in C++
class Solution { public: bool isValid(string s) { map<char , char> m; m[')'] = '('; m['}'] = '{'; m[']'] = '['; stack<char> st; if(s[0] != '(' || s[0] != '{' || s[0] != '[') return "false"; for(int i = 0; i<s.length(); i++) { if(s[i] == '(' || s[i]== '{' ||...
Regarding your expression: (s[0] != '(' || s[0] != '{' || s[0] != '[') For a start, unless s[0] is some weird quantum variable that can be three things at once, that expression will never be false. Think about some possibilities: Character != '(' != '{' != '[' || all --------- ------ ------ ------ ------ (...
63,377,717
63,378,296
How to use regular std::basic_istream::read, std::basic_ostream::write on a buffer of data in memory?
I have a QByteArray and want to use it like a regular text file. How can I use functions like std::basic_istream::read on it ?
QByteArray data type is close to a container, not a stream. You can't handle it like a text file unless you inherit std::streambuf class that handles QByteArray internally. You can also consider converting std::stringstream to QByteArray if you don't care of performance, std::stringstream ss; // write to ss ... . . QBy...