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
65,194,529
65,195,490
How do you reference a specific recipe revision from conan-index?
I need to reference spdlog 1.7.0 revision 1eebff2f51d90cb700b63c6d2449ebcb, not the latest revision, but I cannot seem to do this. Specifying revision requires the user/channel#REV syntax, but recipes on conan index doesn't seem to have user/channel. How do I reference a specific revision from conan-index?
You should be able to install specific revision using command: conan install spdlog/1.7.0@#1eebff2f51d90cb700b63c6d2449ebcb Notice the @ symbol after version.
65,194,620
65,209,918
Get caption of child window button on windows using uiautomation with c++
I want to get this Zoom Meeting's "Mute My Audio" caption on windows using uiautomation with C++ this is my calling current code: // Get the handle of the Zoom Meetings window. zoomWnd = ::FindWindow(NULL, "Zoom Meeting"); if (zoomWnd != NULL) { std::cout<<"zoom meeting"<<"\n"; IUIAutomationElement *zoom...
here the code which worked... IUIAutomationElement *zoom = GetTopLevelWindowByName(L"Zoom Meeting"); ListDescendants(zoom, 2); void ListDescendants(IUIAutomationElement* pParent, int indent) { osFocusZoomWindow(); if (pParent == NULL) return; IUIAutomationTreeWalker* pControlWalker = NULL; IUIAutomation...
65,194,773
65,232,770
QPluginloader error: "Cannot load library: The specified module could not be found" unless the plugin is in the same folder as in .exe
I am having a weird error while loading plugins using QPluginloader. I built 4 plugins in total all specified with Q_PLUGIN_METADATA, Q_OBJECT and Q_INTERFACES. I can see all the plugins are built properly and there are no missing .dlls (checked with Dependency walker). All these plugins are placed in separate "plugins...
While reading through Dynamic-Link Library Search Order i found out it is possible to modify the search order using SetDllDirectoryA() as described here. It finally worked. SetDllDirectoryA((LPCSTR) "path/to/plugin/folder"); Windows will now search for all the plugin dependencies in specified plugin directory which is...
65,194,832
65,194,884
Getting "non-standard syntax; use '&' to create a pointer to member" for std::sort
I'm trying to implement this code for Linear Regression here but it is unable to compile due to std::sort returning several errors. #include "LinearRegression.h" #include <iostream> #include <algorithm> #include <vector> bool LinearRegression::custom_sort(double a, double b) /*sorts based on absolute min value or erro...
custom_sort is a non-static member function, it can't work with sort directly because under the hood it expects three arguments, not two - the first one is the object pointer. In your particular example, custom_sort doesn't use any data members, so it can be made static (static should go into the declaration): static b...
65,195,127
65,195,301
Using int as void pointer in C++
There is a C++ snippet which has to use some old plain C event_handler functions. The event_handler has this common signature: add_event_handler(event_cb callback, void* user_data) Note: event_cb is a function pointer, probably unrelated to this question. user_data is defined to let the user to pass some extra informa...
If (and only if) the user_data pointer isn't used elsewhere, you can use casting to convert any integer whose sizeof is smaller than (or equal to) sizeof(void*) to a void* type. However, to be fully compliant you can't do the cast in a single step, it has to be done over an intermediate cast: add_event_handler(mycallba...
65,195,291
65,196,197
Can non-array continuous block of data be accessed by pointer with index?
If i have struct with several ints, is this possible to access them like in array? ints will have decreasing addresses due to stack allocation but will be continuous. I have code similar to this struct z { static int a; static int b; static int c; static int d; static int e; static int get(int index) { ...
I wonder ... if i even should do something like this. You shouldn't. The behaviour of your program is undefined. If i have struct with several ints, is this possible to access them like in array? No, it is not possible (at least not in this simple way). If you want to access like an array, you should use an array: ...
65,195,382
65,195,581
Find smallest element in array
In an array of N elements (N is given), find the smallest element from the first zero element to the end of the array. If there are no zero elements in the array, display a message about it. Can someone fix this for me please? #include<iostream> using namespace std; int main() { int i, n; cout << "N= ";...
You can simply check it in the same loop in which you looking for smallest element. #include <iostream> #include <climits> using namespace std; int main() { int i, n; bool isZeroElement = false; cout << "N= "; cin >> n; if (n > 0) { int *a = new int[n]; for (i = 0; i < n; i++) { ...
65,195,841
65,196,363
Hash function to switch on a string
I am trying to get to work a switch on a string in C++, with the help of a hash. It became personal between me and this code, so I don't wanna give up and use an enum, even though I finally have only like 8 strings to put in switch cases. Combining what I saw on other topics, I wrote this very simple and not so reliabl...
Unless you are using c++20 std::string is not constexpr so can't be used in hashstr. The value returned is larger than is representable in long, as signed arithmetic overflow is undefined behaviour your code can't be used in constexpr. Fixing these two issues gives the working code: constexpr unsigned long hashstr (con...
65,195,909
65,196,012
c++ fstream::read only returning 1st char
Preface: I am a inexperienced coder so its probably an obvious error. Also like all of this code is stolen and slapped together so I claim no ownership of this code. System: I am using windows 10 64 bit. I write my code in Notepad++ and compile with MinGW G++. What I'm trying to do: I am trying to read an entire file (...
std::cout << "\n\n" << *buffer << "\n\n"; Buffer is a char*, so by dereferencing it you get a single char, which in your case is B. If you want to output the whole data that you read just don't dereference the pointer, in C/C++ char* has special treatment when outputing with std::cout,printf and such. std::cout << "\n...
65,196,623
65,196,794
What is the correct way to cast a struct to a type that matches its first set of members?
Please consider the following structs from the WinAPI: typedef struct _PROCESS_MEMORY_COUNTERS { DWORD cb; DWORD PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsag...
Documentation states that GetProcessMemoryInfo accepts A pointer to the PROCESS_MEMORY_COUNTERS or PROCESS_MEMORY_COUNTERS_EX structure that receives information about the memory usage of the process. So, reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc) would be the answer to your question. But you must set cb to the...
65,196,875
65,209,507
Is it possible to use stbi_load on Android?
I am a newbie on openGLES, I just want to open an image serve my texture later. Since most tutorial on the internet for openGL is based on development on laptop, they simply open image like:unsigned char *data = stbi_load("pic.jpg", &width, &height, &nrChannels, 0); and put the picture under same folder. But I then rea...
I figure it out by myself in case someone encounter same issue.. Note in android you need to read from Sdcard not from drawable. Remember to grant permission.
65,197,140
65,198,808
MSVC: Crash when invoking a method directly via the VTable that returns by value (C++)
I'm trying to understand why the following code does not properly work in MSVC under Windows. It calls a VTable method directly which returns by value. #include <iostream> #define RETURN_BY_VALUE 1 struct Value { int Secret; }; class IFoo { public: #if RETURN_BY_VALUE virtual Value GetValue() = 0; #else virtua...
Don't forget about __stdcall. Without __stdcall, calling convention for free function and for methods differs more. GetAdapterLuid is __stdcall I guess. With Windows ABI returned structures are passed as hidded out parameter. It looks like that the order between this and the hidden parameter is different in method and...
65,197,201
65,197,584
Allocation: Smart pointers and dynamically sized structure
I've a structure that can be dynamically sized. I want to use smart pointer (unique_ptr here) to allocate this structure. The problem is that this struct is dynamically sized.. Here is the structure (of Windows library): typedef struct _STORAGE_DEPENDENCY_INFO { STORAGE_DEPENDENCY_INFO_VERSION Version; ULONG Nu...
You can use smart pointers with any allocator-deallocator pair by using a custom deallocation function. Here is an example using std::malloc and std::free: struct freer { void operator()(void* p) const noexcept { std::free(p); } }; template<class T> using unique_c_ptr = std::unique_ptr<T, freer>; temp...
65,197,250
65,197,689
input string as character array in c++
I have search a lot but i haven't find my answer I want to write a program that will give an array with 3 members and then i want to print array with 3 members : char array[3] ; for(int i=0;i<3;i++){ cin>>array[i] ;} But the point is , i don't want to cin array members in character ,and i want this in string ; bu...
char array[3][10]; for (int i = 0; i < 3; i++) { cin >> array[i]; cout << array[i] << endl; } Where the 2nd size of the array depends on the length of the input string.
65,197,268
65,197,402
Iterate through a struct with a pointer
I currently have this code: struct LAYOUT { WORD a [8] = {::Rook, ::Knight, ::Bishop, ::Queen, ::King, ::Bishop, ::Knight, ::Rook}; WORD b [8] = {::Pawn}; WORD empty [32] = {::None}; WORD c [8] = {::Pawn+0x6}; WORD d [8] = {::Rook+0x6, ::Knight+0x6, ::Bishop+0...
In the statement LAYOUT* chessboard = &chessLayout; /* ... */ for(int i = 0; sizeof(LAYOUT) / 2;i++){ printf("%x", *(reinterpret_cast<WORD*>(chessboard+i))); } the pointer chessboard is incremented, which is of type LAYOUT*. This will move the pointer along "i * sizeof(LAYOUT)" bytes, whereas what you want is t...
65,197,435
68,021,788
Cannot use an Xaml component from a C# WinRT Component in C++/WinRT Xaml Islands project
How to replicate (we will use Windows Terminal as example): Clone the Windows Terminal repo and fetch submodules Create a C# Windows Runtime Component in the solution with a UserControl with some random controls Reference the C# WinRT Component from the project you want to host the UserControl in Open an Xaml page ...
So I finally found the solution we have to register against CLRHost.dll instead of the Runtime Component Winmd file So if the app is packaged we have to add that inside the Extensions tag (which is inside the Package tag not the one that inside the Application tag) of Package.appxmanifest (keeping in mind that Namespac...
65,197,573
65,197,849
Can a 'using' be made in a class independent of the class' template?
If I use a typedef or using inside a class or struct, I sometimes want it to be independent of the templates used for that class or struct. In the example below, I would use Object<T>::RefCountT, which would work, but I would rather use something like Object::RefCountT in this case, because then I don't have to arbitra...
Object is just a template, but you need to instantiate it to access its member alias. I see several options: A) Don't make RefCountT a member of Object. B) Provide a default parameter so you need not explicitly pick a type to access the alias: template <typename T = void> struct Object { using RefCountT = unsigned ...
65,197,671
65,202,841
LookupAccountSid() throws System.AccessViolationException on Server 2016
I use pinvoke implementations of LookupAccountSid in managed C# code for several years. On a German Windows Server 2016 it starts throwing an System.AccessViolationException when resolving S-1-5-11 (Authenticated users) where the German name is: "NT-Authorität\Authentifizierte Benutzer". I tested 3 different impementat...
I wrote the following, using the Vanara libraries and @RbMm's comments, to mimic the LookupAccountSid functionality using LsaLookupSids. private static NTStatus LookupAccountSid2([Optional] string lpSystemName, PSID lpSid, out string lpName, out string lpReferencedDomainName, out SID_NAME_USE peUse) { lpName = lp...
65,198,011
65,198,058
Why can't std::array<std::pair<int,int>, 3> be initialized using nested initializer lists, but std::vector<std::pair<int,int>> can?
See this example: https://godbolt.org/z/5PqYWP How come this array of pairs can't be initialized in the same way as a vector of pairs? #include <vector> #include <array> int main() { std::vector<std::pair<int,int>> v{{1,2},{3,4},{5,6}}; // succeeds std::array <std::pair<int,int>, 3> a{{1,2},{3,4},{5,6}}; /...
You need to add an outer pair of braces to initialize the std::array<...> object itself: std::array <std::pair<int,int>, 3> a{{{1,2},{3,4},{5,6}}}; The outermost pair is for the array object, the second pair is for the aggregate array inside the object. Then the list of elements in the array.
65,198,821
65,201,951
How to add additional value/parameters in RTP header
Basically, I am working in the VOIP application and trying to build an app using the WebRTC. I already know complete implementation and details about the RTP header which contains things like 1. version 2. padding 3. extension 4. CSRC count 5. marker 6. payload type 7. sequence number 8. Time Stamp 9. SSRC 10...
If you're implementing an RTP packet with additional parameters, you need to put them in the "Extension header". The extension is located right after the default RTP header values. Don't forget to set "profile-specific extension header ID"(your extension id) and "extension header length"(length of extension excludes th...
65,198,988
65,199,389
OpenGL 2DTexture from c++ unsigned byte array
I'm trying to process a 2D array in a fragment shader - so to learn that, I started building my array: int const _s = 512; std::array<GLubyte,_s*_s*4> hitmap; for(unsigned j = 0; j < _s; j++) { for(unsigned i = 0; i < _s; i+=4) { hitmap[i+j*_s] = j%256; //R if(j>33 && j < 45) hitmap[i+j*_s...
You've misunderstood the concept of GL_MIRRORED_REPEAT. See OpenGL wiki glTexParameter GL_MIRRORED_REPEAT causes the s coordinate to be set to the fractional part of the texture coordinate if the integer part of s is even; if the integer part of s is odd, then the s texture coordinate is set to 1−frac(s), where frac(s...
65,199,101
65,199,415
Various variations of the implementation of dfs
Suppose I have the concrete undirected graph: "1----2----3----4". What is the difference between the next implementations of the algorithm "dfs": #include <iostream> #include <vector> using namespace std; const int maxSize=4000; vector<int> graph[maxSize]; bool visited0[maxSize]; void dfs0(int firstPoint, int previousP...
There is no logical difference between Variation 1 and Variation 3, but Variation 3 is optimised version as it will avoid unwanted recursive calls which might be a great deal if large test cases are involved. This might consume more memory unnecessarily. The Variation 2 differs logically from the other two variations, ...
65,199,431
65,199,489
Unable use functions on templates
I have a class called Variables which just adds variables together as I want:- #include <iostream> #include <typeinfo> using namespace std; template <class Type> class Variables { public: Variables operator+( Variables& ); void set(Type); void print() const; Variables(); private: Type item; }; in...
In C++17, use std::is_same in a if constexpr: template <class Type> Variables<Type> Variables<Type>::operator+( Variables& x ) { Variables<Type> t; if constexpr (std::is_same_v<Type,int> || std::is_same_v<Type,double>) t.item = item + x.item; else if constexpr(std::is_same_v<Type,double>) t...
65,199,463
66,443,005
How to draw a pixel line on a sprite represented by an array of color?
I'm making my own graphics library and I have a Sprite class which is just an array of colors with a width and a height. I can set a pixel on the sprite by changing its color value. How can I draw a line on a sprite given a start position and an end position? class Sprite { public: Sprite(); public: LongUtils:...
Use something like Bresenham's line algorithm. Here's an example: void Line( float x1, float y1, float x2, float y2, const Color& color ) { // Bresenham's line algorithm const bool steep = (fabs(y2 - y1) > fabs(x2 - x1)); if(steep) { std::swap(x1, y1); std::swap(x2, y2); } if(x1 > x2) { ...
65,199,581
65,207,386
Overriding std::variant::operator==
I'm a little surprised that putting the variant's alternative types into a sub-namespace seems to break the operator==: #include <variant> #include <iostream> namespace NS { namespace structs { struct A {}; struct B {}; } // namespace structs using V = std::variant<structs::A, structs::B>; bool operator==(cons...
The reason is due to ADL. In particular, see [basic.lookup.argdep]/2: (emphasis mine) For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated entities (other than namespaces) to be considered. The sets of namespaces and entities are deter...
65,199,666
65,208,496
Size of buffer pointed to by char* returned from field_buffer
So I am trying to work with the <form.h> library provided by <ncurses> I am reading this man page that tells me of the function: char *field_buffer(const FIELD *field, int buffer); The return type is a pointer to char *. On the end of this pointer, I suspect, is a c-style array containing the chars I want to access. No...
It's not explicitly stated, but since there's no pointer to a length-parameter allowing the library to return the string-length as a side-effect, you have the C convention of null-terminated strings. The manpage does say this: The function field_buffer returns a pointer to the contents of the given numbered buffe...
65,199,816
65,200,701
Chars exadecimal to string conversion
I need a function that convert hexadecimal char pointer to string: ex: std::string Myfunction(char* hexacode) { std::string output; // // return output; } std::string Result = Myfunction("\x55\x8B\xEC\x83\xEC\x14\x53\x56\x8B\x75\x0C"); In short I need to convert in string this parameter or similar. Because in th...
If you want the user to input the string, you don't have to care about anything, string escaping only happens for constant strings in the code file. If you don't want the constant strings in the code file to be escaped, no function conversion needed, just do this: "\\x55\\x8B\\xEC\\x83\\xEC\\x14\\x53\\x56\\x8B\\x75\\x0...
65,199,844
65,200,535
Is there any alternative of Python Dictionary in C++ without using high level Data Structures?
I was actually working a projects of OOP in C++ and stuck in a problem to store keys and their associative values. Both keys and values are string type. Here's the code I'm trying to write but still it's showing error. #include <map> #include <iostream> std::map<std::string,std::string> dest; using namespace std; dest[...
You might use initialization at global scope: /* const */ std::map<std::string, std::string> dest = { {"M", "001"}, {"D", "010"}, {"MD", "011"}, {"A", "100"}, {"AM", "101"}, {"AD", "110"}, {"AMD", "001"} };
65,200,431
65,200,456
Sending Slack message via windows Curl
I'm try to send Slack messages with Slack API and curl command on C++ Console Application but I can’t solve this error due to String type: Curl command (this command successfully send a message) curl -X POST -H "Content-type:application/json" --data "{\"text\":\"A New Program Has Just Been Posted!!!\"}" https://hooks.s...
You need more escaping. You've escaped the shell "s, but not the JSON "s. #include <iostream> #include <string> int main() { std::string command = "curl -X POST -H \"Content-Type: application/json\" --data \"{\\\"text\\\":\\\"A New Program Has Just Been Posted!!!\\\"}\" https://hooks.slack.com/services/{API_KEY}";...
65,200,467
65,200,584
How can i get the sum of odd and even number with input user in Array C++
Our programming activity is to construct a C program that creates an array of size 12 and then display separately the sum of even-indexed cells and odd-indexed cells as well as their average. The sample run must be like this. Sample Run: Enter 12 elements: 1 1 1 1 1 1 1 1 1 1 1 1 Sum of even-indexed cells: 6 Sum of od...
You don't need 3 arrays. Just an array for the elements and 2 variables for the sums of evens and odds. You could check the position in the array by checking if the remainder of the index divided by 2 equals 0. You could also start an even position and increment the index by 2 so it would only check the even positions....
65,200,690
73,347,173
How to run a Qt application in headless mode (without showing my GUI)
I have a QT application based on a QApplication and supposing that my application has a complex GUI (QDialog, QMainWindow...). My Application can run in two modes: with GUI in headless mode I would like to know how I can launch the application in headless mode (that is to say without GUI visible) From a very basic co...
There are several options here. Either you need a Qt Console Application or you need a headless GUI Application. You will find truly running a GUI in headless mode rather tricky. This applies in case you need to run the very same app in a Linux system which does not have the installed GUI libraries, like a minimal setu...
65,201,082
65,201,152
How exactly are fundamental data types assigned to specific architectures
So I got into fundamental data types and I was left with one thing that I'm confused about - if I was going to build a 64-bit program, would I have to use data types specifically made for 64-bit architecture? I did some research and turns out that 64-bit optimized version of integer would be long long int. Or it doesn...
You may find that some types have different sizes than you're used to. For example, a 32-bit Solaris environment has 4-byte long, but a 64-bit Solaris environment has 8-byte long. Meanwhile, this isn't the case in Visual Studio, which retained 4-byte long. This is why, if you are relying on extreme range for integer ty...
65,201,093
65,201,246
Resolution of overloaded extern C function with default arguments
This code: #include <stdlib.h> // int abs(int); int abs(int i = 0) { return 42; } int main() { return abs(1); // Returns 42 } Returns 42. The compiler picks the overloaded C++ function. I tested this on many versions of g++/clang. Can I rely on this behaviour? Is it documented anywhere? Source on Wandbox
You get undefined behavior by doing that. [extern.names] 4 Each function signature from the C standard library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace. int ab...
65,201,350
65,201,443
Code Blocks doesn't show any error but still can't show output (0xC00000FD)
I have this code: #include <iostream> #include <iomanip> using namespace std; main() { int i, n, a[n], b[n], c[n]; cout << "Program kreira nizove po matematickoj zavisnosti" << endl; cout << "Unesite vrednost n =" << endl; cin >> n; for (i = 0; i <=n; i++) { a[i] = (i+1)*2; i...
This line: int i, n, a[n], b[n], c[n]; has two problems: Variable length arrays are non-standard, and: n is uninitialised so a[n] tries to allocate an array of some indeterminate size on the stack. Which, in your case, is too large and is causing a stack overflow. So, initialise n before you use it, and rather th...
65,201,545
65,201,587
Is the `std::sort` function unstable?
Just wanted to confirm if what I am thinking is right or wrong. According to the definition: A sorting algorithm is said to be stable if two objects with equal or same keys appear in the same order in sorted output as they appear in the input array to be sorted. Now in std::sort in the standard library, returning fal...
Now in the sort function in STL, returning false when two elements are equal is a must. Hence, is it safe to say that the sorting algorithm used is unstable? No, that’s completely unrelated. As a matter of fact, std::sort isn’t guaranteed to be stable; if you require a stable sort, use std::stable_sort. But the strin...
65,201,708
65,201,922
Calling private member of inherited class for unittest
I'm trying to write a unittest but I'm running into some problems. I've got a class which has an int to keep track of the current state. All classes that are inherited of this class can change the state by calling the protectedFunction. class RandomClass { public: RandomClass() { mState = 0; } protected: ...
Your class declares a free-standing function to be friend. Your unit test uses a member function of a class, the class is not declared friend. You can write friend class UnitTestRandomClass; Specifically, what you want to do, make a member function of a future derived class a friend is not provided by the standard. The...
65,202,374
65,202,504
Why this code works (C++ template class with invalid non-template function)?
This C++ code builds successfully: void h(int *) { } template <typename T> class A { public: void f() { T *val; h(val); } }; int main() { A<const int> a; } Why? It is undeniable that A<const int>::f() cannot work. If you call a.f(), it fails to build as expected. Why is an in...
There's no sfinae here. If we look closely at the declaration of the function, and not it's implementation: template <typename T> class A { public: void f(); }; You can see that there's nothing to tell the compiler that this function should not be part of overload resolution. If we add a return type containing an ...
65,202,434
65,206,517
what's the original type for a member function template during partial ordering
Consider this example struct A { }; template<class T> struct B { template<class R> int operator*(R&); // #1 }; template<class T, class R> int operator*(T&, R&); // #2 The partial ordering will apply to #1 and #2 to select the best viable function template. Two sets of types are used to determine the...
Yes, it's a bit of a mess. As you've observed, it doesn't make sense for the "original type" of a class non-static member function to lack the inserted this parameter. The only way to make it work is for the subsequent paragraphs in subclause 3 to apply to the "original" function type on the other side of [temp.deduct....
65,202,562
65,202,563
How to compare and convert const reference and const_iterator
Here is a simplified version of what I have to deal with. I got a struct that holds a number, one that holds a vector of numbers, and one that holds a ref to a number. #include <iostream> #include <string> #include <vector> using namespace std; struct Number{ int a; Number(int b): a(b){} }; struct NumberCollectio...
So, first, to make a NumberRef you actually just have to deference the iterator. NumberCollection collection; vector<Number>::const_iterator vec_it = collection.begin() +1; NumberRef numberRef(*vec_it); Second, to compare the address of the two, consider this: cout << to_string(&(numberRef.myNumber) == &(*vec_it))...
65,202,772
65,206,757
Assigning std::function inside union crashes program
I wrote the following class which stores either a fixed value (constant) or a function to get a value (get). template <typename T> class DynamicValue { private: bool isConstant; union { T constant; std::function<T()> get; }; void copy(const DynamicValue& value) { isConstant =...
Your copy constructor for DynamicValue does not initialize the get member, causing the assignment in copy to fail. Adding an initialization for get DynamicValue(const DynamicValue& value) : get() { copy(value); } resolves the crash but has other issues. See version here Going in this direction is problematic, so you s...
65,202,911
65,203,090
std::reference_wrapper v.s. int&
I was trying out the std::reference_wrapper with the following snippet int a = 42, b = 52; std::tuple<std::reference_wrapper<int>> t = std::make_tuple(std::ref(a)); std::get<0>(t) = b; std::cout << "t[0] = " << std::get<0>(t) << ", a = " << a << ", b = " << b << std::endl; The output is t[0] = 52, a = 42, b...
I thought std::ref gives us std::reference_wrapper rather than &? That's not a question, but you thought correctly. How I should explain the case of & and why it is different from std::reference_wrapper. When a std::reference_wrapper argument passed to std::make_tuple, the resulting tuple will have a reference ...
65,203,067
65,635,794
Why won't Unity recognize this DLL - is it in the wrong place?
I have inherited a project that has little to no documentation. Basically its a Unity project that receives simulated heart rate information from a running Linux program, to display. I was given a working version of the Unity application running on a tablet. But when I open the project from the repository, and try to r...
Ahhh I finally solved the problem! There's a dependency that my DLL requires that doesn't exist. For some reason, instead of giving a dependency error or something like that, Unity is just reporting DllNotFoundException: <dllName.dll>. I found a GitHub thread suggesting a tool called Dependency Walker to check for depe...
65,203,106
65,204,401
Makefile confusion ' errno=2 for architecture x86_64'
I have a Makefile that looks like this: CFLAGS = `pkg-config opencv --cflags` -Wall -Wextra -Werror -pedantic -std=c++11 LIBS = `pkg-config opencv --libs` % : src/%.cpp src/%.h $(CXX) $(CFLAGS) -g -o bin/$@ $< -O3 $(LIBS) clean: rm -rf bin/* When I run `make skin-detect' I get this error: make skin-d...
Can't add formatting in comments: you should be able to do something like this: % : src/%.cpp src/%.h mkdir -p bin $(CXX) $(CFLAGS) -g -o bin/$@ $< -O3 $(LIBS) if the problem is really that the bin directory doesn't exist. However of course there could be other issues. One thing you said in your quest...
65,203,313
65,203,806
Why does map not include out_of_range?
Consider the following code that doesn't compile: #include <map> //#include <stdexcept> // uncommenting this works int main() { std::map<int, int> test; try { test.at(10); } catch(std::out_of_range& e) { } return 0; } Why does std::map not include std::out_of_range, even if it uses it?...
Whether a standard header does include another header is an implementation detail unless explicitly specified. With templates its a little more involved, but just to point you in some direction, consider this toy example: // header: my_map.h struct my_map { int at(int); }; Only in the source file the header for th...
65,203,441
65,203,495
std::source_location as non type template parameter
In my infinite quest to push limits of what can be used as non type template parameter I was trying to see if I can use std::source_location as non type template parameter. That failed with a weird message, since I presume source_location is some magical struct... type 'std::experimental::source_location' of non-type ...
std::source_location is specified as: struct source_location { // ... private: uint_least32_t line_; // exposition only uint_least32_t column_; // exposition only const char* file_name_; // exposition only const char* function_name_; // exposition o...
65,203,643
65,203,851
Empty virtual function: good practice?
I have a superclass Student, from which Junior class and Senior class inherit. virtual void student::attend(void){ //call either Junior's or Senior's attend //if attend is called on a Student object, do nothing. } void Junior::attend(void){ //do stuff } void Senior::attend(void){ //do stuff } B...
The real question is whether a student object will ever be created on its own (versus as a subobject of a Junior or Senior). If it won't be created, consider declaring a function which does nothing for a student to be pure virtual: virtual void attend() = 0; Then you will not be able to create a student object on its...
65,204,894
65,205,053
Function object to pass std::get around as an argument to functions
My intention is to write a getter for the Nth element of whatever std::get can take as argument once it's instantiated with a specific N. In other words, std::get<N> cannot be passed around because it's not a function object, but a function templated on the type of the argument it takes. Is it possible to define an obj...
which doesn't take parenthesis after the closing >, as it happens for variable templates. Exactly, a variable template is just what you want: #include <functional> #include <tuple> template<int N> auto getNth = [](auto const& x){ return std::get<N>(x); }; int main() { auto whatever = std::tuple{1, 2, 3}; re...
65,204,945
65,205,249
How to create compile-time constant string with prepended length byte?
I have some old code that uses #define to, um, define some string literals, e.g. #define FredString "\004FRED" That I would like to update to avoid using #define. Closest I get is something like the following: static constexpr char* FSraw= "FRED"; static constexpr char FSlen= (char)(sizeof(FSraw) - 1); static constexp...
template <std::size_t N> constexpr std::array<char, N+1> AddLenPrefix(const char (&str)[N]) { std::array<char, N+1> ret{}; ret[0] = N-1; // Exclude the '\0'. for (std::size_t i = 0; i < N; i++) ret[i+1] = str[i]; return ret; } static constexpr auto FredString = AddLenPrefix("FRED");
65,205,284
65,206,049
arduino esp32 bluetooth recieve a whole string
Is there a neat way of receiving a message string with the esp32 BluetoothSerial library just like Serial.readString(). The idea is to send a message from a smartphone, receive the message and update variables from that message which will affect what the Arduino does. Also can I save a byte as e.g. 255 instead of 0xFF?...
It actually seems that BluetoothSerial has a readString method... I'm on Platform.io with an esp32 + Arduino framework configuration and it correctly compiles...
65,206,461
65,206,531
C++ use iostream inside class
I'm using iostream and map. When I try to set the functions, they throw an error. My code: #include "string" #include "iostream" #include "map" using namespace std; class myClass { map<string, string> Map; Map["Ziv"] = "Sion"; cout << Map["Ziv"]; }; My error: error: 'Map' does not name a type error: 'co...
Why I can't use iostream and cout? Because a class cannot (directly) contain expression statements. It can contain only member declarations. Expression statements can only be within functions. This would be correct for example: class main { map<string, string> Map; void example_function() { Map["Ziv"...
65,206,747
65,206,924
Fixed number of template function arguments according to template argument
I'm currently looking for a solution to give a templated classes’ constructor and function a fixed template according number of arguments N. My template is of the form template<typename T, unsigned int N>. The idea is that the following will work: MyClass<int, 4> object(1, 2, 3, 4); While the following should fail (an...
You can add a constraint to the overload, such as template <typename T, std::size_t N> struct MyClass { // pre-C++20 template <typename... Args, std::enable_if_t<sizeof...(Args) == N, int> = 0> MyClass(Args&&... args) { /* ... */ } // or alternatively, post-C++20, template <typename... Args> requires (si...
65,207,060
65,207,118
Json http respone, if else statement
I CANNOT ALTER THE JSON RESPONSE, SHOWN BELOW. I want to be able to detect when the POST message was successfully entered into the database. When the data is successfully entered the response is: {"status":"success","message":"successfully inserted"} I want to then use an if-else statement in Arduino to detect when thi...
This just requires escaping if you're testing literally: if (line == "{\"status\":\"success\",\"message\":\"successfully inserted\"}") Keep in mind this could just as easily have the keys swapped, there's no guarantee they'll be in that order. This is why using a proper JSON parser is imperative.
65,207,216
65,207,255
how to check std::array is declared but not explicitly initialized
std::array has a built-in method empty() to check if the array is empty. As shown in the example copied from here: #include <array> #include <iostream> int main() { std::array<int, 4> numbers {3, 1, 4, 1}; std::array<int, 0> no_numbers; std::cout << std::boolalpha; std::cout << "numbers.empty(): " <...
No. std::array<T, N>::empty() where N!=0 will always return false. https://en.cppreference.com/w/cpp/container/array/empty "Checks if the container has no elements, i.e. whether begin() == end()." Similarly std::array<T, 0>::empty() will always return true, because begin() == end().
65,207,286
65,207,841
How to overloading operator= in red-black tree? C++
I have a red-black tree that needs to be overloaded with an assignment operator. I kind of overloaded the operator= of a binary tree whose nodes don't know their parents. But how do I do this for a tree where nodes have a relationship with the left, right, and parent? template<typename KEY, typename VALUE> class map; t...
You might pass new parent to CopyTree: const map<KEY, VALUE>& operator=(const map<KEY, VALUE>& other) { if (this != &other) { if (root != nullptr) destroy(root); copyTree(root, nullptr, other.root); } return *this; } void copyTree (Node<KEY, VALUE>*& copiedTreeRoot, ...
65,207,358
65,207,410
Copy data from file into vector of pointers
I'm trying to create a function below called load() that copies all the records from my graduate.dat file into my vector of Record pointers called primaryCollection. I created a Record class with variables that make up each Record, and in my load() function in createReport.cc I attempted to read each line in the file, ...
The correct syntax here is: Record* record = new Record(year, province, degree); Everything after that is fine, but keep in mind that vector now "owns" the pointers and you're responsible for releasing those allocations somehow. This is where pointer wrappers come in handy.
65,207,893
65,208,115
Purpose of using a virtual function without overriding that virtual function
I am currently working through the Educative course Grokking the Coding Interview. While it is a very good course and does explain the algorithms very well, it does not always explain the code. A few times I have seen the use of virtual functions, as a dynamic function (to be clear, I mean functions that require the in...
From reading up on virtual functions, I gather that they are used to achieve some OOP principles such as run time polymorphism Yes. or just generally improving the maintainability of some code No. In the case of these algorithms questions, that seems to be completely unnecessary. In fact, I am able to just delete ...
65,207,906
65,210,434
lambda/function pointer with std::function causes error
Update: These errors appear to be from CODAN, Eclipse's code analyzer, that appear in the Problems view and are also underlined in red on the line the error refers to. Oddly enough building the project successfully creates the executable, and the build does not report these errors in the Console. I can run that executa...
This behavior is a known bug with Eclipse CDT version 10.0. Update: This issue is fixed by upgrading to Eclipse CDT version 10.1: https://download.eclipse.org/tools/cdt/builds/10.1/cdt-10.1.0-rc2/ Steps to fix: Enter the above URL in Help --> Install New Software... --> Work with: and install all the options. Restart ...
65,208,313
65,208,343
With a 2D vector, does calling clear() on the 1st level clear all the memory associated with that vector?
I have a 2D vector declared as such: vector<vector<uint16_t>> vector; After this is used and I need to clear all memory associated with it, even the elements in the [][X] dimension, can I simply do: vector.clear(); Or do I have to go through each of the vectors inside and call .clear() on them, before finally calling...
Since a vector neatly destructs its elements and deallocates the used memory when itself gets destructed, and v.clear() also destructs the elements in the vector, calling v.clear() is a perfectly valid way to delete an entire 2D vector. Note that if you want also the memory for v itself cleaned up you need to call v.sh...
65,208,380
65,237,681
global variable not found in llvm JIT symbol table
I am trying to get a llvm::Module with a global variable to compile with the KaleidoscopeJIT Compiler, however, I get an error in the symbol lookup from the JIT compiler. (KaleidoscopeJIT.h source code from https://github.com/llvm-mirror/llvm/blob/master/examples/Kaleidoscope/include/KaleidoscopeJIT.h ) Upon inspection...
The problem seems to be that uninitialized global variables are somehow optimized out and not added to the symbol table. A quick work around to ensure that the variable gets added to the symbol table is to initialize it with an "Undefined value". The following code allows to do such an initialization with the c++ api /...
65,208,437
65,208,638
How to pass lambda to function that requires class parameter
Edit: Compare was a given parameter class type, so I have created struct Compare, but i don't know how to cast the lambda variable passed in test to Compare class, which is a wanted parameter type. Edit2: Alright guys, I think I sounded pretty unclear, so I'm posting the whole assignment text. Create clamp function wi...
There is nothing in the posted assignment that says Compare is expected to be a struct/class type that you have to implement. There are only 3 ways to pass a lambda in a function parameter: if the parameter is a plain function pointer, and the lambda is non-capturing. if the parameter is defined as a template type. ...
65,208,852
65,208,960
Disambiguating overloaded member functions with non-type template parameters in mutiple inheritance class
I have the following small program: #include <iostream> class Field1 { using Self_t = Field1; public: template<unsigned int KEY, std::enable_if_t<KEY == 1, Self_t>*> int get() { return 1; } }; class Field2 { using Self_t = Field2; public: template<unsigned int KEY, std::enable_if_t<K...
template<unsigned int KEY, std::enable_if_t<KEY == 1, Self_t>*> int get() { return 1; } // ... f.get<1>(); This function takes two template parameters, but you have only provided one. Either pass the second one as well when calling the function, or provide a default argument for the second template parameter s...
65,209,355
65,209,606
Increment pointer when Unpacking Variadic Arguments with Lambda
I have the following code which has a function VariadicWrite and this function accepts a pointer that it can modify by incrementing it to it points to a different memory location depending on how much data is written to it: #include <iostream> #include <cstring> template<typename T> T Read(void* &ptr) noexcept { T...
The problem is your VariadicWrite() call will modify ptr to point to the end of your written data. Then you call Read() without resetting the pointer back to the start, so you read zeros from the uninitialized portion of your buffer that follows the data already written. Insert ptr = temp; between the write and read a...
65,209,390
65,209,483
"Stack around the variable 'b' was corrupted." (No heap allocations)
So I have a simple matrix class, and when I log it to the console everything is fine, but the problem occurs when the program terminates. I haven't allocated any heap memory, it's just a simple template class that can log a matrix to the console. (I plan on adding addition, subtraction, and multiplication though.) #inc...
Issue is this loop (thanks to dxiv ) for (int i = 0; i < R; ++i) matrix[i][i] = identity; access array out of bounds when R > C, you should eliminate that loop and modify previous to (assuming logic to always fill diagonal with identity in your code is correct): for (int i = 0; i < R; ++i) for ...
65,210,101
65,210,238
C++/Win32: Keyboard input to a non-foreground window
My goal: I want my application to be able to respond to specific keyboard shortcuts/hotkeys regardless of whether it is the foreground window without interfering with other applications' use of these shortcuts. For instance, if another process has the foreground window and the user presses the VK_MEDIA_PLAY_PAUSE key, ...
You can use SetWindowsHookEx with WH_KEYBOARD_LL parameter: Here is a sample: #include <windows.h> #include <iostream> HHOOK _k_hook; LRESULT __stdcall k_Callback1(int nCode, WPARAM wParam, LPARAM lParam) { PKBDLLHOOKSTRUCT key = (PKBDLLHOOKSTRUCT)lParam; //a key was pressed if (wParam == WM_KEYDOWN && nCod...
65,210,159
65,212,069
Monitoring data in named pipe (FIFO) in C++
I want to chain the stdin and stdout of several programs via named pipe. These programs act like services or daemons so I wish they could keep reading from a FIFO until they are blocked due to the FIFO is cleared. I modified the code from the answer in the question C++: Read from stdin as data is written into pipe as b...
Why the second t is not blocked when the first t exits in my case When the first t is terminated, it generates an end of file on the fifo and the second t is not blocked anymore. Is there anyway to keep the second t being blocked when the first t exits This is a problem in inter process communication (IPC). The inp...
65,210,374
65,210,724
How to solve requires clause is incompatible
I am trying to implement a recursive version std::iter_value_t with C++20 concept so that the base type T of nested container like std::vector<std::vector<...std::vector<T>...>> can be retrieved. The experimental implementation is as below. template<typename T> concept is_iterable = requires(T x) { *std::begin(x); ...
Lots of things. First, C++20 already has a concept for iterability: it's called std::ranges::range. Second, since C++11, there is no reason to use typedef. Always prefer using. The use of typename was also invalid. So using type = T; rather than typedef typename T type; The reason for this is that using is much more po...
65,210,483
65,215,970
Extracting the minimum value from a file using a while loop c++
I am required to set the minimum value (minValue) equal to -1 in my declarations. How do I, using the || (or condition) within my while loop, extract a minimum value from a positive set of numbers considering that a negative value concludes the program? Also, the double average variable (average), is not calculating th...
I am required to set the minimum value (minValue) equal to -1 in my declarations. With initialization to -1, all positive numbers will be greater than minValue. You can set/initialize it with max value or first input value, or handling the special case in the loop: if (minValue == -1 || intVal < minValue) minValu...
65,210,524
65,211,508
Is it possible to do math inside of a variable name? For example: S[BP1P - 8]O == false
I am trying to create a program that outputs all possible moves(chess). I started by creating variables to check if the spaces are occupied or not so S0O, S1O, etc. Now I want to take a piece marked by a variable in this case BP1(Black pawn 1) with an int value marking square. So if BP1 = 48 how would I check if S40O i...
Using the example from the link above, I put together some code that demonstrates how to use the unordered_map and manipulate the strings within, or you can change the keys before they're assigned (the keys are the colors "RED", "BLUE", and "GREEN" in this example). #include <iostream> #include <string> #include <unord...
65,210,556
65,220,680
Why do templated class data members require the static keyword?
What is the rationale that this does not compile? class Math{ template<typename T> std::map<int, T> m; // error: member 'm' declared as a template }; while making the data member static compiles? class Math{ template<typename T> static std::map<int, T> m; };
This answer was posted by Peter (under the CC BY-SA 4.0 license), as a comment to the question Why do templated class data members require the static keyword?. For exactly the reason the diagnostic described. A non-static data member of a class cannot be a template, since it means that each instance of the class has ...
65,211,184
65,211,490
How to set low latency in serial port open by QSerialPort
I have already developed an application and it performs serial communication with sensors. For an unknown reason, my received data is slow with QT C++ Framework. I have tested the sample code (https://www.pjrc.com/tmp/host_software/receive_test.c). I received data in the appropriate time with this sample code. Here i ...
The descriptor is the Handle of the QSerialPort: #include <sys/ioctl.h> #include <linux/serial.h> // ... pUsbSerialPort->open(QIODevice::ReadOnly); int fd = pUsbSerialPort->handle(); struct serial_struct kernel_serial_settings; ::ioctl(fd, TIOCGSERIAL, &kernel_serial_settings); kernel_serial_settings.flags |= ASYNC_...
65,211,317
65,261,080
How to fix the UClass has no member "WeaponMesh" error?
Currently I have a class for my character like so: .h #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "DarkFantasies_MainCharacter_Base.generated.h" class USpringArmComponent; class UCameraComponent; class ADarkFantasies_WeaponBase; UCLASS() class PROJECT_DF_API ADarkFantasies_MainCharacter_Base...
For anyone that will be look for future answers, I have found the answer. Essentially the problem was that I pointed towards the class and not the actor I spawned. So what I did was I added another variable called weapon pointer to the character and saved the weapon in there which I then used to call upon the mesh of e...
65,211,463
65,211,906
How is `int a[100] = {1}` initialized
I've been told that when we write int a[100] = {1};, the elements after 1 will be initialized to 0. But I didn't find out how this is done. (And is this true?) I've tried the code below to roughly find out the time cost: #define M 500000 clock_t begin = clock(); int main(){ /*-1-*/ //int a[M] = {1}; /*-2-*/...
But I didn't find out how this is done. It is done by the compiler. And is this true? Yes, this is true. but how is this done in lower level It can be done in any way that the compiler designer had chosen. If you are interested on what your compiler did, you can read the assembly that it produced. I'm sorry I di...
65,211,541
65,211,600
Why do I have to assign a size for a std::array, when a plain array doesn't have to be?
std::array<int, 3> foo = {1,2,3}; int bar[] = {1,2,3}; // the size is 3 For a plain array I don't have to assign the size. But I have to assign the size for std::array. Why?
Arrays in C++ have a separate set of rules from other types. If the size is not specified, the size can be deduced from the number of arguments provided in the initalizer. std::array on the other hand is a class template, so you need to specify all the arguments when instantiating an object of that type. From C++17, th...
65,211,714
65,211,947
Moving a unique_ptr vs. using get()?
std::unique_ptr<Something> p{...}; f(p.get()); // is this better f(std::move(p)); // or this? Semantically, I know that the first case is if f just wants to do something with p but doesn't want to "own" it, whereas the second transfers ownership of p to f so that afterwards p is useless. But, this is too abstract I'm ...
This function does not participate in ownership: int f(Something* p) { if (p == nullptr) return 0; return 1; } It merely uses the pointer value to do something. It could also dereference the pointer, but it has no buisness in deleting the pointed to object. Not participating in ownership is indicated by taking...
65,211,930
65,212,145
OpenGL - blend two textures on the same object
I want to apply two textures on the same object (actually just a 2D rectangle) in order to blend them. I thought I would achieve that by simply calling glDrawElements with the first texture, then binding the other texture and calling glDrawElements a second time. Like this: //create vertex buffer, frame buffer, depth b...
Thanks to @tkausl for the tip. I had depth testing enabled during the initialization phase. // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); The option needs to be disabled in my case, for the blend operation to work. //make sure to d...
65,211,968
65,213,091
How a '\t' escape sequence different than that of four spaces manually?
I was making matrix in C++ and to show it look like matrix I used nested loops of for. for (i=0; i<m; i++){ for (j=0; j<n; j++){ cout<<matrix[i][j]<<"\t"; } cout<<"\n"; suppose I input the elements of matrix to be 1, 2, 3, 45, 45, 6 of order 2x3. so the output is 1 2 3 ...
The \t (tab) is short for tabulator which is inherited from (professional) typewriters with built-in tabulator stops at certain (evenly spaced) columns to help the typist to create tables etc. In some typewriters the tabulator stops could even be set by the typist. When pressing the ->| (tab) key the typewriter's carri...
65,212,036
65,212,157
why am I able to call grandparent method with grandchild object? I read that it was not possible
This is the code I got from the internet... and how virtual keyword is working? i think this virtual keyword has something to do with this behaviour but I don't understand what it is. class A { int x; public: A(int i) { x = i; } void print() { cout << x; } }; class B : virtual public A { public: B() ...
why am I able to call grandparent method with grandchild object? Because that is how inheritance works. That member function was inherited by the child class and the grand child. I read that it was not possible Either what you read is wrong or you misunderstood it. how virtual keyword is working? When a virtual b...
65,212,049
65,212,850
Is it safe to pass a _bstr_t object to a function expecting BSTR as argument?
I am new to C++ so please bear with me. I know that _bstr_t is just a wrapper class for BSTR but, as seen in the MSDN documentation, _bstr_t does not have an operator to convert itself to BSTR. So can I pass a _bstr_t object to a function expecting a BSTR as argument, and is it safe? Or is there any better way to do th...
_bstr_t does not have an operator to convert itself to BSTR Yes and no. BSTR is defined to be equivalent to wchar_t* in the "afx.h" header file: typedef _Null_terminated_ LPWSTR BSTR; And the _bstr_t class (in "comutil.h") does have conversion operators for that, with or without a const qualifier, as in: class _bst...
65,212,254
65,212,319
what is "terminate called after throwing an instance of 'std::bad_weak_ptr' " after I use shared_ptr
The class Request adds itself into a class EventLoop. The shared_ptr loop is not nullptr. However, I get some problems. The code is as follows: #include <iostream> #include <vector> #include <memory> using namespace std; class Request; typedef std::shared_ptr<Request> RequestPtr; class EventLoop { public: Event...
In order to use the shared_from_this, you need to have that shared pointer. In main function, try instantiating not a heap object Request, but std::shared_ptr<Request> r = std::make_shared<Request>(); r->add_inself();
65,212,489
65,910,019
Error when starting a new project of C Cpp in eclipse
When using Eclipse for C C++ operations it shows this error. I have installed mingw64 and jdk14, also in the system variables>> added both bin path there. "An internal error occurred during: "Load QML Analyzer". java.lang.NullPointerException"
Just found this on the web. It worked for me. Might help you as well, if you still need it. "If you need the Qt plug-ins, the workaround is to downgrade to Java 14. Otherwise, to get rid of the message box, it is possible to uninstall the Qt plugins: go to the Eclipse menu → (Help →) About Eclipse IDE click the Instal...
65,212,799
65,212,970
Why exception caught without throwing in C++?
I am running this program. As per my understanding, there should be a bad allocation exception raised within the try block and should cause a runtime failure. However, the program executes without any problem. I have the following questions: Why is there no run-time error? How does the control reach catch block even ...
-1 will be converted to the std::size_t value std::numeric_limits<std::size_t>::max() due to the implicit conversion to an unsigned type. It is indeed unlikely that you have that much memory available. However a std::bad_alloc might not be thrown if your operating system doesn't actually allocate the memory until you c...
65,212,922
65,213,055
How can I define virtual function which takes derived type as its parameter?
I have a parent class Obj with empty virtual function cmp class Obj{ public: virtual int cmp(const Obj& val) = 0; ... }; I am trying to define that function in the subclass MyString, but instead of const Obj& as argument, i use const MyString& which probably occures the error "Emprty virtual function Obj::cmp h...
If you want to use overriding you have to define method in subclasses as it is in base class and can't change parameters of virtual function. In method of subclass you can cast to a type you need. class Obj { public: virtual int cmp(const Obj& val) = 0; ... }; class MyString : public Obj { priv...
65,212,941
65,213,010
How to use union in C++ correctly?
I have following union in C++ union MsgData { struct { uint32_t msb : 1; uint32_t reg_addr : 7; uint32_t data : 8; uint32_t fill : 3; uint32_t crc : 5; } bits; uint8_t bytes[3]; }; In case I do following (address contains 26, data contains 255 - both ...
The behaviour of your program is undefined because you read from an inactive member of the union. How to use union in C++ correctly? In general: By only reading from the active member of the union which is the one that was assigned last. Exceptions do exist. For example, reading from inactive member that has the same...
65,213,494
65,213,697
How to register a window with the default cursor using LoadImage() instead of LoadCursor?
I can register a window class with the default cursor using: WNDCLASSEX wc = {0}; wc.hCursor = LoadCursor(nullptr, IDC_ARROW); But after looking at the docs for LoadCursor here: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadcursora it says that "This function has been superseded by the Loa...
According to the document: hInst To load an OEM image, set this parameter to NULL. name To pass these constants to the LoadImage function, use the MAKEINTRESOURCE macro. For example, to load the OCR_NORMAL cursor, pass MAKEINTRESOURCE(OCR_NORMAL) as the lpszName parameter, NULL as the hinst parameter, and LR_SHARED as...
65,214,289
65,214,428
How does this for loops works?
can someone explain how the highest and lowest works in the if statement? and what happen when we use cin.sync()? it works but i dont know how it works. using namespace std; int main() { string name, p1, p2; int n; double salary, sales, income, commission, highest, lowest; highest=0; lowest=9999999; for(n=1; n<=...
This loop will run only two times. Once for n=1, and then for n=2. From what I understand we want to get the highest value. So we initialize it with the min value that is 0. Next whatever value salary has for the first time will be set as highest. After this (from the second time) only the value of the highest will cha...
65,214,629
65,225,339
Results of RANSAC plane segmentation depends on the size of point cloud?
For testing of my PCL client code, I generated an artificial set of points that all lie on a plane (something like a,b,c,d = 1,1,-1,0 for the plane model a*x+b*y+c*z+d=0). After fitting the plane model I'd expect anything that is linear dependent to above stated coefficients. The range (and size) of the point cloud is ...
Despite it's "random"-ness, for a cloud containing a plane with no outliers and no noise whatsoever, plane segmentation should always succeed in this case (any 3 non-colinear points will give you the correct plane). Story short - by setting seg.setOptimizeCoefficients(false); we get the correct coefficients for n=5000 ...
65,214,677
65,215,142
C++ Calling parent virtual function from pointer
I have this code: void FAuCoreEditorModule::OnAssetEditorOpen( UObject* EditObject , IAssetEditorInstance* Toolkit) { FName NAme = Toolkit->GetEditorName(); if(Toolkit->GetEditorName() == "CurveTableEditor") { FAssetEditorToolkit* AET = static_cast<FAssetEditorToolkit*>(Toolkit); AET->...
It this legal ? Potentially yes. Not necessarily. Static downcasting is allowed if IAssetEditorInstance is a non-virtual unambiguous base of FAssetEditorToolkit and if the pointer is truly to an object of such type (or a type with such non-virtual base). If some of those restrictions are not satisfied, you can use dy...
65,214,764
65,214,847
C++ Templates polymorphism used togheter
I need to define a GUI for the Camera class where I have different types of camera. So to do this I really want to use polymorphism because make sense to use one interface Camera for different implementations (Camera1 , Camera2). The problem is that different implementations require different type of BufferCalculations...
It depends on what you want to do in CameraGui. If it does not depend on the template parameter type of Camera, you could do something like the following: class BasicCamera {...}; template <typename T> class BufferCalculation {...} template <typename T> class Camera : public BasicCamera { BufferCalculation<T> bufferCal...
65,215,375
65,223,215
FLEX replace words with dates
Im really new to flex and sadly there are very few examples on the internet compared to other languages. I want to replace the words: TODAY with today's date TOMORROW with tomorrows date1 YESTERDAY with yesterdays date TODAY-n with todays date before n days TODAY+n with todays date after n days. I did some research a...
Here's a very basic implementation, concentrating on flex rather than the intricacies of computing and showing dates. It depends on the fact that the default action for unrecognised characters is to copy them to the output stream. However, to avoid recognising TODAY in the middle of a word (like AATODAYBB), I added a p...
65,215,459
65,215,531
How can I cast (n+n%2) expression to float so it will give me float number after division?
I am trying to get float number result from this c++ code, but i cannot for some reason: int n = 5; std::cout << static_cast<float>(n + n % 2) / 2 << std::endl; Console output is 3. Could you explain what I am missing in this expression?
How can I cast (n+n%2) expression to float so it will give me float number after division? You can use static_cast, as you did in your example. Console output is 3. Could you explain what I am missing in this expression? Your are missing nothing. The cast to float was achieved successfully and 3 is the correct resu...
65,215,469
65,215,553
where am i wrong?? EXC_ARITHMETIC (code = EXC_I386_DIV, subcode = 0x0)
I can't understand where I'm wrong. I think the error is in the averaging. Thread 1: EXC_ARITHMETIC (code = EXC_I386_DIV, subcode = 0x0) It returns me this error. Thanks in advance to those who will consider my request. #include <iostream> using namespace std; int main () { int m, n; int a[30]; ...
for (int i= 0; i<30; i++) { if (a[i]>m && a[i]<n) { somma = somma + a[i]; media = somma/i; } } If you successfully enter the if statement in the first iteration you try to divide by 0 so your program crashes Also, you should probably save the number of values you sum to somma to calculate...
65,215,607
65,215,639
C++ language feature: double square brackets [[ ]] used in class or method declaration
I am currently diving into smart contract development for eosio. By walking through the tutorials I noticed a certain C++ language feature I have never seen before: #include <eosio/eosio.hpp> using namespace eosio; class [[eosio::contract]] hello : public contract { public: using contract::contract; [[...
What is the term for this C++ language feature? The double square brackets are syntax for attributes. They are specified in the C++ standard section [dcl.attr]: [dcl.attr] Attributes specify additional information for various source constructs such as types, variables, names, blocks, or translation units. My ques...
65,215,616
65,217,247
Reading File through ifstream with delimiters
I am trying to read from a textfile that includes the id, name, and description of an item. They are delimited by the '-' character. The code works for the first line, but for the rest of the lines, only the ID is read properly while the name and description are blank. Here is a snippet from the data text file that I a...
You missed std::list<ItemData> itemsList; from your code. #include <iostream> #include <string> #include <fstream> #include <string> #include <vector> struct ItemData { int ID; std::string name; std::string description; }; std::vector<ItemData> itemsList; void GetItemData() { std::ifstream File("item...
65,216,184
65,216,355
Why does public const not imply static?
In C# const implies static so you can reference a public const without having to reference an instance of a class or struct. In C++ this is not the case. If you want to access a const member variable in C++ you need to first have a reference to an instance of the class. In C++ as far as I can tell making a member vari...
Just because the member is const does not imply that it has the same value in all instances. Consider: struct foo { const int x = 1; foo(int a) : x(a) {} }; foo a{1}; foo b{2}; Now a and b have different values for their const int member. I don't know C# but it looks like something is missing when you c...
65,217,728
65,217,791
Is there any way to check how much data/bytes is written in buffer in C
is there any way to check how many bytes are written in a buffer at the exact moment? I would like to dynamically set how much data I send via socket using socket.send(). Now I have problem, lets say that my file is 200KB and my buffer is set to 24KB so I need to send 9 packages and my output file is 216KB big and not ...
socket.send is unknown to me. I assume you mean using send(2) on some socket(7). In many cases (think of some tcp(7) traffic going thru several Wifi routers), the packets could be fragmented. So a given send(2) on one side could correspond to several recv(2) on the receiving side and vice versa. Then you need to manag...
65,217,916
65,217,979
Virtual destructor, what would happen I didnt have a destructor in the derived class?
I've just had my lesson about virtual destructors and I have a question. Lets say we have this code below: #include <iostream> class Base { public: virtual void fun() { std::cout << "Base Fun" << std::endl; }; virtual ~Base() { std::cout << "Base Destructor called" << std::endl; }; }; class Derived : public B...
All classes have a destructor. If you don't write one explicitly, then compiler will implicitly generate it. Thus the case you are asking about "if I didn't have a destructor" doesn't exist. and would the whole program still work as earlier? It would work but not quite the same way since the implicitly generated dest...
65,217,972
65,218,069
How to wrap C++ types into a list for variadic arguments
Related to an earlier question from me. Just starting to use fold expressions, but it does not yet behave as I intend to. The background is that I want to be able to define 'my_list' in a dedicated header file to simplify maintenance. A call with separate types works, but when calling with 'my_list' it does not work....
You need to specialize on your typelist (or perhaps any typelist). Using function object variable templates, this would be: template <typename ... Types> static constexpr auto myFunc2 = [] { (std::cout << "Size: " << sizeof (Types) << std::endl, ...); }; template <template<class...> class TL, typename ... Typ...
65,218,195
65,218,498
how can I apply C++ array in this?
How can I apply C++ Array to this? the picture above is the format/question. How can I apply C++ Array to this? the picture above is the format/question. #include <iostream> using namespace std; int main(){ int profit, monthly, Sales, Expenses; string Month[6] = {" January"," Febuary"," March"," Apri...
First of all, your code is a mess. Next time go through some tutorials, so that you know how to work with basic elements of language (e.g. loops, arrays,..). Now to get to the code: #include <iostream> using namespace std; int main(){ int profit; string Month[6] = {" January"," February"," March"," April"," Ma...
65,218,367
65,220,469
How to guarantee compile-time evaluation of algorithm while allowing runtime invocation as well
I have a hash function, I want to implement it with C++20 consteval to make sure the inputs I want to be evaluated at compile time will be done before runtime. That's for the constants and hardcoded content. However, later I need to compare them with runtime/dynamic variables, for the equals() to work I have to calcula...
How to guarantee compile-time evaluation of algorithm while allowing runtime invocation as well Write your function as a constexpr one, and then, if you want to guarantee a particular result is done at compile-time, write the result into a constexpr variable: constexpr int f(...) { ... } constexpr int compile_time_r...
65,218,702
65,219,246
I have n number of elemet in the 2 sets and i have to go through them such that at each iteration i get the current element ans also the next element
BELOW , Is the code i wrote which is showing error ( that we cant use end()-1 and itr+1 operations). MY purpose is to go through the set as in pair. eg X[1 2 3] i want to get {1 2} {2 3}. for(itr=X.begin();itr!=X.end()-1;itr++) { int l1,l2; l1 = *(itr+1) - *itr; for(itr1=Y.begin();itr1!...
Set iterators don't support + or -. This seems like the easiest way to do what you want std::set<int> X = ...; auto i = X.begin(); if (i != X.end()) { auto j = ++i; while (j != X.end()) { int l1 = *j - *i; ... // similar code for Y loop ... ++i; ++j; } } ...