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
62,425,084
62,428,620
FIFO: One process never reads from pipe
I'm following THIS TutorialsPoint guide to Linux Piping, and I specifically need to use FIFOs. However, the code doesn't work at all for the server side. The server file either hangs indefinitely or it reads nothing, while the client instead writes on the FIFO and immediately reads it has just written. Here's the full ...
You let the server sleep after writing – but not the client. That way, the client still might read its own output back before the server can fetch it. So at very least you should add a sleep after both writes, letting the server sleep a bit longer to make sure the client wakes up first to read the servers output. Acces...
62,425,505
62,425,632
c++ small chance for runtime error while using std::multimap
Sometimes i get runtime error while using multimap std::async. Visual2019 in debug mode show this error: Expression: cannot dereference end map/set iterator. Example of code that generates error: #include <iostream> #include <map> #include <future> #include <mutex> #include <Windows.h> class MyClass { public: M...
std::async by default runs in a separate thread. So you're accessing the same object (mp) from multiple threads without synchronization. This is known as a race condition, a form of undefined behavior. Unsynchronized parallel access to the same object is possible only in case of (1) multiple readers, 0 writers, or (2) ...
62,425,677
62,430,087
How to append to QTextEdit without using the current paragraph style
When using myQTextEdit.append() the style of the inserted text is as follows (Qt 5.14 documentation): "The new paragraph appended will have the same character format and block format as the current paragraph, determined by the position of the cursor." However I would find it convenient to be able to append text with a...
I tried to reproduce in an MCVE what OP described: // Qt header: #include <QtWidgets> // main application int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // setup GUI QTextEdit qTextEdit; qTextEdit.show(); // populate text editor qTextEdit.appe...
62,425,888
62,427,209
Cmake: Set warning levels for C and C++ code individually for MSVC (Visual C++)
I'm trying to control compiler warnings individually for C and C++ code in a cmake-based build: For gcc and clang, I can set additional flags that are applied only to the C compiler like this with TARGET_COMPILE_OPTIONS: target_compile_options(MyLib PRIVATE $<$<AND:$<COMPILE_LANGUAGE:C>,$<NOT:$<...
... it seems COMPILE_LANGUAGE:C is ignored by MSVC-based builds in mixed C/C++ projects. Yes, CMake documentation confirms your conclusions: Note that with Visual Studio Generators and Xcode there is no way to represent target-wide compile definitions or include directories separately for C and CXX languages. Also, ...
62,426,624
62,447,088
CGAL seam_mesh: how to include the seam in the halfedge_descriptor of the boundary?
I am parametrizing a simple mesh (see the picture below) with the seam_Polyhedron_3.cpp example of CGAL 4.14. I identified the vertices to "cut it open" that I wrote into a seam file (they lie along one polyline connecting the lower and upper boundary): 73 75 80 120 However, I am confused about what the line halfed...
The comment of @mgimeno helped me understand what was wrong. I post it as an answer in case someone else will be confused about the structure of .selection.txt files in future (see also a related discussion). Here once again the mesh but with the labels of the vertices along which I want to cut. Tip: To find these num...
62,426,727
62,427,140
What is the best way to handle timed callbacks that affect an object shared across different threads?
I have a class, let's call it Foo foo, which holds data that is useful to multiple threads. These threads may call read and write operations (e.g. foo->emplace(something)) which I protected by a mutex inside Foo and added mutex locks to the operations. Here's where I'm uncertain when it comes to implementation. I have ...
You have a few options: One thread per request a.k.a your solution Advantages: easy to implement precise remove times Disadvantages: lots of threads created. But then again all the threads sleep for their whole life so it might not be a problem worth solving. One queue and one thread that periodically checks expire...
62,426,879
62,427,249
I need an algorithm to concatenate 2 vectors and also update the vector in cases of common element in C++ (not specific to C++11)
I have 2 vectors say vector of string/char. vector<string> dest having elements {"Demo01","Demo02","Demo03"} vector<string> src having elements {"Demo03","Demo07","Demo08"} I want to copy all the elements from src to dest such that if dest vector already has an element present in src vector, replace that element in t...
The most simple approach would be to just check for every element in src vector, if an duplicate exists in dest vector or not. If it exists just append Duplicate to it, else you can just push back the element as a new element in dest vector. The follow code would do the job - #include <iostream> #include<vector> #inclu...
62,427,265
62,428,515
Template argument deduction inconsistent
The following code compiles and runs on MSVC 2019 and Clang trunk. (I think it needs at least C++17). It does not run on gcc-trunk and I believe the consensus is that this is due to a bug in gcc. However, when any of the elements are replaced by a user type or a pointer type, it fails on all compilers. To see this, unc...
First, before CWG 727 you're not allowed to specialize a member function template inside a class scope. You will have to use constexpr-if, tag-dispatching or SFINAE to handle the i==0 case. In c++14 using std::enable_if_t that would be: template <int i, typename T> std::enable_if_t<i != 0> Set(T&& v) { tail.templat...
62,427,902
62,427,962
How to convert/cut uint256_t to uint8_t[ ]
I got one library that uses uint256_t to represent a hash, and another library that uses uint8_t array for this. I guess there should be a way to cut/convert this uint256_t into an uint8_t[32] somehow. However, I couldn't find yet how that could be easily converted.
Use memcpy. You have two unrelated types, but you know that the binary representation of the hash is identical for both. The safest way to convert between the two is via memcpy. uint256_t source_hash; // compute source_hash // [...] uint8_t dest_hash[32]; std::memcpy(dest_hash, &source_hash, 32); Note that this only ...
62,428,201
62,428,292
Check if input std::array pointer data is equal to some constant array
I have a function trace that can be simplified to : void foo(const std::array<unsigned long long int, 3>& in) And I want to check if the value of in is specifically something (eg. {1,1,1}) so I can warning/error. I've seen that you should be able to use == and != operators in std:array, however the following fails: i...
in refers to a std::array<unsigned long long int, 3>, std::array<unsigned long long int, 3>{1,1,1} is also a std::array<unsigned long long int, 3>, hence you can compare them directly via ==: if(in == std::array<unsigned long long int, 3>{1,1,1}) In case the array has more elements you might want to use an algorithm t...
62,428,251
62,596,756
Asynchronous Loading of images in gtkmm
Currently, in my project, we are using gtkmm pixbuf create_from_file or create_from_date which hangs up whole GUI for 1-2 seconds in case of high-resolution images and in case of loading multiple images for a screen it becomes awfully slow. Is it possible to load images asynchronously in gtkmm for the above two functio...
There are docs for that. That example does exactly what you are asking for. These are the functions that do the magic. The example is easy to follow. // notify() is called from ExampleWorker::do_work(). It is executed in the worker // thread. It triggers a call to on_notification_from_worker_thread(), which is // execu...
62,428,640
62,429,893
which is best way to initialize array, "memset" or " {//value} "?
int main(){ int ar[50]={1}; //OR int br[50]; memset(br, 1, sizeof(br)); return 0; }
int ar[50]={1}; This will set only the first element to 1. Rest all will be 0. memset(br, 1, sizeof(br)); This will set all the bytes in br to 1. It is not the same as setting all the values to 1. The values afterwards are: {16843009, 16843009, 16843009, 16843009, 16843009} Use memset when you know you really need i...
62,429,286
62,437,291
Display header files in Qt Creator using Cmake
So I just setup a new Cmake project with Qt Creator. Then I added some classes to the project and Qt Creator is displaying the files as follows: Project Folder Project Name Source files Header Files Now when I add a header file (New File > C++ Header File) only (without a source file), the header file is not di...
You need to add the header to the sources list in CMake. In your case if(ANDROID) add_library(TEST SHARED main.cpp wetcanvas.cpp wetrenderer.cpp MyHeader.h qml.qrc ) else() add_executable(TEST main.cpp wetcanvas.cpp wetrenderer.cpp MyHeader.h qml.q...
62,429,453
62,429,601
Is it possible to pass a template function as argument without filling its own arguments?
Sorry if the question looks stupid. But I have the following code that compiles. I was wondering if it's possible to pass only the name of the function as template and then later on fill it in the function? Like for example in here we have template<typename T> int getDiscount(T t,const std::vector<int> & discounts...
You might do: std::cout << getDiscount(std::mem_fn(&Discount::getMaxDiscount), discount) << std::endl; or with lambda: std::cout << getDiscount([](const Discount& discount){ return discount.getMaxDiscount()), discount) << std::endl;
62,429,636
62,429,751
How I can get second value from function using *pointer?
I have a function, and I need to get two values from there. Function can return only one value. I read somewhere that I can use pointer to get second value, when I'm trying to do this I'm getting error so it looks pointer value can't go outside of visibility zone. So that means I have only one value. How I can get seco...
An instance of a certain type is "one value". Consider this class: struct foo { int bar; double moo; }; Now I can write a function that returns one value of that type: foo asdf() { foo result; result.bar = 42; result.moo = 3.14159; return result; } PS: Don't use pointers. It is possible to ...
62,429,881
62,430,502
Why must the return type of a coroutine be move-constructible?
Consider the following code that defines the invoker class - a minimal return type for a coroutine. We explicitly delete the copy and move constructors of the invoker class. #include <coroutine> #include <cstdlib> class invoker { public: class invoker_promise { public: invoker get_return_object() { ret...
With C++17 guaranteed copy elision, the invoker returned by get_return_object() is a prvalue, and hence should not be materialized until after it is returned from f(). That would only be true if a coroutine function call were guaranteed to generate its return value by a call equivalent to building a bunch of objects ...
62,430,684
62,448,359
Why C++ requires public inheritance, ignoring friend declarations, to make dynamic downcast working?
Here we have a class B, inherited from class A, and it has a friend class C. Being a friend, C should have access to everything in B, including the A base class. To test it, first we create a B instance. we upcast its address to an A* then we try downcast it with dynamic_cast<> again to B*. The expected result is to ...
Summarizing the useful infos and cited resources in the comments, a self-answer can be written. First, the friend declaration is a no-issue: friend affects only the accessibility of the members of the class where it is declared on, but not its base class(es). Second, accessibility check in C++ goes in compilation time....
62,430,862
62,431,022
How to detect a type type alias?
I can detect a member using the following template check: template <typename T, typename = void> struct hasMember : std::false_type {}; template <typename T> struct hasMember<T, decltype((void)T::member, void())> : std::true_type {}; E.g. for: class Test{ public: int member; using sometype = size_t; } I could ...
You can do that by using the same method as with the data member detection. Instead of using a data member, simply use a member type and void_t: template <typename T, typename = void> struct hasSomeType : std::false_type {}; template <typename T> struct hasSomeType<T, std::void_t<typename T::member_type>> : std::true_...
62,430,952
62,432,546
Best container combination to hold named set of coordinates
I need to hold a set of up to 50 coordinate (x, y) sets, up to 4 each, so it would look like: 4: {7, 3}, {5, 3} 27: {1, 1} 44: {9, 9}, {9, 7}, {7, 7} and so on Both x and y will never be higher than 9 nor lower than 0. I ended up with unordered_map<uint8_t, vector<vector<uint8_t>>>, but almost sure that its ineffici...
If you know about x and y (0 <= x <= 9), you can use bit field. And I would store data like this struct Pair { uint8_t x:4; uint8_t y:4; }; unordered_map<uint8_t, vector<Pair>> container;
62,431,149
62,431,302
Multidimensional array to store three different data types?
I have a set of three values pairs that I want to store in an array, each value with different type. [string][int][double] for storing things like [John][12][40.025] [Amy][20][16000.411] and I want to be able to retrieve the values by location. What container should I use? I have looked through many answers but most of...
This is what classes are for: struct data { std::string name; int name_describing_this_variable; double another_descriptive_name; }; You can store instances of this class in an array: data arr[] { {"John", 12, 40.025}, {"Amy", 20, 16000.411}, };
62,431,297
62,431,371
One class with multiple different declaration
I have some simple codes here: // main.cpp #include <iostream> #include "foo.h" int main() { Foo foo; foo.spam(); std::cout << "In main: sizeof (Foo) = " << sizeof (Foo) << std::endl; return 0; } // foo.h #ifndef FOO_H #define FOO_H class Foo { public: int bar; void spam(); }; #endif // foo...
class Foo; is a declaration, but class Foo {}; is a definition. So you have multiple definitions of Foo in your program. This violates the one-definition-rule, which states (among other things), that every entity in your program must have exactly one definition. Violating ODR leads to undefined behavior, so there's ...
62,431,359
62,448,548
Rebuilding a C++ program with OpenCV on a VM
I need to switch from an ubuntu 20.04 to a Windows 7 workstation. I'm writing a program for Raspberry PI that needs pthread, so I need a linux test environment. I installed an ubuntu 20.04 VM and reinstalled all the libraries used in my program : OpenCV 4.2 Libtorch NumCpp Here is my CMakeLists.txt : cmake_minimum_r...
I finally managed to make it work, thanks to @squareskittles : I needed to uninstall OpenCV, and rebuild it from source to the good version, with C++14 standard. If you have linking problems related to OpenCV when building, uninstall OpenCV and build it yourself : sudo apt remove libopencv-dev && sudo apt autoremove c...
62,431,423
62,431,489
c++: calling multi-argument constructor using operator =
i have this sample: #include <iostream> using namespace std; class A { public: int x; A(int one) { x = one; } int getX() { return x; } }; void main() { A first(5); first = 10; } which in here the constructor is called in both lines of main. but if we had more than one variable in the class, is i...
Yes, since C++11 you can do it with copy-list-initialization like this: A example = {50, 40}; example = {40, 50};
62,431,777
62,432,989
Undefined identifier/ undeclared
I recently started C++ and I wanted to create a simple ceaser cipher function that could be called on, however because I copied the coding structure form my python program I seem to be getting 4 errors and 2 warnings. The mode bit is a bool where true is to encrypt and false is to decrypt (it worked on python so hey) :...
As noted above, the major issue you have in your code is that CharPos is redefined in each if clause. Every place you put int CharPos = ..., you create a new variable, and even though its name is similar for you, for the compiler, there are three unique variables of this name. In order to use the same variable in all o...
62,431,846
62,432,243
does ofstream::close() call sync on linux?
Re this quetion: Does close() call fsync() on Linux? This question describes that close() (c lib) does not call sync on linux. Is this the same for fstream::close()?: http://www.cplusplus.com/reference/fstream/fstream/close/ suggests that is does write all the remaining bytes to file. I have observed (rare) cases where...
does ofstream::close() call sync ... It will flush the buffers that are internal to the stream, and the closes it. Whether something comparable to sync or fsync is called is unpecified. ... on linux? This is up to the implementation. Thus, it may depend on which standard library implementation you use. If you use a...
62,432,153
62,432,967
ESP32 not recognising that any device is connected to its access point
I have gotten my ESP32 to create a wireless access point. It shows up fine on any device however, no matter what device I try and connect (iPhone 6s, iPhone 8, Windows desktop), the ESP32 just says that there is no device connected. My code is: #include <WiFi.h> #include <WiFiClient.h> #include <WiFiAP.h> const char *...
That's not how this works. Your program is working properly; your expectations are wrong. WiFiServer is poorly named. It has nothing to do with clients connecting to the wifi network that softAP creates. Instead it creates a server listening on the TCP port number that you gave it when you created the object (in this c...
62,432,165
62,432,649
Declare and access struct from a C library in C++
I'm using a C library which has a struct called dataSet which is used throughout the library. I can declare the struct in my C++ code and pass it to the methods in the C library and it works fine, but I don't know how to access items from this struct in C++ as I get read file access violation. I'm not sure if I should ...
I want to be able to simply do trainingData->numInputs in my main.cpp file, but I'm not sure if this is possible. The library has been designed in such a way, as to hide the definition of dataSet, and thereby prevent access to numInputs and other members. Technically, you can access the member, simply by defining th...
62,432,576
62,432,686
Data structure for interpolating T along axis of numerical keys
Is there a data structure that when initialized with a key1 at 10 and key2 at 20, when accessed at 15 will call an interpolation callback function with (key1, key2, 0.5) with return value T? The callback ensures that we can use our preferred S-curve for the interpolation. I'm expecting accesses on each end to pass the ...
Its not just a data structure you are looking for, but a way to retrieve information from it. You can use a map + find_if: #include <map> #include <algorithm> #include <iostream> template <typename C,typename I> double get(const C& container,double x,I interp) { auto it = std::find_if(container.begin(),container.e...
62,432,845
62,459,622
Saving names of files with specific extension in particular folder with Boost Filesystem C++
I'm trying to write a function that will save the names of files in a particular folder that have the extension .fac into a vector so that I can use them later. I found this in an older question How to get list of files with a specific extension in a given folder? , which seems to be exactly what I'm looking for but I ...
@AlanBirtles I think I've figured it out, it was entirely my own stupidity and a quirk of VS. When using Debug to test it the vector is always empty but when opening the .exe directly it does indeed work. Thank you for the help Without a doubt this is down to the current working directory. When debugging the current ...
62,432,999
62,433,113
Why don't these functions decay to a function pointer?
I had a class which held a function pointer to be called, and now I've come across a situation where I would like that callable function to hold a self-contained reference/value (lambda). So I create my templated class to accept either function pointers or lambdas like this: template <typename FunctionType> class MyCla...
You could make your class store a function pointer instead, like this: template <typename Ret, typename ...Args> class MyClass { public: MyClass(Ret (*function)(Args...)) : function(function) {} Ret (*function)(Args...); }; Then you can store the lambda, by explicitly decaying it to a function pointer: MyClass...
62,433,250
62,447,260
Limit amount of files user can select in QFileDialog
Here the code: dialog = new QFileDialog(this); dialog->setFileMode(QFileDialog::ExistingFiles); connect(dialog, SIGNAL(currentChanged(const QString&)), this, SLOT(dialogSelectionChanged(const QString&))); void MainWindow::dialogSelectionChanged(const QString& file) { QStringList selected = dialog->selectedFile...
This can be done if you're willing to accept a shameless hack :-) Assuming the following code... QFileDialog fd; Inspecting fd using fd.findChildren<QListView *>() reveals that it has two children that either are or inherit from QListView... QListView named listView QSidebar named sidebar (where QSidebar is private ...
62,433,707
62,433,796
Cast a pointer to point to main function in C
Hi i see an example of pointer as below: void main() { int a=197,*p=&a; (int(*)())p==main; } I do not know what the statement (int(*)())p==main do ?
If we split it up into smaller parts we have (int(*)())p == main The first is a cast of p to a pointer taking either an indeterminate number of arguments (in C) or no arguments (in C++). It compares this pointers to the pointer that main decays to. Then throws away the boolean result (the result is not used). Note th...
62,434,508
62,439,801
Sublime Text C++ Build System
I use the following compiler settings to compile my C++ code: g++ -Wall -Wextra -O2 -fwrapv -Wfloat-equal -Wconversion -std=c++17 A.cpp But I am not sure how to setup the build system for the purpose, nor I want to try myself! I doubt that I may mess up the configuration (because I did once). So I need help to configu...
This build system works in my machine, basically its the default C++ build system with the extra options, { "shell_cmd": "g++ -Wall -Wextra -O2 -fwrapv -Wfloat-equal -Wconversion -std=c++17 \"${file}\" -o \"${file_path}/${file_base_name}\"", "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_d...
62,434,772
62,434,958
SDL_FreeSurface is not freeing RAM / RAM Overflowing
simple problem I think, but I have problem with freeing surface, cuz RAM is overflowing even if I add SDL_FreeSurface() to my code. Without this function RAM is fine. There's something more to "free" in this code? This code is trying to make text (score for ping pong game) on the top of the screen. TTF_Init(); ...
You're freeing the surface, but you're not freeing the texture that was created based on it. Add this line to the end: SDL_DestroyTexture(Message); You will also need to close your font: TTF_CloseFont(arial); It's also good practice to close SDL_TTF. Add this line just before SDL_Quit(); TTF_Quit();
62,434,913
62,451,770
How to create a table in qt with SQLite?
I have a property of class named m_database. class SqlThread : public QThread { public: SqlThread(); void run(); private: QSqlDatabase m_database; QString m_dbfilename; }; and i instantiate in constructor like the example below: SqlThread::SqlThread() { m_database = QSqlDatabase::addDatabase("QSQLITE"); } ...
Replace the query string to: databaseQuery.prepare("CREATE TABLE IF NOT EXISTS data (id int not null primary key, tu text, data BLOB, puits integer);"); Otherwise the execution fails if the table already exists.
62,435,378
62,435,411
Can you compile and run a c++ file in the Linux terminal?
I am coding on a Raspberry Pi, and I just learned C++,and I want to continue coding in it. I am using the Raspbian OS. I can't download xCode, as it is humongous, and the Raspberry Pi would break. In CodeCademy, it teaches you to compile and run the programs using g++ and ./a.out. Is there any way to do that in the ter...
Yes, but you have to install a C++ compiler first. As root, run apt-get update && apt-get install g++. Then you can run g++ as usual.
62,435,526
62,435,631
aliassing a template parameter pack
I would like to use a using alias for a parameter pack such that the templates can be used elsewhere in the code base. In the following code I commented the lines where I would use the types: template <typename FirstArg, typename ... OtherArgs> struct Base { using UsableFirstArg = FirstArg; // this would be needed ...
You cannot alias variadic template argument. You can wrap them in std::tuple: template <typename FirstArg, typename ... OtherArgs> struct Base { using UsableFirstArg = FirstArg; using UsableOtherArgs = std::tuple<OtherArgs...>; virtual OtherClass method(OtherArgs... a) = 0; }; Unwrapping need some helpers...
62,435,542
62,435,910
Iterator aware objects in std::list
I have a list of objects: std::list<A> objects; In order to trigger an async operation that will remove them from the list based on some condition, The objects need to be aware of their location in the list: A::A(std::list<A>::iterator it); How can I pass iterator to constructor when adding items to the list? objects...
There is a chicken and egg problem that you have to resolve: the A class wants the iterator to be ready before the object is constructed, while the iterator assumes that some sort of an element is constructed already. One way to solve this problem is to introduce an additional level of indirection, for example to store...
62,435,588
62,441,092
Reading obj files! (Indices)
What I want to do is read the faces(f), but they have "/" that I don't know how to remove? Basically what I want, is to get the faces number stored in a temporary variable. I have no idea how to do it in c++ fstream. std::string text; std::istringstream iss(line); iss >> text; // Easy part! if (text =...
int i, j, k; char c; iss >> i; iss >> c; // remove the / iss >> j; iss >> c; // remove the next / iss >> k; store the i,j,k somewhere and so on, then repeat as many times as needed.
62,435,671
62,435,818
Is there a way to modify 'operator->' so that 'z->im' returns imaginary part of complex number
I have a struct Cmplx which models complex numbers. class Cmplx{ double x; double y; public: Cmplx(int X, int Y){x = X; y = Y;} double& operator->(...){...} } I need to implement the operator, such that int main(){ Cmlpx z(1,2); z->im = 5; z->re = 2; } Changes my complex number into (2,5); I know how to do...
You might abuse of operator-> that way: struct ComplexRef { ComplexRef* operator->() { return this;} double& re; double& im; }; class Cmplx{ double x; double y; public: Cmplx(int X, int Y){x = X; y = Y;} ComplexRef operator->(){ return {x, y}; } }; Demo The overload of operator -> must either retu...
62,435,720
62,437,551
Destructor for circular linked list in c++?
when the destructor of 'class LL' ~LL() gets called for this circular singly linked-list, the program crashes instead of freeing up the heap space of the pointer. How can I solve this problem? class Node { public: int data; Node *next; }; class LL { private: Node *head, *tail; public: LL() { head = NULL; ...
There are a few issues with the linked list. The linked list's destructor assumes that head isn't null, when there is a possibility that it could be. Make sure to check that head isn't null before trying to clean up memory. Once that is done, it looks like your original destructor should work. The function createLL wi...
62,436,247
62,436,516
C++ beginner: why is my compiler returning "name not found" based on my loop?
This is my first time programming with C++ after taking 3 classes in Java (so, definite beginner here). The homework is prompting me to append to a text file and then to search within the text file for a name (in this case, my name). It was working perfectly then I was trying to get it to show my whole name rather than...
If you want your name to be written on a single line, you should write a complete line, including a newline: outFile<<"Katelyn Walker" << std::endl; And when asking for a name to search for, std::cin >> search wont let you enter spaces. If you don't want spaces, then that is ok, otherwise you should probably use std:...
62,436,386
62,436,767
Why the need for both const reference and const member function?
I'm doing the exercises from "Programming Principles and Practice using C++" and I found a class with this member function here: const vector<string> &get_name() const { return name; } where name is a vector: vector< string> name; The book presents 2 concepts so far (up to page 235): return a const reference to pre...
return a const reference to prevent the function to change the returning value a const member function that cannot modify the object. in this case, it would be like this This could have been a bit more clearer, I'll try my shot at explaining it better. Returning a const reference prevent the returned object to be m...
62,436,553
62,437,694
Temporary class object
I'm currently reading c++ primer 5th edition and these is one of code examples that were in the book. I'm confused with this line of code auto ret = StrBlobPtr(*this, data->size()); if I understand correctly this line creates a temporary StrBlobPtr object and it calls this constructor StrBlobPtr(StrBlob& a, size_t sz =...
Since c++11 you can use keyword auto if you don't want to specify type of variable explicitly, but don't confuse it with automatic variables, which means that they are deleted at the end of the block (you can read this: cppreference). So at first line of function StrBlobPtr::end() constructor is called, object of type ...
62,436,764
62,437,600
Drag and Drop from 2 listwidgets , but change text after dropping in 2nd ListWidget
The 'Country' QListwidget is going to be populated with country names items and if the user drags that an item and drops it in capital QListWidget, it should show me the name of its capital , i.e that item text should change in capital QListWidget. for example - an item named "Russia" in country listwidget , after dra...
A simple solution is to create 2 roles that store each information, and then use a delegate to display the text depending on the view: #include <QtWidgets> enum CustomRoles { CounrtyRole = Qt::UserRole, CapitalRole }; class DisplayDelegate: public QStyledItemDelegate{ public: DisplayDelegate(int displayRo...
62,436,857
62,438,383
Physical memory address and pointer address is not same
Hi i'm playing with c++ pointers and also using program called RamMap from microsoft for inspecting memory physical address. but i figure out that the address of variable pointer in c++ does not exist in list of RamMap For example: #include <cstdlib> #include <iostream> #include<conio.h> using namespace std; int main...
Every process has its own view of memory that consists of logical addresses. They may or may not correspond to physical addresses, that is, actual RAM. But even when they do correspond, the values are still different. If this wasn't the case, a lot of things would go wrong. But the most obvious one is probably the issu...
62,437,056
62,511,695
Check for amount of line breaks — winapi c++
I have a static text control that should resize along with the window, its text width is smaller than the whole line of text at first, so it clips like I need by default. I would like to center the text vertically. When it is clipped the whole height is occupied, but when static's width is large enough and the whole te...
After some research, I found that you can customize the height of the upper left corner of the text to achieve vertical centering. Of course, the text can be truncated. When the length of the static control is less than the length of the text, the text will be truncated. So we need to calculate the height and length of...
62,437,507
62,493,785
C++20 compiling modules with Visual Studio: doesn't compile or import ixx files
Visual Studio 2019 doesn't attempt to compile my .cxx or .ixx files. Here is my .cxx file: export module greetings; import std.core; export std::string get_greeting_text() { return "Hello, World!"; } and here is main: import std.core; import greetings; int main() { std::cout << get_greeting_text() << '\n'; ...
Solution: Add greeting.ixx to Header Files. (It won't work to add it to Source Files.) Right-click properties on greeting.ixx, and Set Item Type to C/C++ Compiler Set Excluded from Build to No. Save Build It seems a little flaky. Rebuild failed unless I did a Clean first.
62,438,065
62,438,134
Visual Studio Code Run program in Terminal for Input
Recently started learning c++ and wanted to try to use inputs. Just made a very basic program that tells you the number of weeks in a given number of days with remaining days included. Whenever I run this program in Visual Studio Code it runs the code but it waits for a input with not way to input. Tried to build this ...
use the integrated terminal in visual studio code. you can toggle it with ctrl+ù. then compile with g++ and run the output. typically, it looks like this : g++ main.cpp -o out.exe; .\out.exe . to prevent the terminal from closing, you can add a cin.get() at the end of the cpp file
62,438,098
62,472,012
Is this a data race? OPENMP
I am a bit confused if there is a data race for variable k. To my understanding, only one thread will execute the single construct but since no wait is asserted, threads will start executing the for construct immediately. Is atomic here enough to prevent any potential data race? #include <stdio.h> #include <omp.h> #de...
Assuming the rest of the code expresses your intended algorithm correctly, it almost is. As you were probably suspecting yourself, you need to protect k' s update in the single region as well. j is an unused variable, I do not know if you simply forgot to delete it or you were trying to implement sth else. I would have...
62,438,340
62,441,756
Template class with std::enable_if_t, static const member initialization
Okay, after searching myself half to death and not finding any answer that actually seemed to work I gotta ask: Say I've got a class (contrived example, but hopefully good enough for now) template <typename T, std::enable_if_t< MyConditional<T>::value >> class MyClass { public: static const MyClass ZeroInited; ...
Issue with template <typename T, std::enable_if_t< MyConditional<T>::value >> is that you expect as second argument a void value, which doesn't exist. use template <typename T, std::enable_if_t< MyConditional<T>::value, bool> = false> class MyClass{/*..*/}; and template <typename T, std::enable_if_t< MyConditional<...
62,438,376
62,438,553
Should call istream::clear() in my custom >> operator?
I'm writing a custom >> operator, which reads an entire stream character by character and updates an object with each character, something like this: class MyClass { public: bool Process(char c); } std::istream& operator>>(std::istream& input, MyClass& value) { if (input) { char c; ...
Should I be calling istream::clear after successfully processing the stream? That would be fine since your stream succesfully read the entire input and that is what your user-defined operator>>() is supposed to do, so it should report success. I would change it to clear the mask except for the ios_base::eofbit as t...
62,438,379
62,438,667
What is the correct way to create a class function that is passed a string array as a parameter? [Arduino]
I want to create my own function in an existing library from Arduino/ESP8266, pass an empty array in case the user doesn't have any header. //.h file t_httpUpdate_return updateheader(WiFiClient& client, const String& url, const String& currentVersion = "", const String& header[][2] = {{}}); //.cpp file HTTPUpdateResul...
Arrays of references are not allowed. Also, you can't constrain the size of the inner array like that. Arrays can't be passed around as values, they basically decay to pointers when you pass them to another function. That also means you need to pass along the size of the array. What you wrote: sizeof(header) is a bug -...
62,438,429
62,438,501
How would you write feature agnostic code for both AVX2 and AVX512?
One way of doing this would be to create function pointers which conditionally point to different functions depending upon a preprocessor directive which selects the desired feature set. #if defined(__AVX512__) void (*func_ptr)() = _mm512_func; #else void (*func_ptr)() = _mm256_func; #endif int main() { fu...
If you're detecting AVX512 only at compile time, you don't need function pointers. The simplest way: don't define different names for the same function at all, just select which definition to compile in the .cpp file where you have multiple versions of it. That keeps the compile-time dispatching isolated to the file t...
62,438,479
62,439,181
Confusion with function pointer, __cdecl, and template
In Visual Studio 2019, I have written the following test codes, but the results confused me. #include <iostream> using namespace std; template<class T, class Func> int call(T x, Func f) { return f(x); } int square(int x) { return x * x; } int main() { int (*func0) (int) = square; // line 0, OK //int (func1)...
square and *square are the same type because functions decay, just like arrays do, to pointers, except (just like arrays) under certain contexts. In particular, decay is suppressed under typeid and &, but not under *, so typeid(square) gives you the type of square, int (__cdecl)(int), while typeid(*square) means typeid...
62,438,961
62,438,962
Why is the Base class data initialized before Derived class data
Consider this code: class Base { public: Base(): m_i{10} {} private: int m_i; }; class Derived: public Base { public: Derived(): m_f{100.0} {} private: float m_f; }; int main() { Derived d; } When Derived d; is instantiated C++ first calls Base() constructor and initializes Base's data - m_i - and only the...
1) The main reason for it is - Derived class should have access to Base class fields. Let me explain with an example: class Base { public: Base(): m_i(10) {} protected: int m_i; }; class Derived: public Base { public: Derived(): m_f(100.0) { m_i = 1; } void print() { std::cout << "Derived m_f=" << m_...
62,439,111
62,439,817
Move assignment in overloaded vector summation
I am going over A Tour of C++ (Section 5.2 Copy and Move). Following the instructions in the book, I have built a container called Vector (it mimics std::vector). My goal is to efficiently implement the following (element-wise) summation: Vector r = x + y + z; According to the book, if I don't have move assignment and...
There is a move elision takes place. According to the C++ 17 Standard (12.8 Copying and moving class objects) 31 When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for t...
62,439,455
62,439,737
Where should my project include new.h from? (Visual Studio and/or SDK corruption or version incompatibility?)
I have a project that started as a Visual Studio 2005 project, and is now a Visual Studio 2019 project. It is built using the 142 Platform Toolset on Windows 10, but for deployment on Windows 8.1 and later. So it selects the Windows 8.1 SDK, and sets WINVER, _WIN32_WINNT and _WIN32_WINDOWS all to 0x0603. It's an MFC pr...
Case (d): you are missing the Windows SDK 8.1 installation on the laptop. That needs to be done separately from the VS install. From the Visual Studio 2019 v16.0 Release Notes - Deprecations: The Windows 8.1 SDK is no longer available in the Visual Studio installer. Please upgrade your C++ projects to the latest Windo...
62,439,951
62,440,026
Managing extended objects in a single container
I was extremely surprised to see the following work. If you have a set of classes that extend each other, and you create a container for them using the base class pointer, how is it able to properly call all associated destructors? #include <iostream> #include <string> #include <vector> class A { public: A...
When A::~A() is invoked through a pointer/reference, it is called virtually, because A::~A() is declared virtual. This winds up invoking C::~C() instead, since the actual object being deleted is of type C. C's destructor implicitly calls the A and B destructors (but statically, not virtually). Note that a method with ...
62,440,242
62,440,361
Vulkan compute shader not stalling on infinite loop
I am trying to make a shader that stalls my program as so: #version 450 layout (local_size_x = 16, local_size_y = 16) in; void main() { while(true) {} } I am trying to call the pipeline associated with the shader like this: static void GpuCompute( EffectFramework& frame_work, const std::string& shader_pa...
make a shader that stalls my program Your operating system and graphics drivers don't like it when the device responsible for the primary user interface stops responding. Neither do the users of said operating system or said graphics drivers. Therefore, they don't allow you to do that. Any shader operation that runs ...
62,440,698
62,441,241
boost::this_thread::sleep_for sleeping entire program
C++98 and Boost 1.54 I'm having trouble figuring out why using boost::this_thread::sleep_for is sleeping my entire program. The only time and place the Wait() function is called is inside this thread, and this thread's sole purpose is to read file names in a directory and trigger an upload. But for some reason, when it...
it hangs there and sleeps all the other threads as well No it doesn't. If it seems that way, that is because the other threads were already stuck or finished. Look for things that block (mutex.lock, condition wait, IO operations, etc.) or check that the threads didn't exit. Notes Your seconds calculations is off. On...
62,441,306
62,441,351
Is there a good way to optimize the multiplication of two BigNums?
I have a class BigNum: struct BigNum{ vector <int> digits; BigNum(vector <int> data){ for(int item : data){d.push_back(item);} } int get_digit(size_t index){ return (index >= d.size() ? 0 : d[index]); } }; and I'm trying to write code to multiply two BigNums. Currently, I'...
If you use a different base, say 2^16 instead of 10, the multiplication will be much faster. But getting to print in decimal will be longer.
62,442,050
62,444,198
How to draw dynamic 2D grid that adjusts according to camera zoom: OpenGL
So my question is exactly like the title states. I'm not looking for a concrete code example, just some thoughts/guidelines on any preferred methods of doing this. In my 2D game engine, I like to have a grid that represents a certain amount of pixels (e.g 32x32 pixels). I specifically want to be able to define, the wi...
regardless of the rendering method First you have to compute the grid. I do it like this: get AABB (x0,y0,x1,y1) of screen in world coordinates The best is to have 3x3 matrix with accumulated all the transform converting from world coordinates into GL screen space: vec2 world,screen; mat3 w2s; screen = w2s*world; ...
62,442,065
62,447,840
Placing exclusive lock on read-only files in Linux
Assume that: 1) I have a folder on Linux that I only have "read" and "execute" permissions. 2) Somebody with higher privilege (with a "write" permission) will put some files into that folder. 3) Multiple processes of a program running in parallel will read and perform some data processing on the files. Requirement...
Any access (read or write) will suffice for a Linux flock syscall to place a lock on file, unlike fcntl lock which requires read access for a read lock and write for a write lock. You might be using libc that emulates flock on top of fcntl. To get what you need, invoke system call directly through syscall: #include <sy...
62,443,222
62,443,272
error: invalid conversion from ‘int (*)(int, int)’ to ‘int’ [-fpermissive]
I'm trying to create a program with functions that prints the smaller number between two numbers. But when i assign a function to a variable it shows this error: error: invalid conversion from ‘int (*)(int, int)’ to ‘int’ [-fpermissive] The code : #include <iostream> using namespace std; int minimum(int num1, int num2...
That happens because you call the function without any parameters, also min is never created and your function currently checks for maximum number. #include <iostream> using namespace std; int minimum(int num1, int num2) { int min; if (num1 < num2) min = num1; else min = num2; return min...
62,444,038
62,444,227
How to understand code like this in c++ [request->headers().Method()->value().getStringView())]
I am suppose to reduce it down to [request->headers().getMethodValue())]. I am fairly new to C++. Can someone please tell me how to understand this type of code? There are multiple . operator and -> operator. I loose track of the classes and others. It's a little overwhelming.
The . operator is used to access stuff inside the object (functions, variables etc.) the -> operator is just a . operator but for pointers. In your case you call request's headers function that returns an object. For that object then you call getMethodValue function.
62,444,448
62,444,475
OCI-22303: type ""."VARCHAR2_5_TYPE" not found
C++ code as below: stmt = con->createStatement("BEGIN ABC.INPUT(:1, :2, :3, :4, :5); END;"); oracle::occi::setVector(stmt, 1, id1, "VARCHAR2_5_TYPE"); oracle::occi::setVector(stmt, 2, id2, "VARCHAR2_5_TYPE"); oracle::occi::setVector(stmt, 3, data, "NUMBER_10_2_TYPE"); oracle::occi::setVector(stmt, 4, time1, "VARCHAR2_1...
You need to create the type outside the package as: create or replace TYPE varchar2_5_type is table of varchar2(5);
62,444,495
62,444,586
What's the real difference between "constinit" and "constexpr"?
constexpr int f() { return 0; } int g() { return 0; } constexpr auto c1 = f(); // OK constinit auto c2 = f(); // OK constexpr auto d1 = g(); // ill-formed constinit auto d2 = g(); // ill-formed int main() {} As illustrated in the code above, I cannot find any difference between constinit and constexpr. What's the r...
A constinit variable is constant initialized, but it is not usable in a constant expression, nor even automatically constant. Your main can legally contain this line c2 = 2; Yup, modification is possible after initialization.
62,444,773
62,446,947
Memory allocation issues using NTAllocateVirtualMemory and GetProcAddress not working
I am trying to write a little program which uses NTAllocateVirtualMemory and GetProcAddress instead of VirtualAlloc. This is what I have currently: #include "pch.h" #include "windows.h" #include <iostream> #include "Memoryapi.h" #include <wininet.h> #include <string> #include "HTTP_Requests.h" using namespace std; t...
Since your actual problem is to hide from anti-virus, I would suggest to use a static buffer. Make data sections executable(in Visual Studio) Specify Project->Properties->Linker->Specify Section Attributes. For uninitialized data uninitialized is still zero initialized /* global or static*/ char buf[20000]; specify .bs...
62,445,017
62,451,009
how __is_trivially_copyable is implemented inside g++ stl?
In stl algorithm, when the value type is triviall copyable, the copy algorithm will use memmove to accelerate this operation. I found that in file "type_trait", it uses following code to check whether an object is trivially copyable: template<typename _Tp> struct is_trivially_copyable : public integral_constant<bool, _...
A1: @HolyBlackCat is correct; __is_trivially_copyable is a compiler intrinsic. There's no real way to tell (in the language) whether or not an arbitrary type is trivially copyable. A2: The standard library looks to see if the iterators are raw pointers (as opposed to some class). If the iterators are pointers, then the...
62,445,042
62,445,932
How to call a generic std::function with a list of void* parameters?
I have a std::map where I store some arbitrary methods that I want to call later. map<string, function<void(void)>> methods; template<typename R, typename ...P> void storeMethod(const string& name, const function<R(P...)>& method) { methods[name] = method; } A the time of calling, I get the parameters to call...
You will have to wrap method in something that can remember the parameter types. struct OpaqueFunction { virtual std::any call(const std::vector<std::any> &) = 0; }; template <typename R, typename ... Args> struct OpaqueFunctionImpl : OpaqueFunction { OpaqueFunctionImpl(std::function<R(Args...)> f) : f(std::mo...
62,445,210
62,445,348
Segmentation fault for a particular case
I am writing a code which will edit a string.But, my code is giving a segmentation fault for an input "zzzzzzzzzz". I am unable to figure out the reason behind the segmentation fault. #include<iostream> #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t;cin...
It seems that you are hoping that this code while(i<(l-1)) will stop you trying to erase character in s that don't exist. But remember that l is the size of the original string, and in the loop you progressively shorten the string. I guess what you really need is while(i+1<s.size()) That way you are always testing ag...
62,445,392
62,445,612
How to add all subdirectories in "Include directories" in visual studios?
When cloning a repo on github I have made with lots of subfolders (like src,include and then several sub-directories in those) on a new PC I get a heap of errors that it can't find the paths for the include files. How do I quickly let Visual Studios know to look for include files in those sub-directories and not just t...
As far as I know there's no way to search for include files in subfolders. And it's obvious if this was possible it would not be relevant to do that as this will take more time to search them. But you can do one thing, when including files just add their relative path Such as #include "../src/header_file.h"
62,445,478
62,446,664
How to do the modulus of complex number more efficiently in CUDA?
I was trying to do the Fast Fourier Transform to the data I collected. After the FFT operation, I wanted to calculate the modulus of the cufftComplex type data. Therefore, I summed the real part square and imaginary part square, and then took the square root of the summation. The code are provided below also the assign...
If I want to shorten the execution time, how should I do it? I can think of at least five things (in no particular order) Get rid of the __syncthreads() call. It is unnecessary and will actively slow down your code Pass the kernel length*lines as a single argument to the kernel. Why have an every thread do an integ...
62,445,545
62,445,682
Number of times the integer that input occurs by using multiset
I tried to write a program that gives out the number of times it occurs when I gave the input. For example, 10 20 10. Number : 10. Number of times : 2 Number : 20. Number of times : 1 But instead my result gave me Number : 10. Number of times : 2 Number : 20. Number of times : 1 Number : 10. Number of times : 2 #includ...
You can create another vector. There will be only one element of each kind in it. void count_occurence(unordered_map<int, int>& m, vector<int>& vec) { vector<int> order; for (auto itr = vec.begin(); itr != vec.end(); ++itr) { if (m.find(*itr) == m.end()) order.push_back(*itr); +...
62,445,592
62,445,658
Getting wrong value for Millisecond delay
I am trying to get 1 millisecond delay but i am getting 15 times higher.I have also tried with windows Sleep(1) function which was also giving me the same result. why am i not getting exact millisecond delay? Where as it works with 1 second delay. #include <iostream> #include <Windows.h> #include <thread> #include <chr...
You are not getting the expected results, because your expectations are off. sleep_for is not to wait for exact time. From cppreference: Blocks the execution of the current thread for at least the specified sleep_duration. This function may block for longer than sleep_duration due to scheduling or resource content...
62,446,405
62,448,052
QML Tableview horizontal scrollbar
I am using TableView QML component, where each column width is set to the table total width divided by number of columns. This introduces some fraction parts and in result, a horizontal scrollbar is almost always visible in the bottom. But I don't want to disable scrollbar as I have ability of changing column width and...
columnWidthProvider is calculated once at adding column. I cant reproduce your bug with this. contentWidth become same as width TableView { id: table anchors.fill: parent columnWidthProvider: function (column) { console.log(parent.width , columns, parent.width / columns) ...
62,446,464
62,446,525
shared_ptr use_count() return 0 after assignment operator (=)
Im new to shared_ptr and can't wrap my around this, I want to store shared_ptr in custom struct. struct ThreadSafeQMsg { ThreadSafeQMsg(shared_ptr<ptree> control, shared_ptr<uint32_t> data=0, int data_size=0) { data_size = data_size; data = data; control = control; } size_t data_siz...
Inside the constructor, the names of parameters hide the names of data members; so these assignments like data_size = data_size; are just assigning the parameters to themselves and have nothing to do with the data members, which are kept default-initialized. You can initialize them in member initializer list as ThreadS...
62,447,304
62,651,795
How to run command in cmake with the same parameters that are passed to the compiler?
I need to run a few commands after I build my project with cmake. The commands will do some transformations to the source files in order to produce a new binary. The whole process would be like this: compile the target (executable or library) and link it (as it is now) run tool A on the compiled binary and produce an ...
Because it looks like you are compiling the library twice anyway, I would go with two targets. set(srcs <list of source files> add_library(target1 ${srcs}) add_custom_command(OUTPUTS semething_from_target1 DEPENDS target1 COMMAND aaa $<TARGET_POPERTY ... (get command line options )> $<TARGET_FILE:target1>...
62,447,327
62,448,956
data member pointer being shared c++
I have created two classes SystemClock which is used to show current time(by creating a pointer to struct tm from ctime) and another class called CustomClock which creates a time object from hours, minutes and seconds given by user. CustomClass inherits from SystemClock and SystemClock has a display method to display t...
The pointer is sheared, because localtime method is returning pointer to the internal object. The returned value points to an internal object... and The function also accesses and modifies a shared internal object... You can read more about it on: http://www.cplusplus.com/reference/ctime/localtime/
62,447,470
62,447,549
Why we use pointer to integer for max stl function instead for size_t data type(which is generally use) for array of characters in c++?
I was working on a problem and need to find the maximum character (alphabetically or we can say according to ASCII values) and found that size_t data type can't be use for returning from the max function defined in algorithm header file instead I found pointer to integer for that . below is the piece of code I am havi...
Because std::max_element is not only a function for arrays. It is a function that works with any iterator. And indexes are meaningful only for random access containers, so using an index as return value would unnecessarily limit the interface of the algorithm.
62,447,529
62,459,748
How do I reduce the running time of the code to justify text?
This is the Problem Statement in a nutshell: Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra space...
The linked problem statement starts with Given an array of words and a width maxWidth In the posted code the function justifiedText first traverses to vector passed as a parameter as if it is composed by lines of multiple words, extracted and copied into a new vector (using stringstream temporaries). Every string in ...
62,447,751
62,531,998
Does LMDB support random reads?
Suppose there's a large LMDB file, Normally, I would get its contents sequentially using mdb_cursor_get(cursor, &key, &data, MDB_NEXT) through a cursor. And now, To increase the read speed,I create a queue, dividing the LMDB into 10 equal parts and starting 10 threads to read each piece of content separately ,then put ...
In my tests, multi-threading did not improve the efficiency of reading LMDB, but doubled (or more)the reading time. Test method: Generate an LMDB with 10000 pieces of data and record the complete read time: 365s Divide the LMDB of this 10000 pieces of data into two equal parts and four equal parts, and read one equal...
62,447,953
62,448,735
efficient extraction of elements from a C++ unordered set
In C++ suppose you have an unordered set (https://en.cppreference.com/w/cpp/container/unordered_set) of strings - is there a way to efficiently extract all strings from that set that meet a certain criteria (e.g. find all strings in the set that begin with letter "a") using a method other than iterating through the ent...
For any criteria this is not possible, see this answer for some more details. Depending on your other needs, a sorted std::vector is highly likely to be the most efficient for the extraction part alone. Use algorithms like std::lower_bound to work with a sorted std::vector. In the end, your actual use cases is what det...
62,448,092
62,448,620
Why does va_arg(va_list, type) give me a C6285 warning?
Everything is working as intended, and I get the values I need from va_arg(va_list, type), but I get this warning everywhere I call va_arg: Warning C6285 (<non-zero constant> || <non-zero constant>) is always a non-zero constant. Did you intend to use the bitwise-and operator? Example code: void Logger::log(LogLe...
C6### error codes are IntelliSense codes. These are based on heuristics and are meant to point the attention to potential errors, but can also result in false-positives, which seems to be the case here; it's probably triggering on the va_arg implementation in the CRT: #define __crt_va_arg(ap, t) ...
62,448,165
62,448,360
How std::initializer_list Works?
I am currently studying c++11 i did not understand constructor of std::initializer_list it looks like this constexpr initializer_list() noexcept : _First(nullptr), _Last(nullptr) {} constexpr initializer_list(const _Elem* _First_arg, const _Elem* _Last_arg) noexcept : _First(_First_arg), _Last(_Last_arg) {} But H...
std::initializer_list is special. It is impossible to write a class that could be used as a constructor argument in the same way. The language rules specify how std::initializer_list works - or rather, how constructors that accept std::initializer_list i.e. initializer-list constructors work. And the language implement...
62,448,834
62,449,855
Concise bidirectional static 1:1 mapping of values and types
I'm going to start with how I imagine using the code I'd like to create. It doesn't have to be exactly like this but it's a good example of what I mean by "concise" in the title. In my case it's mapping of a type to a related enumeration value. struct bar : foo<bar, foo_type::bar> { /* ... */ }; // \_/ \...
As @yeputons said, friend-injection can help here. It's a spooky feature, and I can't say I fully understand how it works, but here it goes. #include <iostream> #include <type_traits> template <typename T> struct tag {using type = T;}; template <typename T> struct type_to_enum_friend_tag { friend constexpr auto a...
62,449,158
62,598,583
Why I'm unable to open/read txt file in C extension called from Python?
I try to pass file name from python to C\C++ .dll and make C\C++ code open/read that file. Here is a very simple example of what I'm trying to achieve using ctypes. Please pardon noobness of my C++ code. I'm learning here. //C++ code in example.cpp compiled to example.dll #include <stdio.h> extern "C" { char* _line;...
SOLVED. It was compiler issue after all. Instead of using cygwin I should've been using mingw-64 bit. https://www.msys2.org/ I followed instructions in this yt video: https://www.youtube.com/watch?v=aXF4A5UeSeM Works fine.
62,449,477
62,451,013
C++ wxWidgets: Change Font of Sizer
I recently started learning C++ and wxWidgets and now I'm building a calculator program. I have a grid sizer with buttons and I want to know is it possible to change the font of the whole sizer instead of changing the font of every single button?
Sizers are not windows and so don't have any font, so, no, you can't just call SetFont() on a sizer. You can iterate over all sizer items and call SetFont() on each item which is a window. Or, somewhat less efficiently (because you "waste" a window), but more conveniently, you can make all your button children of a wxP...
62,450,033
62,458,483
How to check why some symbol is required for linkage?
This question gets cumbersome, lets try short version: Usually when you fail with unresolved symbol reference it is quite strait forward, here you call something that linker cant find. You just feed your linker with library and it just works. Sometimes, there are cases when you banging your head on the wall and dont se...
Well, apparently I managed to answer the question not seeing the code as well as error message. Time to open my psi-consultancy. Concerning linking on Linux/ELF target, it is important to remember that linker, while trying to satisfy/resolve symbols, is merging (and copying to final executable) sections (aka segments)....
62,450,411
62,503,908
QDateTime::toString() fails when used in exit handler
I tried to log std::exit calls in my GCC10 compiled Qt 5 application. This fails when turning a QDateTime object into a string. It can be reproduced with the following snippet: void exitHandler() noexcept { QString b = QDateTime::currentDateTime().toString(); } int main(int pArgc, char* pArgv[]) noexcept { std::...
Exit handlers are called after deinitialization of static variables and thus it is unsafe to call functions that might access static variables. qdatetime.cpp for instance contains at least one static lookup table for the days of the week which is probably used by toString(). There might be more accesses to (already des...
62,451,260
62,451,377
Passing a unique pointer's pointer to a function that takes a double pointer
I have a function that effectively does this void foo(Class** c) { // memory checks and stuff (*c) = new Class(); // more stuff } I cannot change this function. To call this function I have to do something like this. Class* c = nullptr; foo(&c); if (c) { // stuff } delete c; I would very much prefer t...
Create a wrapper around foo: std::unique_ptr<Class> foo() { Class* c = nullptr; foo(&c); return std::unique_ptr<Class>(c); }
62,451,918
62,457,957
Reading user input after reading a file from stdin
I have a program that I start from a command line with a file pushed to stdin: main.exe < file.bin I read all the contents from the file like so: freopen(NULL, "rb", stdin); // it's a binary file long* buffer = new long[16000]; while ( fread(buffer, sizeof(long), 16000, stdin) == 16000); After all numbers are read,...
If you use a file file.bin as a stdin via main.exe < file.bin, you cannot simultaneously use console as a stdin using standard C or C++ libraries. Maybe you could try it with WinAPI https://learn.microsoft.com/en-us/windows/console/readconsoleinput And using std::cin to read binary data is unfortulately not possible: R...
62,452,153
62,454,752
Set a higher priority to a boost::asio thread wrt the process
I know that C++ has some ways to set priority on threads. Something like what is is being discussed here. Similar to that, is there something similar available in threads that boost::asio runs? I am doing an async_read and async_write to read and write data from the network. Note that I do want to set priority betweeen...
I'm with the commenters that doubt this will be useful. But to answer your question: there is no such thing as a Boost Asio thread. It is explicitly documented why: Threads And Boost Asio Consequently, it is the library user's responsibility to create and manage all threads to which the notifications will be deliver...
62,452,241
62,452,461
what is c++ compiler version on my device
in cmd I typed g++ -v which results the message : Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=C:/Program\ Files\ (x86)/CodeBlocks/MinGW/bin/../libexec/gcc/mingw32/5.1.0/lto-wrapper.exe Target: mingw32 Configured with: ../../../src/gcc-5.1.0/configure --build=mingw32 --enable-languages=ada,c,c++,f...
It seems as though your compiler version is 5.1.0 (from the directory name in the path) C++11, or C++14 or C++17 do not have to do with the version of your downloaded compiler. Any compiler should have all of the versions of the standard which the compiler has implemented included in its download (as Nicolas Dusart poi...
62,452,811
62,452,970
Divide complex numbers - conditions
I have a question. I wrote the operator in C++, which divides complex numbers. friend const Comp operator/(const Comp& x, const Comp& y) { Comp temp; temp.real = ((x.real * y.real) + (x.imag * y.imag))/(y.real*y.real + y.imag*y.imag); temp.imag = ((x.imag * y.real) - (x.real * y.imag))/(...
Is there any situation that we can't divide complex numbers? If you go for creating your own class for dealing with complex numbers instead of using std::complex , try to make it behave like a user would expect. That is: n/d when n != 0 and d == 0 gives inf, inf (or possibly -inf, -inf). n/d when both are 0 gives na...
62,453,083
62,454,075
how to prevent the implicit conversion of double value to integer
I am taking user input as integer and selecting the function to run depending on it. However, When I enter 1.3 as car_choice, it takes the 1 as input, runs the program for the first case. How can I prevent this? I am using C++. int car_choice; std::cout << "Please enter the vehicle types for calculations\n"; do { ...
The problem is that you aren't doing any input validation: you ask std::cin, an input data stream, for an integer. std::cin then builds an integer from that stream, consuming numerical digits (and maybe a - too) until either the stream ends, or until the next byte of data wouldn't be valid for an integer. Perhaps you s...
62,453,565
62,457,959
Bad: C++# input and output debug
this is my C++ homework 'debugging problem' it is about I/O. I have debugged many errors. And the program did not report an error, but its result is wrong. Its result should be this: Enter a number:2.3456 Enter a number:0.895 The value of x is:+2.346000000 The value of y is:8.95e-001 but my result is: Enter a number: 2...
You can remove these lines for ( int i = 0; buffer[ i ] != '\n'; i++ ) cout.put( buffer[ i ] ); and for (int i = 0; buffe[i] != '\n'; i++) cout.put(buffe[i]); just write cout << buffer; For me readNum didn't work as it should. You have to convert ASCII symbol to number everytime. And you need to ski...
62,453,839
62,454,105
Why does two different input to this scanf() gives two diffrent outputs?
#include <iostream> using namespace std; int main() { int n,m; scanf("%d : %d",&n,&m); cout<<n<<m; } Why does input given 1 2 gives an output 10 while input 1:2 gives output 12.
After running different samples of code based on your description. I found, scanf("%d :%d") will listen to the input of the user and when an input of type (value1:value2) supplied : will be used as delimiter. Whereas if you do not supply an input with : it will simply select the initial value and assign a GARBAGE value...
62,454,497
62,455,066
How to get a web page source code using QT Creator?
I'm using Qt Creator and C++ and need to assign a web page source code to a text variable. But not sure if I should use QWebEngineView, QTextBrowser or other class, and specially what function. QString sourcecode=someFunction(www.example.com);
You can include QtNetwork and try something like the following, where url_string is your http address as std::string : QNetworkAccessManager manager; QUrl url(url_string.c_str()); QNetworkRequest request(url); QNetworkReply *reply(manager.get(request)); QEventLoop loop; QObject::connect(reply, S...