question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
72,920,015
72,920,050
"static const" function and variable
I read so many answers saying static const functions can't exist. Eg. this Q&A. and this Q&A What if this is the use case: #include<iostream> using namespace std; class Sample{ static const int privx; static int privy; public: static int getPrivx(){ return privx; } static int getPrivy(){ ...
This code is illegal, it's const qualified static method class Sample{ public: static int fun() const { return 0; } }; This code is OK, it's a const qualified non-static method class Sample{ public: int fun() const { return 0; } }; This code is OK, it's a static method with a const ret...
72,920,343
72,920,565
How to ensure a weak_ptr is not created from a temporary shared_ptr?
Let's have class Foo and method void use_weak_ptr(std::weak_ptr<Foo>). Is there a way to ensure - preferably at compile time - that the method is not called with temporary? Allow this: auto shared = std::make_shared<Foo>(); use_weak_ptr(shared); Do not allow this: use_weak_ptr(std::make_shared<Foo>()); Edit: Godbolt ...
You "poison" overload resolution on rvalues void use_weak_ptr(const std::shared_ptr<Foo>&&) = delete; void use_weak_ptr(std::weak_ptr<Foo>);
72,920,442
72,920,486
CMake add list of subdirectories
In my CMake project I need to add a list of subdirectories. The correct way is not nice because I can not pass a list: add_subdirectory(Helpers) add_subdirectory(Lib1) add_subdirectory(Lib2) subdirs can pass a list, but is deprecated: subdirs(Helpers Lib1 Lib2) Is there a way to add subdirectories...
You could use foreach(): foreach(SUBDIR IN ITEMS Helpers Lib1 Lib2 ) add_subdirectory(${SUBDIR}) endforeach() You could even wrap this in a custom function function(my_subdirs SUB1) foreach(SUBDIR IN ITEMS ${SUB1} ${ARGN}) add_subdirectory(${SUBDIR}) endforeach() endfunction() ... my_...
72,920,641
72,920,677
How to simulate EAGAIN or EWOULDBLOCK when send data to socket
I have a non-blocking socket to send data to. When sending data to a socket in non-blocking mode, we can get EAGAIN or EWOULDBLOCK if there is not enough space in the socket buffer. If the send call returns EAGAIN or EWOULDBLOCK, I subscribe to the EPOLLOUT event in epoll to know when the socket is ready to resend data...
How i can test my code in this case? This depends a lot on your kind of application and protocol. In general to trigger the condition the socket write buffer needs to fill up. This can be done by sending lots of data and making sure that the receiver application does not read from the socket. But this will not work i...
72,920,805
72,920,848
How versatile are c++'s templates?
I want to write a highly optimized code in C++ and there is a templated structure which takes a type variable T. There is one function wow() in that structure that can be optimized to run twice faster if and only if the size of T is a power of 2. Can I use the better version of wow() without doing branching (use if or ...
I would use constexpr if and std::has_single_bit: #include <bit> template<class T> struct foo { void wow() { if constexpr (std::has_single_bit(sizeof(T))) { // sizeof(T) is a power of two } else { // not a power of two } } };
72,920,862
72,920,923
Why does template ordering matter when defining a method?
I have the following code: template<int n> struct array_container{double arr[n];}; template<int n> struct avg{ double first[n], second[n]; template <int q> array_container<q> get_avg(double p) const; }; I can add a definition for get_avg like this: template<int n> template<int q> array_container<q> avg<n...
Why is this so? Because when providing an out-of-class definition the first parameter clause template<int n> corresponds to the outermost enclosing class template while the second parameter clause template<int q> corresponds to the member template get_avg itself. More importanty when providing an out-of-class definit...
72,920,894
72,921,342
Reference to a vector element become invalid after n iterations
Program stop occur in this line guess = secret; From that, I guess that reference is broken, because if I change reference to simple value const string secret = word_list[idx_word]; the program finishes correctly. So, my question is why this happen. The word_list is not changed/resided in loop. Erorr occur on 392 ite...
word_list[0]; - this is a non-const operation in a QVector (see documentation, there is even a note about the possible detach) and since the reference count of your word_list is two due to the copy to possible_answers some lines above, the container has to do a detach and therefore your reference goes out of scope. If ...
72,920,937
72,924,499
How to get the number of fields in a boost-hana adapted struct?
Say I have the following struct: struct MyStruct { int field1; float field2; }; I would like to obtain the number of fields in the struct using boost-hana. #include <boost/hana/adapt_struct.hpp> BOOST_HANA_ADAPT_STRUCT(MyStruct, position, field1, field2); // this code does not work: constexpr std::size_t NU...
Hana specifically aims to simplify meta-programming by lifting type functions to the constexpr domain. In plain English: you shouldn't be using length<> as a "type function template" but as a normal function: Live On Coliru struct MyStruct { int position; int field1; float field2; }; #include <boost/hana.h...
72,920,979
72,924,031
Win32 Handle WM_NOTIFY message from Rich Edit Control
How can I retrieve information about what change is being made in a rich edit control when handling WM_NOTIFY? More specifically, I am confused because in the documentation for WM_NOTIFY it says that lParam points to an NMHDR structure but in the page for EN_CHANGE they say that lParam points to a CHANGENOTIFY structur...
If you read the EN_CHANGE documentation you linked to more carefully, you will notice this caveat: https://learn.microsoft.com/en-us/windows/win32/controls/en-change--rich-edit-control- Notifies a windowless rich edit control's host window that a change has occurred. A rich edit control sends this notification code in...
72,921,003
72,923,894
Why does RegOpenKeyExA fail to open a key path with a space in the name?
Why does RegOpenKeyExA throw a path not found error according to the error codes from Microsoft docs other paths (no spaces) do open flawlessly int res; HKEY hKey; res = RegOpenKeyExA(HKEY_CURRENT_USER, "SOFTWARE\\Policies\\Microsoft\\Windows Defender", 0, KEY_QUERY_VALUE|KEY_WRITE|KEY_READ|KEY_SE...
RegOpenKeyEx() allows spaces just fine. MANY Registry keys have spaces in their names. Error 2 is ERROR_FILE_NOT_FOUND, which means the key you are trying to open does not exist. And indeed, the Windows Defender key does not exist in HKEY_CURRENT_USER, it exists in HKEY_LOCAL_MACHINE instead. BTW, KEY_WRITE include...
72,921,071
72,921,365
binary '<': no operator found which takes a left-hand operand of type 'const _Ty' glm::vec3 in map
I've been dabbling with discregrids LRUCache, but I'm having trouble getting it working with glm's vec3's. I keep getting a binary '<': no operator found which takes a left-hand operand of type 'const _Ty' error, even though I've implemented an operator overload for the underlying std:map [file.hpp]: bool operator<(co...
The short form is your operator< is not being found due to how ADL works. In particular, C++ searches the namespaces of the arguments (and their base classes, and other related classes). You've placed operator< in the global namespace, which is not the glm namespace. So, you could either put the comparison in the gl...
72,921,127
72,922,577
Why is my thread execution jumping between CPU cores?
I recently started experimenting with std::thread and I tried running a small program that displays the webcam feed in a separate thread and I am using OpenCV. I am just doing this for "educational" purposes. What I noticed was that the thread seemed to keep jumping between cores which striked me as odd since I thought...
The default Linux scheduler schedule tasks (eg. threads) for a given quantum (time slice) on available processing units (eg. cores or hardware threads). This quantum can be interrupted if a task enters in sleeping mode or wait for something (inputs, locks, etc.). waitKey(25) exactly does that: it causes your thread to ...
72,921,359
72,921,562
Dereferencing a string pointer from a FreeRTOS queue
I'm trying to use the queue API that FreeRTOS provides to read a string data from an Interrupt Service Routine (ISR) on an ESP32 device. As strings are quite large data, I actually send the address of the string using a pointer. This seems to work as I can read the correct pointer adress (see example below). However, I...
Basically the pointers outlive the objects they point to. Let's break the ISR down as an example: void IRAM_ATTR ISR_GSM_RI(){ BaseType_t xHigherPriorityTaskWoken = pdFALSE; String sGsmEventData = "String sent from ISR"; //string is created on the stack String * pGsmEventData = &sGsmEventData; //its address ...
72,921,565
72,921,747
How to get two threads to work on the shared resource
I have a С++ class that has a databases_list_ vector defined. This vector contains database objects. I need to make two functions that will run on separate threads. And each function will use the databases_list_ vector. That is, this vector is a shared resource for my functions. In this case, I don't know the correct a...
You can lock a std::mutex every time you want to access the shared resource. You also access is_work_ from multiple threads and I therefore suggest making that std::atomic<bool> is_work_ instead. #include <atomic> #include <mutex> class Worker { private: std::thread check_oo_thread_{}; // thread #1 std::thread...
72,921,596
72,948,819
How to automatically append gtkwidget in new line when no horizontal space is available in gtkbox?
Let's say I have the following code m_box=gtk_box_new(GTK_ORIENTATION_HORIZONTAL,4); gtk_widget_set_halign (m_box, GTK_ALIGN_START); gtk_widget_set_valign (m_box, GTK_ALIGN_START); Now I am adding multiple widgets and running out of horizontal space. How can I make it responsive? NOTE:- I am using gtk4
This is not something a GtkBox can do. It's quite "dumb" in that it doesn't care about reflowing or anything like that. It does one thing and one thing only: putting child widgets next to each other in a specific orientation. For your use case, you might be more interested in Gtk.FlowBox, which rearranges its children ...
72,921,983
72,922,085
C++ spaceship-operator and user-defined types: comparing a subset of attributes only
I have two classes. The first one composing the second one. Both classes have its own synthetized attribute that doesn't collaborate to either ordering or comparision. In addition, I want to usestd::ranges::sort over a container of the second one, so I need to implement a strong-ordering. That's what I have: struct bas...
How should I appropiately efficiently overload operator<=>? The simplest way to do both would probably be to use std::tie and use the existing function template for operator<=> for tuple types: template< class... TTypes, class... UTypes > constexpr /* see link */ operator<=>( const std::tuple<TTypes...>& lhs, ...
72,922,675
72,946,528
Google S2 Geometry: polygon contains check does not work as expected
I'm using the Google S2 Geometry library to check whether a given geo point is within a polygon. The following assertion should pass, but is failing and I'm unable to explain what's going wrong: std::vector<S2Point> vertices = { S2LatLng::FromDegrees(60, -118).ToPoint(), S2LatLng::FromDegree...
S2 uses geodesic edges, so the loop is not just a rectangle on a flat map, but the "horizontal" edges are curved towards the poles following the shortest path on spherical Earth. For small distances, the difference from planar maps are negligible, but for huge distances like here the shortest path is quite different. T...
72,923,419
72,923,454
Compile C++ Code Using The Terminal Directly Without Save File.cpp
I need to compile C++ code directly in the terminal or CLI without saving the file When is use the below way, It shows me an error. gcc -x c - <<eof #include <iostream> using namespace std; int main() { cout << "Hello world"; } eof
You are trying to compile a C++ program using a C compiler. This works: g++ '-xc++' - <<eof #include <iostream> using namespace std; int main() { cout << "Hello world"; } eof
72,924,024
72,926,021
Slicing and Indexing Eigen matrix Error: how to index matrix correctly?
I have matrix u with size 11 by 15 where 11 is number of rows and 15 number of columns. I am trying to index my matrix so that the first five columns and the last five columns are equal to some expression. I am able to index the first 5 columns but not last 5 as the following: static const int nx = 10; static const int...
Thanks to @chtz from the comments, this fixed the issue: seq(last+1-nx/2, last)
72,924,527
72,924,578
retrive username and domain with GetUserNameExA
I am trying to get username and domain with GetUserNameExA function this is my code #include <windows.h> #include <Lmcons.h> #include <iostream> using namespace std; #include <windows.h> #include <Lmcons.h> #include <Security.h> #include <secext.h> DWORD main() { CHAR *username = [200]; DWORD ...
CHAR *username = [200]; should be this char username[200]; And this wcout << L"Hello, " << NameSamCompatible << L"!\n"; should be this cout << "Hello, " << username << "!\n";
72,925,058
72,925,102
Creating variadic template with template object containing string
I want to create a template that will take variadic number of a specific class that contains a string. When i try to make such a template class, it throws no instance of constructor "A" matches the argument list class A: template<template_string s> class A {}; class B: template<A... As> class B {}; template_string.h...
This is an instance of the "most vexing parse" problem, where it looks like you are declaring a function type instead of creating on object. Here's a complete working example, where I've replaced the function call () with the uniform initialization syntax {}: #include <cstddef> #include <string> using std::size_t; t...
72,926,596
72,926,617
Type deduction for a member function pointer
I know there are similar questions on SO, but the usages there seem different to what I have. Here is my MRE: #include <iostream> #include <functional> using namespace std; void freeFunction() {} struct Foo { void memberFunction() {} }; template<typename FunctionPtrT> void foo(FunctionPtrT* f) { f(); } template<typ...
General suggestion for type investigations I think the easiest way to answer questions like "what is the type of x in this context" is to put a static_assert(std::is_same_v<void, delctype(x)>); in that same context. The compiler will then tell you the static_assertion failed because void is not equal to the type of x, ...
72,926,648
72,926,709
how to map a class object and instantiate it
I'm trying to mimic this Python functionality: class Bla: def __init__(self, arg): self.arg = arg {"bla": Bla}["bla"](None) # create a Bla class dynamically I looked at this but it didn't help me... My C++ module looks something like this: // MyObj is an abstract class with all its subclasses using same s...
C++, in contrast to Python, is statically typed. Classes are not first-class objects and you can't store them. In the following I assume that MyObj is the abstract base that all "stored" types are meant to inherit from and that MyObj1/MyObj2 are some of these types. Instead of the classes themselves, you can store func...
72,926,766
72,926,818
Recursive print within std::cout
The input is N spaced integers. You have to read the input and print the input backwards. Source:(https://www.hackerrank.com/challenges/arrays-introduction/problem?isFullScreen=false) One of the solutions is: #include <iostream> int main() { int N,i=0; std::cin>>N; int *A = new int[N]; while(std::cin>>A...
The << operator (even though it's overloaded for output streams and is no longer a bitwise shift) has higher precedence than the && operator. Thus, we can add parentheses to your while statement to make it clearer: while ( (std::cout << A[--N] << ' ') && N ) ; The expression within the added parentheses wi...
72,926,985
72,927,090
Pass array from C++ to C#
I need to pass an array from C++ to C# The C++ header is the following extern "C" GMSH_API void GMSH_Model_OCC_Fragments(int* arrayPtr); The C++ cpp is the following void GMSH_Model_OCC_Fragments(int* arrayPtr) { int array[] = {1,2}; arrayPtr = array; } The C# code is the following [DllImport("GMSHCSHARP.dll"...
When you call C++ from C# you have to play by the rules of C++, so you cannot assign an array by arrayPtr = array; You can however fill an array given by C# C++ Function void someFunction(char* dest, size_t length){ char* someData = "helloWorld"; size_t copyLen = std::min(length, strlen(someData)); mem...
72,927,080
72,927,806
How Could I Register Types With A Deleted Copy Constructor To QMetaType?
The Problem: I want to create an object instance at runtime using QMetaType by the type name. But I couldn't register the type because it's a QObject and I don't have access to the implementation to change it. Duplicate Question(s): How to properly use qRegisterMetaType on a class derived from QObject? I couldn't und...
A Non-portable And Non-documented Solution: Specialize the QtMetaTypePrivate::QMetaTypeFunctionHelper for your type: namespace QtMetaTypePrivate { template <> struct QMetaTypeFunctionHelper<MyObject, true> { static void Destruct(void *address) { static_cast<MyObject *>(address)->~MyObject(); } static void ...
72,927,098
72,927,147
Recursive Type Dependencies in C++
#include <iostream> #include <cstdlib> class Egg; class Chicken; class Egg { public: Chicken *creator; Chicken getCreator() { if (!creator) return Chicken{}; return *creator; } }; class Chicken { public: Egg creator; Egg getCreator() { if (&creator == 0...
You need to define the member functions after the full definitions of the necessary classes have been seen. Example: class Egg; class Chicken; class Egg { public: Chicken* creator; Chicken getCreator(); // declaration only }; class Chicken { public: Egg creator; Egg getCreator(); // declaration only }...
72,927,480
72,927,732
Reading integers and strings from a text file and storing in parallel arrays
I have a text file that stores the index, student name and student ID and I am trying to read them into an array of integers index, arrays of strings studentName and studentID. I'm having problems storing the student's names because they could be more than a single word. I could separate the items in the text file by c...
It's an error to read one line into one student property with the given input format. You need to read one line and then split the information in this line into the 3 properties. std::stoi can be used to convert to convert the first part of the line read to an int. Futhermore it's simpler to handle the data, if you cre...
72,927,672
72,927,734
CMake creating libraries that depend each other
my goal is to create libraries like client and generator and use them in src/main.cpp, but sometimes these libraries depend each other. In this case: client/User.hpp uses generator/IdGenerator.hpp Project │ ├── CMakeLists.txt ├── libs │   ├── CMakeLists.txt │   ├── client │   │   ├── CMakeLists.txt │   │   ├── User.cpp...
I misunderstood what the problem was initially, but now I think this might help. Try adding to the CMakeLists.txt of your client instead of include_directories(generator/) this command target_include_directories(libclient PUBLIC <Path to your generator file>) Maybe you need to experiment a little to get the path corr...
72,928,619
72,928,763
confusions about a simple smart pointer implementaion
The following code is abstracted from the book << Hands-On Design Patterns with C++ >> by Fedor G. Pikus published by Packt. Some confusions have been bugging me for weeks. (1) How the char array mem_ is initialized? (2) Is allocate used to allocate memory? How? (3) Why does mem_ == p ? How was the memory delocated? //...
How the char array mem_ is initialized? mem_ is not initialized as in filled with values until the use of the custom new operator in new(&a_sh_obj) int(42). This only initializes a small portion of the memory though. Space is allocated on the stack however when you create the local SmallHeap a_sh_obj; variable in mai...
72,928,680
72,928,730
Tidying function template to avoid duplication: decltype issues
I have the following class which wraps a member function: #include <cstdio> #include <type_traits> #include <utility> using namespace std; class testclass { public: double get() { return d_; } void set(double d) { d_ = d; } double d_ = 0.0; }; template<typename Retriever, Retriever retrieverFunc, typenam...
Retriever is supposed to be the value, not the type, of the non-type template argument. So it should be declared as non-type template parameter. Since you want the type to be deduced, the type of the non-type template parameter should be auto. Equivalently for Updater: template<auto Retriever, auto Updater, typename Ow...
72,929,159
72,929,258
How to use concepts to pass an argument to a class method?
I have an optional_monadic class that I inherit from the std::optional class template <class T> class monadic_optional : public std::optional<T> { public: using std::optional<T>::optional; monadic_optional(T value) : std::optional<T>(value) {} } In this class I describe the method t...
This is pretty trivial with invokable. And you don't have to require it to become a std::function: auto and_then(std::invocable<T> auto func) -> monadic_optional<std::invoke_result_t<decltype(func), T>> { if(this->has_value()) return std::invoke(func, *this); return std::nullopt; }
72,929,177
72,929,506
Correct way to check bool flag in thread
How can I check bool variable in class considering thread safe? For example in my code: // test.h class Test { void threadFunc_run(); void change(bool _set) { m_flag = _set; } ... bool m_flag; }; // test.cpp void Test::threadFunc_run() { // called "Playing" while(m_flag == true) { f...
Actually synchronizing threads safely requires more then a bool. You will need a state, a mutex and a condition variable like this. The approach also allows for quick reaction to stop from within the loop. #include <chrono> #include <condition_variable> #include <iostream> #include <future> #include <mutex> class Test...
72,929,287
72,929,458
What part of overload resolution (or more generally of the function call processing) does the value category of the argument play a role in?
C++ Templates - The Complete Guide, in §C.1, reads Overload resolution is performed to find the best candidate. If there is one, it is selected; otherwise, the call is ambiguous. Then, in §C.2, ranks the possible matches (of a given argument with the corresponding parameter of a viable candidate) like this (my emph...
why the value category is not mentioned at all in the points above? It is mentioned in the book as can be seen as quoted below. In particular, if you continue reading further then you'll see that the section C.2.2 titled Refining the Perfect Match does mention the part about distinguishing between different perfect m...
72,929,601
72,930,824
Templated Proxy in wrapper class issues
I asked previously about the following class, which is a wrapper around a member function. I now want to add "plugin" functionality to it via a proxy class. My wrapper class's operator* returns a proxy object on which I can then assign and retrieve as shown below: #include <cstdio> #include <type_traits> #include <ut...
You were missing a & from the decltype expressions when trying to instantiate the Wrapper template: Wrapper< decltype(&testclass::get), ^ decltype(&testclass::set), ^ testclass, LOGGING_WRAPPER_PROXY > pp2(&testclass::get, &testclass::set, &tc); Generally, when working with t...
72,929,739
72,930,096
Why does the compiler create a variable that's only used once?
Consider the following two examples, both compiled with g++ (GCC) 12.1.0 targetting x86_64-pc-linux-gnu: g++ -O3 -std=gnu++20 main.cpp. Example 1: #include <iostream> class Foo { public: Foo(){ std::cout << "Foo constructor" << std::endl;} Foo(Foo&& f) { std::cout << "Foo move constructor" << std::endl;} F...
In Foo f = bar(); Baz baz(f); return 0 It is indeed obvious that f will never be used again and the compiler probably even works this out. However the compiler isn't allowed to move f into baz, all optimisations done by the compiler must result in your program having the same behaviour (if the program is well defined ...
72,930,427
72,939,308
How to load data into a vector from a text file that has been created inside the same program. in C++
I want to load data from a Text file that has been created in the same program into a vector of strings. But no line of text is getting pushed into the vector here. Here First I am reading data from some input file and then doing some operations (Removing extra spaces) on it then I save this file as "intermediate.txt"....
Here's a mini-code review: #include <bits/stdc++.h> // Don't do this; doesn't even compile for me using namespace std; // Don't do this either int main() { string inputFileName; cout << "Enter the Input File Name: "; cin >> inputFileName; ifstream f1(inputFileName); // Bad name ofstream f0("...
72,930,594
72,930,640
Does constructor in cpp doesnot return anything?
It is said that constructor doesnot return anything.But if constructor doesnot return anything, then how do this code segment works: *this=classname{args};. I hope someone could shed me some light on whats actually going under the hood. A complete code: #include <iostream> using namespace std; class hell { private: ...
The statement *this = hell(4, 6); does two things: First it create a temporary and unnamed object of the class hell, initialized using the values you use to pass to a suitable constructor. Then that temporary and unnamed object is copy-assigned to the object pointed to by this. It's somewhat similar to this: { ...
72,931,024
72,931,130
Why += works when inserting string in vector<string> and then pushing in 2d string vector, but doesn't work when inserting char by char?
I was creating a vector of strings of size 4x4 with all characters as dots i.e. I was creating: .... .... .... .... And then I had to push this vector of strings in a vector of vector of strings like in the code below: int main() { vector<vector<string>> ans; int n=4; vector<string> matrix(n); for(int ...
This code: int n=4; vector<string> matrix(n); Will create a vector filled with n default-constructed strings; i.e. a vector with 4 empty strings. So, in the following loop, you're accessing each string with an out-of-bound index (which is undefined behavior): for (int i = 0; i < n; i++) { for (int j = 0; j < n; j+...
72,931,173
72,932,107
Why std::shared_ptr control block need to hold a pointer to managed object with its correct type
I am looking at the shared_ptr implementation in the following post. One question that is not entirely clear to me is, why in addition to the pointer stored with T* type in shared_ptr class itself, author also needs to store the second copy of the managed object's pointer with its concrete type in the control block (i....
One case is when using shared_ptr's alias capability. Create a shared_ptr using an object's member but the control block is the same and thus the reference count. class holder : public std::enable_shared_from_this<holder> { int member; public: std::shared_ptr<int> get_member() { return std::shared_ptr<int>(shar...
72,931,394
72,931,439
AzerothCore Unable to connect to server, probably WorldSocket Malformed request sent by client
I am using AzerothCore locally and when I try to log in - I am stuck at "Authenticating". Previously on login attempt - a error occured, WorldSocket Malformed request sent by client, But after opening the ports for both inbound and outbound connections - it dissapeared. Therefore, no error message, just stuck at "Authe...
WorldSocket Malformed request sent by client WorldSocket::ReadHeaderHandler(): client 111.222.11.22 sent malformed packet (size: 1234, cmd: 3333333) means some machine anywhere on the planet sent a random portscan to your IP. Not related to your actual problem. You should try and set the realmlist to the LAN IP of th...
72,931,994
72,932,771
C++ Template Argument Deduction with Additional Specified Template Arguments
I have encountered an issue with template argument deduction. The following complies without issues, the compiler can deduce the template argument: template<size_t a_size> class DummyBase { public: DummyBase() = delete; constexpr DummyBase(const char (& i)[a_size]) { } }; constexpr const auto dummy = Dum...
Unfortunately, "Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place." - https://en.cppreference.com/w/cpp/language/class_template_argument_deduction You could use a wrapper function to do what you want, but ...
72,932,091
72,932,139
Is std::equal guaranteed to short circuit?
I would like to compare a nul-terminated string against a string literal. I hope to use std::equal and am curious if this code is well-defined according to the C++ standard: #include <algorithm> bool is_foo(const char *str) { const char *lit = "foo"; return std::equal(lit, lit + 4, str); } If std::equal is gu...
My reading of the C++ standard indicates that this is pedantically undefined behavior based on the following remark: Remarks: If last2 was not given in the argument list, it denotes first2 + (last1 - first1) below. This is referring to overloads of std::equal that do not supply the second sequence's ending iterator. ...
72,932,948
72,932,995
C-plus-plus coding errors
I am learning C++ and I have to complete an Object Oriented Program. I am struggling to understand why I am getting an error. Please give as much as detail as possible when explaining because it would be helpful in the journey of teaching myself C++. Below is my initial code and the error: #include<iostream> using name...
By 2(length * width) I assume you really mean 2*(length * width) and this color = black; should probably be color = "black";
72,933,156
72,933,186
Is there any risk if I call clear when loop a vector?
I want to call clear when loop to visit the vector. I think this will be dangerous, but in my experiment code below, it seems ok to run, it just stop the loop when i called clear. #include <bits/stdc++.h> using namespace std; int main() { std::vector<int> a = {1,2,3,4,5}; for (size_t i = 0; i < a.size(); ++i) { ...
There is a very, very major temptation that when you have a loop that looks like this: for (size_t i = 0; i < a.size(); ++i) { then you will be under the impression that looking at a[i] and/or modifying it, freely, inside the loop, whenever you have an urge to do so, is perfectly acceptable. And it is. Unless you alre...
72,933,324
72,946,116
how could I create a file in this path : "~/testUsr" by using boost
I want to create a file in the path "~/testUsr" while I don't know which "testUsr" exactly is. if I just use path "~/testUsr", it will generate a directory "~" in current path instead of "home/testUsr"; // create directories std::string directoryPath = "~/testUsr"; if(!boost::filesystem::exists(directoryPath)){...
Using a helper function from Getting absolute path in boost Live On Coliru #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <iostream> using boost::filesystem::path; struct { void WriteConfigFile(std::ostream& os) const { os << "[section]\nkey=value\n"; } } static confi...
72,933,479
72,934,922
The Procedure entry point pointstd::from_chars could not be located in the dynamic link library libpqxx-7-7.dll
I am compiling a C++ program on windows under MSYS2 MinGW and I am using the libpqxx library, the program compiles fine but when I go to run it from file explorer I get the following error The Procedure entry pointstd::from_chars(char const*, char const*, double&, std::chars_format) could not be located in the dynamic...
I have fixed the problem, I just needed to add a few more dll files to the directory in which my program resides and now it starts! the dll files required are: libintl-8.dll libstdc++-6.dll these dll files can be found in the bin folder under the mingw64 folder Thanks to @HolyBlackCat for pointing me in the right dire...
72,933,995
72,934,095
How to not allow conversion from temporary shared_ptr to weak_ptr for derived types
I have asked this question for concrete types. The provided solution is sufficient for those, but when it comes to inheritance, it fails. Would there be a solution to that as well? Lets have a inheritance of classes Foo and IFoo such that class Foo: public IFoo and a function void use_weak_ptr(std::weak_ptr<IFoo>). Is ...
One of the possible solutions - overload use_weak_ptr for all std::shared_ptr. template <typename T> void use_weak_ptr(std::shared_ptr<T>&&) = delete; https://godbolt.org/z/Tj1a134bd The linked answer is not a good answer. const std::shared_ptr<IFoo>&& - const is redundant.
72,934,107
72,959,805
How to use Additional Module Dependencies in C++20
I created a TestModule.ixx in one folder and I want to use import TestModule in my cpp project(in different folder). I tried TestModule=E:\XXX\TestModule.ixx.ifc; in properties-> Additional Module Dependencies, but got error lnk2019. Q: How to import module in other files? Is there a way like adding header file direct...
In the build parameters we need to add it as an option. When it comes to visual studio below is the way worked. Similarly there will a build option for other compilers. In Visual studio (for MSVC) - Project properties--"C/C++"--Command Line--Additional options https://learn.microsoft.com/en-us/cpp/build/reference/modul...
72,934,138
72,934,173
how can I deal with this error: `cannot convert argument 1 from 'Node *' to 'Move'`
I am new to C++ and I am trying to build a Monte Carlo Tree Search from scratch. This structure allows me to traverse from root node to leaf node and also from leaf node to root node. So the node that has a NULL parent is the root. Each node can have multiple children. This structure has to be capable of creating and d...
The problem is that children is a vector with elements of type Node(and not Node*) and you're trying to add item which is of type Node* into. To solve(get rid of) the error you can either make children to be a vector of Node* or you can dereference the pointer item before adding it into children.
72,934,202
72,936,546
sh: 1: Syntax error: Unterminated quoted string\n
I am making an online judge in django frame work I am trying to run a c++ program inside a docker container through subprocess. This is the line where I am getting error x=subprocess.run('docker exec oj-cpp sh -c \'echo "{}" | ./a.out \''.format(problem_testcase.input),capture_output=True,shell=True) here oj-cpp is m...
subprocess.call(shell=True) has some significant security problems and I'd avoid it whenever possible. It opens your application to a shell injection attack. You're actually seeing this in your code: if the string in problem_testcase.input contains any characters that are meaningful to a shell, the shell will interpr...
72,934,250
72,934,294
I am stuck in this binary search problem in geeks for geeks (time limit exceeded)
C++ I don't know what went wrong or am I missing something ? always getting a time limit exceeded. class Solution { public: int binarysearch(int arr[],int n,int k){ int low = 0; int high = n-1; while(low < high){ int mid = (low + high)/2; if(arr[mid] == k){ ...
Here's a hint. Take a closer look at this: else if(arr[mid] < k){ high = mid + 1; } else{ low = mid-1; } Now ask yourself. If arr[mid] is less than the value to be searched for, what range of indices should be searched for on the next iteration? Then compare tha...
72,934,253
72,939,243
How to use multi-threading in C++ binomial pricing?
I'm new to multithreading in C++, and I am not sure how to apply it. Can anyone help? I'm trying to make the BinomialTree function multithreaded, This is what I have tried so far: thread th1(BinomialTree,S0, r, q, sigma, T, N); th1.join(); But it doesn't work int main() { double K = 100; double S0 = ...
From BinomialTree tree(S0, r, q, sigma, T, N); double callPrice1 = tree.Price(europeanCall); it looks like BinomialTree tree(...) is the definition of an object, and tree.Price is the actual function call. Your thread probably should be running the &BinomialTree::Price function. That said, thread th1(&Binomial...
72,934,313
72,934,331
Function not updating internal state of mt19937
I have a function that generates and writes random integers: void randint(int min, int max, int times,std::mt19937 rng){ std::uniform_int_distribution<int> dist(min, max); for (int i=0;i<times;i++){ std::cout<<dist(rng)<<' '; } } When this function is called, generates numbers from the mt19937 ob...
You are passing the object by value (i.e. you are copying the object when you call the function). Use a reference void randint(int min, int max, int times,std::mt19937& rng){
72,934,473
72,936,522
Retrieve Path by Wildcard in custom taget CmakeLists.txt
I'm trying to create a custom target in a CmakeList.txt which I'm planning to execute during the build process with Conan. When executing the build with conan build the sources are compiled and built, creating an output file with a dynmic name and a .a file extensions. Now my question is how is it possible to retrieve ...
If you want to manipulate created library after it is built, you can use add_custom_command with generator expressions: #create library add_library(my_lib STATIC my_lib.cpp) # list the contents of a newly created library add_custom_command( TARGET my_lib POST_BUILD COMMAND ar -t $<TARGET_FILE:my_lib> ...
72,934,598
72,934,755
Specialization of variadic template function over the non-variadic arguments
I have a template for a function that accepts at least one parameter and performs some formatting on the rest: template <typename T, typename... ARGS> void foo(T first, ARGS&&... args) { // ... } I want it to do a different thing when the first parameter is of a specific type. I like the compiler to choose this pa...
If you have access to c++17 or later, using if constexpr you can retain the true statement in the foo, at compile time, as follows: #include <type_traits> // std::is_pointer_v, std::is_same_v template <typename T, typename... ARGS> void foo(T first, ARGS&&... args) { if constexpr (std::is_pointer_v<T> // is point...
72,934,901
72,935,772
inline constexpr have external linkage?
I know global constexpr variables have internal linkage. so how is it that inline constexpr are introduced with having external linkage? does adding inline just converts internal linakges to external linkages in all cases?
There seems to be a little bit of confusion about what "linkage" and "inline" actually means. They are independent (orthogonal) properties of a variable, but nevertheless coupled together. To inline a variable one declares it inline. Declaring a constexpr variable at namescope does not imply inline [1]. To declare a va...
72,934,928
72,935,043
SEGMENTATION FAULT for my code , need guidance with debugging
I am using the below code to solve the rat maze problem from geeksforgeeks.However I am getting the segmentation error and I am unable to debug it.Can someone guide me with the debugging? Here's the code: class Solution{ public: string x=""; void rat(vector<vector<int>>&m,int n,vector<string>&ans,int i,int ...
Seem very likely to me that this code if(i>0) { x+="U"; rat(m,n,ans,i-1,j); } x.pop_back(); should be if(i>0) { x+="U"; rat(m,n,ans,i-1,j); x.pop_back(); } Same error several times. The way you have written it, you will remove characters from x that ...
72,935,628
72,965,664
FLTK - Why fl_width function returns -1 for the length of a char array on a Linux machine?
I am using the fl_width function to create widgets whose size depends on their label (e.g., some Fl_Box). In the documentation for this function one reads FL_EXPORT double fl_width (const char *txt) Returns the typographical width of a nul-terminated string using the current font face and size. I encountered anyway ...
One should invoke fl_font(Fl_Font face, Fl_Fontsize fsize) first. As user7860670 suggested in the comments to the question, one have to invoke fl_font(Fl_Font face, Fl_Fontsize fsize) for having a proper behaviour for the fl_width() function. This is also explained in the documentation of fl_font and in the (local) hea...
72,935,819
72,935,985
When to use reinterpret_cast without disobeying the strict aliasing rule?
For a long time I've used reinterpret_cast like this: static_assert(sizeof(int) == sizeof(float)); int a = 1; float b = *reinterpret_cast<float*>(&a); // viewed as float in binary. However, when I reviewed type conversion in C++ recently, I found that it's UB when the strict aliasing rule is considered! Dereferencing ...
When you use a reinterpret_cast in your code, your are telling the compiler: "I know what I'm doing – just implement the cast and trust me that the result will be OK to use." The compiler will then use the result of that cast as it would any other object of the specified destination type. So, if you know that a particu...
72,935,947
72,937,802
CMake imported targets in add_subdirectory not available in main CMakeLists.txt
I want to build an application that depends on the OpenCV (version 3.4.6) viz module. This module has the VTK library (version 7.1.1) as dependency. I want to use ExternalProject to build both, the vtk library and the opencv viz module and subsequently want to build the main application, all in one cmake run. . ├── CMa...
Unlike to normal targets, which are global, an IMPORTED target by default is local to the directory where it is created. For extend visibility of the IMPORTED target, use GLOBAL keyword: add_library(opencv_core SHARED IMPORTED GLOBAL) This is written in the documentation for add_library(IMPORTED): The target name has...
72,936,121
72,957,664
what is the optimize argument in pcap_compile( , , , int optimize, ) in npcap library?
pcap_compile(pcap, &fcode, "tcp", 0, PCAP_NETMASK_UNKNOWN) Here I have set to 0 and it is working, but I want to know what it does. I am trying to filter tcp packets in a pcap file. And does pcap_setfilter() reconstructs pcap file into a given fcode?
Well, as stated in the pcap_compile man page, optimize controls whether optimization on the resulting code is performed. OK, but of course you might be wondering, "What does that really mean?" To answer that question, I think it's best to provide an example. Consider the following capture filter: icmp or udp port 5...
72,937,106
72,982,039
How can I interact with html elements use QT
For example, I have a simple HTML page with button and label (or something else). How can I change the text in label (or something else) and catch the button click use QT. I try to use QWebEngineView to show html, but I don`t know how to interact with elements from QT modul, just change the url, but I dont think its a ...
To be able to interact with HTML rendered with QWebEngine you need to use QWebChannel. You can find the basic guidelines at Qt WebChannel JavaScript API page. To implement intercommunication with JavaScript in your HTML page you need: Add Qt += webchannel in your project file Implement a QObject derived class that sh...
72,937,139
72,937,419
Invalid conversion on template argument type?
With help from this question, I have gradually built up this code, a wrapper around a class member function. The idea is that I can use operator* on my property to write to the class object: #include <cstdio> #include <type_traits> #include <utility> using namespace std; class testclass { public: double get() {...
The cause of the problem: struct Wrapper is a struct with 4 template parameters, and the last of them has a default: template<typename Retriever, typename Updater, typename OwningClass, template<typename PropertyType> class WRAPPER_PROXY = DEFAULT_WRAPPER_PROXY> struct Wrapper { /* ... */ ...
72,937,566
72,987,189
What is the true getrusage resolution?
I'm trying to measure getrusage resolution via simple program: #include <cstdio> #include <sys/time.h> #include <sys/resource.h> #include <cassert> int main(int argc, const char *argv[]) { struct rusage u = {0}; assert(!getrusage(RUSAGE_SELF, &u)); size_t cnt = 0; while(true) { ++cnt; ...
The publicly defined tick interval is nothing more than a common reference point for the default time-slice that each process gets to run. When its tick expires the process loses its assigned CPU which then begins executing some other task, which is given another tick-long timeslice to run. But that does not guarantee ...
72,937,810
72,938,280
Making a function in a struct template
So i made a template struct cause i want to be able to decide what type i give to my val. But when creating a function i don't know how to do it. Here's what i'm doing: In my .hpp template<typename T> struct Integer { T val; void setUint(const T &input); }; Now i can set what variable i want in the val and wha...
A template function is a way to operate with generic types (you may consider the type as an argument). Your template parameter T allows to pass different types to a function when you invoke the function (which means, simply said, you may replace T with some other types int, double, ...) Please, have a look at the foll...
72,939,306
72,940,705
How to set `sf::Drawable` positions sfml
I'm trying to declare a sf::Drawable * property inside my class body. the code i already wrote: #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> class View{ protected: sf::Drawable *view; }; and inside the class constructor, I want to use the view properties: class View{ public: View(){ view->...} prot...
Indeed, sf::Drawable doesn't have a setPosition method. You could instead use sf::Transformable*, which does have setPosition. If you need to have drawable properties, then... If all your items are either shapes/sprites/texts, consider walking down the inheritance chain and use sf::Shape, sf::Sprite, or sf::Text. Make...
72,939,414
72,939,894
c++ classes and vector members
I have checked Stack Overflow for a sample of these class vectors and none of the answers point out common uses of vectors in a class . My code works but I have a few questions on it . I have a struck of objects that is stored in a class member vector struct Station { std::string StationName; int StationId; ...
Is this the correct way to add station to the stations vector ? It's a perfectly fine approach, just a little inefficient. Is this copy or move Semantics ? Copy semantics (this->Stations.push_back(s); invokes the version of push_back taking a const reference and copies it into the vector). Minimalist changes could ...
72,939,460
72,939,842
curl_easy_perform() API crashes
I am trying to get the idea about libcurl and I am trying to download simple photo from the url. But my program crashes when it goes inside curl_easy_perform() API. Any idea about it? #include <stdio.h> #include <curl/curl.h> #include <QDebug> #include <string> int main(void) { CURL *curl; FILE *fp; CURLcod...
I wonder if you are using libcurl library as a win32 dll or static library, according to the libcurl official documentation, it says If you are using libcurl as a win32 DLL, you MUST use a CURLOPT_WRITEFUNCTION if you set this option or you will experience crashes. You may want to see in here: click
72,939,957
72,940,037
How to pass in a callable object into a template class's constructor, able to call it later?
I want a class template whose constructor accepts (among other things), a callable argument. The class can then store a reference/pointer to this callable object and later call the function. I'll try to sketch out what I'm looking for here: template <typename T> class MyClass { public: MyClass(T _a, Callable& _f) :...
I've tried implementing Callable as a type erasure Concept That's a good idea, but the implementation has already been done for you. Use the type std::function<float(T)> as your Callable. The template argument to std::function is a function type, written in general as ReturnType(ParamType1, ParamType2,...). See std::...
72,940,070
72,940,120
I cant make the asterisk operator overloading it does nothing on the code below it should repeat my string 5 times but it doesnot
I can't make the asterisk operator overloading work. It does nothing on the code below. It should repeat my string 5 times, but it doesn't. .h file class Mystring { friend std::ostream &operator<<(std::ostream &os, const Mystring &rhs); friend std::istream &operator>>(std::istream &in, Mystring &rhs); private:...
Your operator* will repeat the string, but you throw away the result of s3*5. Try cout << s3*5 << endl;.
72,940,647
72,940,901
C++ : curly brackets with std library type
I try to understand the docs for std::less, where the following example is given for the usage with a template. #include <functional> #include <iostream> template <typename A, typename B, typename C = std::less<>> bool fun(A a, B b, C cmp = C{}) { return cmp(a, b); } int main() { std::cout << std::boo...
This demo-code suffers from so-called 'uniform initialisation' (broken by design, be careful with its use especially in template code!), classic way to write the same code before uniform initialisation is: std::less<int>()(5, 5.6); // others analogously std::less is a callable class, a so-called 'functor', which means...
72,940,979
72,941,406
Storing 2^31 in an `int`
Looking at links such as this and this, I understand that unsigned int in C++ should be of 16 bits. As such, the maximum value that it can store should be 32767. a. Why can we store INT_MAX in an int variable, such as: int res=INT_MAX; b. How is the code like below which calculates the power of 2 valid (runs withou...
a. Why can we store INT_MAX in an int variable, such as: int res=INT_MAX; INT_MAX is the maximum value that can be store in int. Per definition that can be stored in an int. b. How is the code like below which calculates the power of 2 valid (runs without any error/warning): ... because the constraints say: -2^31 <=...
72,941,116
72,941,252
CUDA optimise number of blocks for grid stride loop
I have started implementing a simple 1D array calculation using CUDA. Following the documentation I have first tried to define an optimal number of blocks and block size ... int N_array = 1000000 ... int n_threads = 256; int n_blocks = ceil(float(N_array / n_threads)); dim3 grid(n_blocks, 1, 1); dim3 block(n_threads, ...
Conventional wisdom is that the number of threads in the grid for a grid-stride loop should be sized to roughly match the thread-carrying capacity of the GPU in question. The reason for this is to maximize the exposed parallelism, which is one of the 2 most important objectives for any CUDA programmer. This gives the ...
72,941,449
72,942,838
operator aligned new/delete vs operator aligned new[]/delete[]
I was writing an aligned operator for vector and I realize that I don't know the difference between operator aligned new/delete vs operator aligned new[]/delete[]. Both seem only de/allocate memory, not call de/constructor, both take the size in byte. So what the point having both ? What I am missing ? Demo code : http...
Both seem only de/allocate memory, not call de/constructor, both take the size in byte. So what the point having both ? They do the same thing because you called the default operators, which do the same thing. In fact the default operator new[] just calls operator new. The reason for having two versions is that they ...
72,941,731
72,942,885
qt and Opencv linking error "undefined reference"
I tried to set up opencv in qt and followed the steps exactly from here https://wiki.qt.io/How_to_setup_Qt_and_openCV_on_Windows, but got linking error like "undefined reference to cv::imread(cv::String const&, int)' debug/mainwindow.o: In function MainWindow::MainWindow(QWidget*)': C:\Users\Han\Desktop\QT_projects\bu...
Try specifying LIBS as LIBS += -Lpath/to/lib -llibname qmake reference LIBS += -LC:\opencv-build\bin -lopencv_core343 -lopencv_highgui343 -lopencv_imgcodecs343 -lopencv_imgproc343 -lopencv_features2d343 -lopencv_calib3d343
72,941,766
72,942,189
Non-Standard Syntax Error in Thread Constructor
I'm currently looking at producing a C++ library. I've not much experience with C++ and have what is probably a very basic question about class instance method calling. main.cpp msgserver m; std::thread t1(m.startServer, "192.168.50.128", 8081); msgserver.h class msgserver { public: msgserver() { } int sta...
The syntax for a getting a pointer to a member function is &<class name>::<function_name>. In this case &msgserver::startServer would be the correct expression. Since std::invoke is used on the background thread, you need to pass the object to call the function for as second constructor parameter for std::thread, eithe...
72,943,094
72,946,444
Make all types passed as template-template argument a friend
In the following code, I would like whatever type I pass through to MyStruct to be declared as a friend of that structure. I anticipate having many different types being passed through and I don't want to have to manually add each one as a friend, like I have shown for the two current possible classes. I cannot figur...
A solution is to declare a common base class Wrapper as a friend of MyStruct and the wrap the private function. Declare xxx_TYPE as a derived class of this common class Wrapper. template <typename T> struct Wrapper { void private_function(T* p) { p->private_function(); } protected: Wrapper() = defau...
72,943,194
72,943,226
How can i fix this displayer image error in ImGui?
I have started to make a program with ImGui and opengl, besides stb for the images. When I show the default image of the demo it appears correctly. While if I load one using stb and link it with opengl and then display it, it looks like this. I do not know what it could be. Btw loading the same image as icon for the wi...
By default OpenGL assumes that the start of each row of an image is aligned to 4 bytes, because the GL_UNPACK_ALIGNMENT parameter by default is 4. Since the image has 3 color channels (GL_RGB), and is tightly packed the size of a row of the image is not aligned to 4 bytes, when 3*CurrentImage.width is not divisible by ...
72,943,196
72,943,280
Determine at compile time if argument type is void
Please consider this simple example of a wrapper around a member function. I have updated this to be more complete code to aid in answering, as suggested. #include <cstring> #include <utility> using namespace std; template <typename FunctionWrapperType> struct THE_PROXY { THE_PROXY(FunctionWrapperType* wrapper) : ...
With specialization, you might do something like: template<typename MethodType> struct FunctionWrapper; // 1 arg template<typename Class, typename ArgType> struct FunctionWrapper<void (Class::*)(ArgType /*, ...*/) /* const volatile noexcept & && */> { using Function = void (Class::*)(ArgType); FunctionWrapper(Func...
72,943,472
72,943,521
Function returning the wrong kth value while using sets
I was attempting to solve this question on some website where you have the find the kth smallest value in c++ so I came up with: #include <bits/stdc++.h> using namespace std; int kthSmallest(int arr[], int l, int r, int k) { // l is the first index // r is the index of the last element (size - 1) // k is ...
The 2nd argument of the constructor of std::set should be an iterator for an element next to the last element, not one for the last element. Therefore, you are operating with a set whose members are {7, 10, 4, 20}. The line set<int> s(arr, arr + r); should be set<int> s(arr, arr + r + 1); or (to match the comment) se...
72,943,719
72,945,780
C++ 20 dependent template in a concept
I would be really grateful if somebody could explain why the below code does not compile due to 'associated constraints are not satisfied' / 'no matching overloaded function found' (MSVC 2022, 17.2.1). The Listener concept below requires a template input param of an Update < V > where V matches the template param V of ...
Listener<UpdateV> - this is your issue I think. In the concept you already check Update<V> and now you pass UpdateV as the parameter V. So your concept ends up checking for an operator()(Update<Update<V>>).
72,943,770
72,949,093
Unable to properly render a triangle in SDL2 (MAC M1)
I'm trying to render a triangle using SDL2 on my MAC (M1), however, the triangle i'm able to generate is too much pixellated and unnecessary pixels are being rendered. Output: My Code: int main(int argc, char *argv[]) { // returns zero on success else non-zero if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { ...
Try clearing the renderer before drawing the lines: SDL_SetRenderDrawColor(brush, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(brush); SDL_SetRenderDrawColor(brush, 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(brush, a.x, a.y, b.x, b.y); SDL_RenderDrawLine(brush, a.x, a.y, c.x, c.y); SDL_RenderDrawLine(brush, b.x,...
72,943,913
73,055,888
Issues with libgcc_s_dw2-1.dll and libstdc++-6.dll on build
I know that these are required to compile a C++ app but what I don't know is how do I build my app so that other users won't need them. I tried to use -static flags to build but it still won't work when I remove mingw\bin\ and msys2\usr\bin\ from my path or when my friends who don't have a C++ compiler try to run it. F...
So, as advised by HolyBlackCat, I fully reinstalled MSYS2 and downloaded SFML and jsonCpp with mingw and after a bit of research and trial and error I ended up with this makeFile : rtx.exe: base.o objects.o rtx.o g++ -O3 base.o objects.o rtx.o -o rtx -pthread -lsfml-graphics-s -lsfml-window-s -lsfml-system-s -lopen...
72,944,176
72,944,658
How to convert cv::Mat to torch::Tensor and feed it to libtorch model?
I read image with cv2.imread() and trying to feed it to torch model in c++. It has datatype cv::Mat. I think i need to convert it to tensor somehow and then use model.forward(), but i am confused how to do it. Is there some function similar to .Tensor() in python?
The function torch::from_blob can be used to create a tensor view over the image data, like this: torch::Tensor to_tensor(cv::Mat img) { return torch::from_blob(img.data, { img.rows, img.cols, 3 }, torch::kUInt8); }
72,944,329
72,944,613
Print multiple COUT using looop
I am making a program to calculate taxes and tips based on the meal price. Is there anyway for me to loop the cout and print different percentages for each cout for 5 times? This is the code I wrote but I am stuck, I can write 5 cout but I need to use looping so I think there must be a way to print with cout until it s...
As I suggested in the comment, I think that the point breaking your loop is the fact that you change tips inside the loop itself and, in yuour example, in the first cycle you start with a tip of 0.05, then multiply it by 100, and at the next iteration you do not even enter because you do not comply with the condition t...
72,944,361
72,944,434
Getting segmentation fault (core dump) for binary search(recursive) to find a number in an array
This is a problem to find the target number in an array using the binary search recursive method. Getting segmentation fault. Have tried a lot but cannot find what is causing it. need some help to avoid such mistakes. which part is wrong in my code?? I have pasted the complete code. #include<iostream> #include<vector> ...
high, low, mid are local to your function. So, each time you call recursivebinarysearch with the same vector arr, you get the same values. So, you infinitely recurse. The segmentation fault happens when the stack overflows. If you want to keep this approach, you need to pass high and mid to the function and have it sea...
72,944,373
72,944,716
gdb : Adding a breakpoint and rerun using existing coredump
my task crashed on production server, and I downloaded the binary and the core dump. I then run : gdb task coredump And I can do some basic debugging in gdb including bt, frame, info locals etc. I have identified a variable that it's content look weird to me. Assuming I am in here : (gdb) frame 8 .... (gdb) list ... (...
can I run the same coredump, with breakpoints this time so I can inspect how this "abnormal" value occurred? No. In order to achieve what you want, you need need to record the crash under a reversible debugger, such as rr. Since you haven't done so, your only option is to guess where the variable became corrupt, add ...
72,944,612
72,944,677
'NumberOfCharsWritten' could be '0': this does not adhere to the specification for the function 'WriteConsoleOutputCharacterW' 22
Im trying to write a console screen buffer, but i keep getting different errors pointing at the LPDWORD variable no matter what values i assign to it #include<iostream> #include<Windows.h> using namespace std; int main() { COORD cell{0, 0}; LPDWORD NumberOfCharsWritten = 0; wchar_t* screen = new wchar_t[8...
You are passing a NULL pointer to WriteConsoleOutputCharacter(), but the pointer needs to point to an actual DWORD instead. Declare a DWORD variable and use the & operator to get a pointer to that DWORD: DWORD NumberOfCharsWritten = 0; ... WriteConsoleOutputCharacter(..., &NumberOfCharsWritten);
72,944,798
72,945,066
reassignment/move of std::future waits for existing future to complete
The main method below launches two std::asyncs. The future f in the main method is initially used to hold the future for the first async before being reassigned to the future of the second std::async. Both threads still appear to still complete on schedule which surprised me. Initially I (foolishly?) expected the fir...
This behavior is actually documented in std::future::~future. Excerpt from the documentation below: these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, an...
72,945,222
72,946,371
Compiling Makefile in Windows runs into "collect2: fatal" error
I am trying to remake the run and infer binaries from this open source repository in GitHub: files here. The Makefile is the one creating the run and infer files. I am currently on Windows 11, with msys2. I have: make-4.3.3 installed gcc-11.3.0, and also installed. and binutils-2.37-5 installed Currently, when I run ...
Just in case someone else is in the same debacle--the folders have some *.o files. I just had to delete those, alongside the older run and infer, simply run make while standing in that folder, and it worked!
72,945,477
72,952,886
Mapping a texture in OpenGL
I am trying to map a texture to a simple quad for the first time, but all it won't render. I am using freeglut for the implementation, and the stb_image.h header to load the texture. The code: #include <GL/glut.h> #include <stb_image.h> #include <iostream> int ww = 500, wh = 500; void display() { glClearColor(1...
Several things: The aforementioned "don't use prohibited functions within a glBegin()/glEnd() pair" issue; as of posting this hasn't been fixed in the question code. GL_LINEAR_MIPMAP_LINEAR is being used without providing any mipmaps. Drop to GL_LINEAR or provide some mipmaps. Pass 3 to stbi_load()'s desired_channels...
72,946,790
72,946,982
Why is the hash function O(1)
Why does finding the hash of a given string only run in constant time? I am trying to write an optimized program to compare two strings by using string hashing. From what I know, the hash of a string is usually defined by a polynomial rolling hash function. Online sources say calculating this hash and doing the compari...
Big-O notation is a way of describing how the execution time of an algorithm will grow with the size of the data-set it is working on. In order for that definition to be applied, we have to specify what the data-set is that will be growing. In most cases that's obvious, but sometimes it's a bit ambiguous, and this is ...
72,946,813
73,368,811
Why does the function 'CGAL::draw' draw a black triangle instead of a polygon in the latest version of CGAL?
I've upgraded my CGAL installation to the latest version (5.4.1) and I can't use the function CGAL::draw anymore - it draws a black triangle instead of everything I need. It's not a problem in my code - even standard examples from the CGAL distribution behave this way. The script below unpacks the CGAL tar-file, then b...
I'm answering my own question. The issue here is that starting from the version 5.3 the CGAL library Qt5-based visualization subsystem doesn't support old graphics hardware - at least on Linux machines (no idea about Windows or Mac worlds). It looks like the OpenGL implementation on Linux (called Mesa) checks the graph...
72,947,048
72,949,314
QFileSystemWatcher not sending fileChanged() SIGNAL
I apologize in advance am very new to QT (and fairly new to C++) I am trying setup a program that will execute a function anytime a specific file is changed. Despite hours on google and reading the docs provided on QT I cant find a way to get myfunction() to execute when SSOpen_Log is edited currently my code looks som...
You allocated your instance on the stack and it thus get destructed when the constructor ends. I would suggest that you make a class member for the instance so that it remains valid throughout the class. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(thi...
72,947,052
72,964,557
how can I receive all message by libevent
Currently, I use libevent to send and receive messages. The issue I am currently encountering is that I do not receive all messages on the server; and only receive the first message I sent. Client Code: for (int i=0; i < 10 ; i++) { bufferevent_write(bev, data, strlen(data) + 1); } Server Code: static void read_cb...
This situation seems to be a bit like a spacket splicing problem, you can try this static void read_cb(struct bufferevent* bev, void* arg) { char bufs[2048]; struct evbuffer *input = bufferevent_get_input(bev); size_t lens = evbuffer_get_length(input); char * rline = bufs; whil...
72,947,518
72,947,620
How do I check whether an index of array is empty and then, if it is, skip to the next?
I'm trying to build a program that can register a user to the database (still learning cpp, I hope that in the near future I'll be able to work with database). What I'm trying to do with this code is to check whether an index of array is empty for the user to store an ID in it. If it isn't empty, I want the program to ...
Please consider the following definitions for an "empty" array element: a) not initialised (unhelpful, cannot be checked) b) never yet written to (same as a) ) c) contains "" (possible, but means that "" must not be accepted as an actual content) d) is empty according to a second array in which that info is maintained ...
72,948,090
72,948,176
How avoid code duplication in visitor and const visitor base classes
I have 2 classes ConstVisitorBase and VisitorBase which contain some code to visit objects. for example: struct Node { enum class Type { ... }; Type type; } class ConstVisitorBase { public: virtual void VisitType1( Node const & node ); ... private: void VisitNode( Node const & ...
Since VisitType1 are public and the two classes are unrelated, you can use a template function: template<typename Visitor, typename T> void dispatch_visits(Visitor& visitor, T&& node){ switch( node.type ) { case Node::Type::type1: visitor.VisitType1( node ); } ... }
72,949,147
72,949,529
C++ possible to call function with same name in different class with single pointer?
Is it possible to call run() with p without concerning different class they are(for example class cast on a void*) and different implementation of run() in each class? class A { void func() { //new B //new C //new D //*p points to the instance of one of B,C,D p->run(i); ...
This works: #include <iostream> class B { public: virtual int run(int i); }; class A { public: int func(B* obj, int i) { return obj->run(i); } }; class C: public B { public: virtual int run(int i){ return 2*i;} }; class D: public B { public: virtual int run(int i){ ...
72,949,300
72,949,373
how are these functions called if I didn't call them?
I'm new to QT. How are these functions automatically called if I didn't call them? Maybe somewhere inside the parent class there are connections that somehow connect them and launch them? I know there will be a default constructor here, but how are these functions called, if the default constructor is empty class Custo...
Public methods can be called by anyone who has a pointer or reference to objects of your class. Presumably objects of this type are added to a QGraphicsScene, which among other things will call boundingRect to determine how much space your CustomItem occupies, and paint when it needs to draw the part of the scene with ...