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,076,574
72,086,141
Error handling exponent ("e") preceding digit
I'd like to create a function that checks whether a number input with an exponent such as 1.32e2, 1e3, +1.32e+2 indeed has the e in the correct position, after a number, not before it (such as e1 or .e4) I'm a beginner so it's just trial and error at this point. This is what I have so far: bool validate_alpha_e(string ...
Worked it out. Thanks for the comments but I wasn't able to figure it out. So I had to create 3 separate functions (see below) First function validates for correct input before the e. Second function validates for correct input after the e. Third function validates that the first character is not an e. Put all these to...
72,076,590
72,076,744
C++ subtuple from tuple given variadic index sequence
Assume I have a std::tuple, I'd like to write a function which receives a tuple and a variadic sequence outputting a subtuple containing the columns corresponding to those indexes. Example usecase: std::tuple<int, char, float, std::string> t{1, 'd', 3.14, "aaa"}; auto subtuple = extract_subtuple(t, 0, 2); // returns s...
You can't do it directly because tuple indices should be constant expressions and function parameters are never constant expressions even if corresponding arguments are. You have two main options. Firstly, you could make indices template parameters: template<std::size_t... Is, class... Ts> auto extract_subtuple(const s...
72,076,844
72,076,907
My programs doesn't return 0 when deleting array pointer
When I try to delete array pointer which declared like short *width = NULL; width = new short[lenght]; delete[] width; the programs stop at delete part and returns a random number. here is my all program int main(){ short **junction = NULL, *width = NULL, length = 0; ifstream input; input.open("sample_inp...
Your code should be actually fine. Please show us the whole program. florian@florian-desktop:~$ cat -n test2.cpp 1 #include <iostream> 2 int main() 3 { 4 const int length = 4; 5 short *width = NULL; 6 width = new short[length]; 7 delete[] width; 8 } florian@florian-deskto...
72,076,963
72,077,400
Fastest way to count words of string
How could I make this algorithm faster and shorten this code which counts word of given string? int number_of_words(std::string &s) { int count = 0; for (int i = 0; i < s.length(); i++) { // skip spaces while (s[i] == ' ' && i < s.length()) i++; if (i == s.length()) break; // word found ...
Your code is quite alright, speed-wise. But if you want to make your code shorter, you may use find_first_not_of() and find_first_of standard functions, like I did in following code that solves your task. I made an assumption that all your words are separated by only spaces. If other separators are needed you may pass ...
72,077,314
72,077,358
Segmentation fault in C++ adding item to a vector
Lately I have set myself to learn C++, and while working on a bigger project, I have tried to use 'vectors'. But every-time I try passing it a value, it exits with a segmentation fault. Here is my terminal output: #include <iostream> #include <vector> using namespace std; int main(){ vector<int> test; cout << "...
Size it vector<int> test = {0,1,2,3,4}; or vector<int> test(5) But you might want to use push_back in this situation #include <iostream> #include <vector> using namespace std; int main(){ vector<int> test; cout << "hello world" << endl; test.push_back(0); cout << test[0]; return 0; } Basically...
72,077,483
72,077,524
Include instructions from other file in CMakeLists.txt
I want to create a second file, for example Instructions.txt, and be able to include it's CMake instructions to the main CMakeLists.txt, for example: // Instructions.txt set(MY_VARIABLE value) set(MY_SECOND_VARIABLE 1234) // CMakeLists.txt <HERE INCLUDE INSTRUCTIONS.TXT> // And be able to use those variables, for exa...
You usually do that simply by using another cmake. Contrary to what you might believe, the file extension is different for other file than build files. Let's call this file instructions.cmake: set(MY_VARIABLE value) set(MY_SECOND_VARIABLE 1234) Then you can include it like this inside your CMakeLists.txt: include(inst...
72,077,841
72,077,985
why return type of operation overloading is sample
why sample as return type in operation overloading can anyone explain how this code works. why the return type is class itself whats the use of .x here #include<iostream> class sample { private: int x; public: sample(); void display(); friend sample operator+(sample ob3,sample ob4) ...
why sample as return type in operation overloading The return type is sample because the author that wrote the operator overload chose to use sample as the return type. It is quite typical for binary operator+ overloads to have the same return type as the type of the operands. Part of why it is typical is that it fol...
72,078,767
72,078,805
How to Add 0 infront of an int without external library c++
What i Hope to accomplish So i have a class with date and time and i am using a struct in which year, month, date are integers I want when the user enters a number for example 3 it must output 03 but must be in an int format without using the IOMANIP library or fmt library as when i use these library i get 'error time ...
setw works in conjunction with setfill so something like std::cout << std::setw(2) << std::setfill('0') << day; might work for you. See also https://en.cppreference.com/w/cpp/io/manip/setfill
72,079,021
72,079,267
Example of use of std::forward_iterator
I have a compute function that looks like this: template <typename PayloadType, complex ValueType> static void comupte_everything( const typename std::vector<DataPointWithAverage<PayloadType, ValueType>>::iterator begin, const typename std::vector<DataPointWithAverage<PayloadType, ValueType>>...
std::forward_iterator is a concept, not a template, so you can't use it like a template, if you want to constrain the value_type of iterator, then you can template<typename T> constexpr bool is_DataPointWithAverage = false; template<typename PayloadType, complex ValueType> constexpr bool is_DataPointWithAverage< Dat...
72,079,217
72,079,434
When declaring a function that has an argument pointer to function, is there such a way to restrict the argument func such that it belongs to a class
Let's say that I have the function doSomething(char* (*getterOne)()) { //do something here } although I've named the parameter of doSomething "getterOne", I have no way of verifying that the function is going to be a getter ( I think? ). So I wonder, is there a way to explicitly specify the kind of function that ca...
A function pointer and a pointer-to-member-function are two different things. If you make a function that accepts a pointer-to-member-function you have no choice but to specify which class it belongs to. Here is an example. #include <iostream> struct Cat { char* myGetter() { std::cout << "myGetter\n"; ...
72,079,305
72,762,162
Windows Sharing file over network NetShareAdd Error 53
I tried to compile this example from microsoft docs for sharing a folder over network however the executable gives an error. Full Code : #include "stdafx.h" #ifndef UNICODE #define UNICODE #endif #include <windows.h> #include <stdio.h> #include <lm.h> #pragma comment(lib, "Netapi32.lib") void wmain(int argc, TCHAR *ar...
With admin privileges, servername ConsoleApplication1.exe localhost and ConsoleApplication1.exe 127.0.0.1 worked fine.
72,079,440
72,079,503
winapi handling multiple keys
I need the program to be able to handle multiple keys at the same time. For this I wrote this code: case WM_KEYDOWN:{ int debug=pix.getMsg().lParam; if(debug>=16 && debug<=23){ char lpKeyState[256]; ZeroMemory(lpKeyState,256); char input[2]; int symNum...
As stated in the documentation of WM_KEYDOWN, bits 16 to 23 of lParam contain the scan code. To extract the scan code from lParam, you can use the following line: DWORD dwScanCode = ( lParam >> 16 ) & 0xFF;
72,079,446
72,080,399
How do I reset the GLFW Fragment / Load a different shader during runtime?
I'm writing a shadertoy-like tool for the desktop. It uses GLFW (OpenGL), Glad, and ImGui to render out images. I've gotten to a point now where I fixed all my previous issues, but I'm now stuck on one particular problem that's been plaguing me the past few days. I want to be able to hot-reload shaders. Right now it ta...
So after fiddling around a while, I actually figured it out. Turns out I was doing way more than was required. All I needed to do was detach the fragment at the start, then delete everything, then re-attach a new fragment, link the program again, then detach and delete it again. Now I can reload my shaders during runti...
72,079,593
72,079,638
Cast raw bytes to any datatype
I'm worried if my implementation is unsafe or could be improved. Suppose I have an array of bytes (more specifically, std::byte); is casting an element's address to a void pointer and then to any datatype safe? template <typename To> constexpr To *byte_cast(std::byte &From) { return static_cast<To *>(static_cast<void...
Your paired static_casts are exactly equivalent to a reinterpret_cast. Both cause UB due to strict aliasing violations (except when the target type is char, unsigned char, or std::byte). The solution is std::bitcast<T>(source). It has the interface similar to what you attempted, except that it returns by value. It's no...
72,079,627
72,079,798
Do while loop keeps looping c++
So, I want this program to keep prompting when the number of digits isn't 16, that part worked, but whenever I try to input 16 digits it loops without letting me type anything in again. This is what I wrote: do{ cout<<"insert number pls: "; cin>>number; //counting digits number_count = 0; whi...
The value limit of int which you're using to store your number is 2147483647, which corresponds to 10 digits. That's why it stopped working at 11 digits. An easy workaround is to use long long int instead. The maximum value in this case is 2^63 which equals 9223372036854775807 (19 digits). You can check the max value o...
72,080,085
72,080,159
why can't I declare the size for the array inside a class?
So I am working on a project and it compiles with no errors but I can't run when I declare the size of the array inside the class but when I declare it inside the class it works. This is what I get when I declare it inside the class. c:\Users\david\OneDrive\Desktop\account>cd "c:\Users\david\OneDrive\Desktop\account" ...
Non-inline static member variables must be defined outside of the class in exactly one translation unit. Like this: const unsigned Account::n{5}; However, this will make it a non-constant expression prior to this initialisation, so you wouldn't be able to use it as the size of the array. A solution is to use an inline...
72,080,211
72,080,388
Using type trait to ensure a type cannot be derived from itself
I would like to statically check if a class is derived from a base class but not from itself. Below is an example of what I try to achieve. The code compiles unfortunately (never thought I would say this). I was hoping for the second static assertion to kick in and see that I tried to derive a class from itself. I woul...
Type must not derive from Derived Derived is not a type in itself, it's a template which in std::is_base_of<Derived, T>::value gets resolved to the current specialization in the context it's in and it can never be T. If you have Derived<Derived<Base>> then T is Derived<Base> and the Derived without specified template...
72,080,305
72,081,415
Copy without duplicates using generic function
I'm trying to make a generic function which will copy elements without duplicates from one block to another. Function accepts three pointers/iterators and must work for all types of iterators. Function should return a pointer/iterator that points exactly one place behind the destination block. p1 and p2 are from the sa...
CopyWithoutDuplicate can be simplified. auto CopyWithoutDuplicate(iter_type1 p1, iter_type1 p2, iter_type2 p3){ return std::unique_copy(p1,p2,p3); } The working example: #include <iostream> #include <iterator> #include <algorithm> #include <vector> #include <unordered_set> template<typename iter_type1, typename i...
72,080,506
72,080,521
Making a pointer point to an element of char array?
Let v be an array of chars, with values "Hello". If I run the following: char v[]="Hello"; char* p_char= v; char* p_char_2 = &v[1]; cout<<"p_char: "<<p_char<<"\n"; cout<<"p_char_2: "<<p_char_2<<"\n"; cout<<"p_char_2 value: "<<*p_char_2<<"\n"; it returns p_char: Hello p_char_2: ello p_char value: e I'm not sure ...
p_char_2 has type char *, which is the type traditionally used to pass around pointers to strings in C and C++. So the designers of the C++ language decided that when you pass a char * to std::cout << , it prints it as a null-terminated string. That's just how the language was designed, and it makes it easy to output...
72,080,986
72,080,997
One Definition Rule and static member initialization
I've read the one definition rule yet could not find the answer to what I'm trying to achieve. I'm implementing a class in which I need to count every occurrence created of this class, let's name it "Item" Such that when the header and CPP files are complicated, the static member is defined and with every call to the ...
I was using Item::idCounter all along, while I needed to use int Item::idCounter; Weirdly, no flags were raised about this.
72,080,987
72,081,041
C++ Array of random numbers
I have a bit of a problem with this. I've tried to create a function to return a random number and pass it to the array, but for some reason, all the numbers generated are "0". #include <iostream> #include <ctime> #include <iomanip> using namespace std; int generLosNum(int); int main() { srand(time(NULL)); ...
So the return for your int generLosNum(int LosNum) was printing 0 because you had it returning LosNum which was initialized equaling to zero. I changed your code so it works and will print out the 10 random numbers. #include <iostream> #include <ctime> #include <iomanip> using namespace std; int generLosNum(); int ...
72,081,124
72,081,179
Why it is a segmentation fault with this code fragment?
Here is my code about Matrix (I decided to practise OOP writing own Matrix class) Matrix.hpp #ifndef MATRIX_HEADER #define MATRIX_HEADER typedef unsigned int u_int; class Matrix { double **mtrx; u_int x, y; public: Matrix(u_int a, u_int b); Matrix(const Matrix &); ~Matrix(); double det(); ...
You might consider using a 1D double[x*y] array instead of a 2D double*[x] of double[y] arrays. It will make memory management a bit easier, since you will have only 1 array to deal with, instead of multiple arrays. In any case, your Matrix(const Matrix &) copy constructor should not be delete[]'ing anything in mtrx ye...
72,081,271
72,081,294
I am getting a "base operand of ‘->’ has non-pointer type" when calling my function
In this program, I am supposed to call animal.at(0)->makeSound() in main() and have it return "Woof" from the public member function makeSound() for Dog. However, when I compile the code as written, it gives me an error: base operand of '->' has non-pointer type While I know there are other ways around this, I am not...
The compiler error is because the vector is holding Animal objects, not Animal* pointers to objects, so you would have to use the . operator instead of the -> operator to access the makeSound() member, eg: animal.at(0).makeSound(); // or, since you KNOW there is 1 object in the vector, the // bounds checking of at() i...
72,081,278
72,081,350
Is it possible to union variable conversion function?
For example, there are three variable conversion functions. //Int int toInt(std::string input) { int ret = strtol(input.c_str(), 0, 10); return ret; } //Double double toDouble(std::string input) { double ret = strtod(input.c_str(), 0); return ret; } //Const char* const char* toChar(std::string input) ...
Your "using" code is passing a template argument to toConvert(), so make sure toConvert() is actually a template, and then you can specialize it for each type you want, eg: template<typename T> T toConvert(std::string &input) { return T{}; /* or, throw an exception... */ } template<> int toConvert<int>(std::string &in...
72,081,406
72,081,533
Convert an integer to an array of digits C++
I'm working on the "Plus One" LeetCode problem, which has you write a function that takes a number (represented by an array of digits), adds one and returns the result as an array of digits. Here is the problem statement: You are given a large integer represented as an integer array digits, where each digits[i] is the...
If what you really want is just to get the resulting vector, you can do this with math instead of converting things to strings std::vector<int> plusOne(const std::vector<int>& digits) { std::vector<int> res = digits; res[res.size()-1] += 1; // carry the 1 if any digit is > 9 int p = res.size()-1; w...
72,081,621
72,081,639
Automatic constructor inheritance in C++20
I just have this code, and I wonder why this code compiles in C++20 and later, but it doesn't compile in C++17 and earlier. struct B { B(int){}; }; struct D : B { }; int main() { D d = D(10); } I know that inheriting constructors is a C++11 feature. But class D doesn't inherit the B::B(int) constructor, even t...
C++20 added the ability to initialize aggregates using parentheses; see P0960. Previously, you could have initialized d using D d{10};; now you can do the same thing with parentheses instead of braces. The class D does not implicitly inherit constructors from B.
72,081,724
72,082,040
Why does exporting a type alias such as std::vector<std::string> in a module allow use of both std::vector and std::string in some internal partition?
I am currently using Visual Studio 2022 Update 17.1.6, and I found something interesting with exporting type alias. For reasons I don't understand, when I export a type alias for some data type such as std::vector<std::string> in a module interface file, I can use both std::vector<> and std::string in the file that imp...
Here's a funny thing about modules: export declarations only matter for code outside of a module. If you import a module unit that is part of the same module as yourself, you have access to all of the declarations in that module unit. This allows you to have "private" declarations which are not exported to the module's...
72,082,143
72,082,166
error: anachronistic old-style base class initializer while using cmake
I am trying to run the code in repository Link. Here, is the Google Colab link which installs all the libraries as required to run the repository. - Link In the link, there are two ways I have built the project. One is using qmake and the other is using cmake. Both of them give me the same errors. I searched for the er...
You defined a proprocessor macro named len(). We can tell from the GCC error message that the file /usr/include/mlpack/core/data/serialization_shim.hpp contains the code len(len) inside it, which is presumably intended to initialize the len member of a class. But the preprocessor is inserting your code there and caus...
72,082,414
72,088,538
Does std::ranges::to allow converting to a std::map?
In the std::ranges::to paper wg21.link/p1206 ths overview section has the following //Supports converting associative container to sequence containers auto f = ranges::to<vector>(m); However I can't find where the detail of converting to a std::map is descibed in the rest of the paper. I tried range-v3 and Sy Brand's ...
Does std::ranges::to allow converting to a std::map? Yes. I tried range-v3 and Sy Brand's implementation of ranges::to in https://github.com/TartanLlama/ranges and neither of them compiles code converting a range to a std::map I haven't tried Sy's implementation, and it looks like range-v3's implementation is weird...
72,084,241
72,084,352
How to store a specific object's member function of known signature in a variable in C++?
What is the recommended way to store a reference to a non-static member function of a specific signature on some object instance? In a way where the calling code needs not to know of the object's class (i.e. no casting), just that the function is the correct signature. For example, if there are two different classes wi...
As you have to store not only the pointer to the member function but also the object which the function should access, you need a way to store both in a single kind of object. As C++ has lambda functions you simply can take them and use them like in the following example modified from your code. class Foo { public:...
72,084,796
72,084,871
Is there a best way to deal with undefined behavior in bitwise conversion between floats and integers in C++14, C++17, C++20 and different compilers?
Which way in below tests is the most preferred in terms of dealing with undefined behavior, auto-vectorization (for struct of arrays) and portability (clang,gcc,msvc,icc)? Is there another way of doing same operation? #include <iostream> #include <cstring> union trick1 { float fvar; int ivar; }; struct trick2 { ...
trick1 (union): Undefined behaviour in ISO C++, unlike ISO C99. The C++ compilers you mentioned support it as an extension in C++. trick2 (std::memcpy) is your best choice before C++20: Well defined with the precondition that sizeof(int) == sizeof(float), but not as simple as std::bit_cast. Mainstream compilers hand...
72,085,417
72,085,971
How to extract all tuple elements of given type(s) into new tuple
The existing tuple overloads of std::get are limited to return exactly 1 element by index, or type. Imagine having a tuple with multiple elements of the same type and you want to extract all of them into a new tuple. How to achieve a version of std::get<T> that returns a std::tuple of all occurrences of given type(s) l...
Only C++17 is needed here. std::tuple_cat is one of my favorite tools. Use a std::index_sequence to chew through the tuple Use a specialization to pick up either a std::tuple<> or a std::tuple<T> out of the original tuple, for each indexed element. Use std::tuple_cat to glue everything together. The only tricky par...
72,086,309
72,088,506
How to create c++ lib with specific architecture?
I am using gradle to build c++ library C++ library gradle reference 1. Configure library target machines library { targetMachines = [ machines.linux.x86_64, machines.windows.x86, machines.windows.x86_64, machines.macOS.x86_64 ] } 2. Configure library linkages library { linkage = [Li...
The reference you've provided gives a very good documentation of what is needed. There are 2 types of libraries, static and shared, that you can create. For the linkage config, you will have to specify the type of library that you would like to create. The targetMachines specifies the configuration of the system where ...
72,086,552
72,086,585
Why doesn't accessing this nullpointer cause an exception?
#include <iostream> class TestClass { public: TestClass() { std::cout << "TestClass instantiated\n"; } ~TestClass() { std::cout << "TestClass destructed\n"; } void PrintSomething() { std::cout << "TestClass is printing something\n"; } }; int main() { TestClas...
Why doesn't accessing this nullpointer cause an exception? Because it's not specified to cause an exception. Accessing through a null poitner results in undefined behaviour. Don't do it.
72,086,820
72,087,404
How to make qlineedit only for some string?
I'm newer for qt. I want to make a lineedit only sell signals for some string,like apple,banana,melon. How can I get it with regex or other method?
Just use QComboBox and check it's editable flag
72,086,996
72,087,324
xarray multiplication via operator * and raw loop give different results
I'm a beginner at xtensor and in the following code, I thought the variables result and sum should be equal but aren't. In this example result == 1000 and sum == 55000. The two variables also hold different results if I compare operations like xt::transpose(x)*A*x and its raw loop implementation (where A has compatible...
There is a small issue in the following line: double result = (xt::transpose(b)*x)(0); Very understandably, you may assume that the multiplication of the vectors gives the sum over the pointwise product, because this is what mathematical expressions would do. However this is not what xtensor does. Fo xtensor, the ...
72,087,238
72,094,479
The module "%VSINSTALLDIR%\DIA SDK\bin\msdia140.dll" failed to load, while trying to install llvm on windows 10
I am trying to get started with compiler development using llvm, I follow official setup page on the 10th step and am getting the following error The module "%VSINSTALLDIR%\DIA SDK\bin\msdia140.dll" failed to load make sure the binary is stored at specified path or debug it to check for problems with binary or depende...
I had the same problem as you at first, please read my solution carefully: You need to use the cd command to enter the folder where you want to install LLVM. Regarding the cd command, I suggest you search for usage methods on Google, I believe it will be easier to understand than what I described. The documentation ...
72,088,421
72,090,259
Why template class assignment operator can use "templated copy constructor" to assign different type
I have a template<class T> class Container {}. While doing some code experiments, I realised that when I call the assigment operator (operator=()) with a different type (i.e. passing a different template parameter to my Container template class), it compiles. It turns out that this is possible because I also have a "te...
Just like @Jarod42 said in the comments. I used cppinsights.io and realised that the compiler is seeing c2 = c1 as c2.operator=(Container<float>(c1));, so I suppose it is simply looking for a conversion constructor (what we called a "templated copy constructor" earlier), to see if there is any known way to cast one typ...
72,088,667
72,088,732
Should I move the value out of an optional or move the whole optional?
Is there an effective difference between std::move(*optional) and *std::move(optional)? Which one is preferable? Full example: #include <optional> #include <vector> void foo() { std::optional<std::vector<int>> ov = std::vector<int>{}; std::vector<int> v; v = std::move(*ov); } void bar() { std::optiona...
They do the same thing. In v = std::move(*ov);, *ov is a std::vector<int>& so std::move(*ov) gives you a std::vector<int>&& that you are trying to assign to v. In v = *std::move(ov); ov is a std::optional<std::vector<int>> so std::move(ov) gives you a std::optional<std::vector<int>>&& and calling * on that calls conste...
72,088,896
72,088,994
C++: For two different functions with do-while loops, why does x+=y give the same result as x=x+y in one function but not the other?
For function A below, I get a different result when I use est += XXX as compared to using est = est + XXX. The former gives a result of 1.33227e-15 while the latter gives a result of 8.88178e-16. On the other hand, for function B below, I get the same result regardless of whether I use est += XXX or est = est + XXX. Wo...
x += y - z is the equivalent to x = x + ( y - z ). You likely wrote x = x + y - z. You need to enforce precedence. See here that with the brackets, the return values are the same. In your case, you want: est = est + ( ( 16 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/5, 2*counter+1) - ( 4 * pow(-1,c...
72,089,029
72,092,221
Difference between a destructor in Python vs C++
How do the contracts of a C++ destructor and a Python destructor differ, especially relating to object lifecycle and when resources are reclaimed? I haven't found a comprehensive side-by-side comparison. What I think a C++ destructor does is that it entirely frees the memory held by the object. And Python deregisters t...
Liftime of a C++ object begins with its construction, and ends with its destruction. C++ assumes a system with limited amount of resources; Resource Aquisition Is Initialization. That just means every aquired resource is bound to an object and must be freed before the objects lifetime ends: the destructor is supposed t...
72,089,764
72,089,841
How to proper set up a destructor in C++ with Xcode?
there is something that has been bugging me for a while. I cannot create a destructor using Xcode (with other IDEs like VS2021 that is no issue). I get the error: 1. Constructor cannot be redeclared 2. Missing return type for function '˜Pointer'; did you mean the constructor name 'Pointer'? If I try to declare outside...
Solved thanks to user4581301: For those having the same problem I did. The issue here was the similarity between ˜ and ~ The correct one should be ~ If you are using MacBook Pro the short-key is Option-N.
72,090,121
72,090,482
How does Hoare partitioning work in QuickSort?
Here is the pseudocode straight from the book (CORMEN): Partition(A,p,r) x=A[p] i=p-1 j=r+1 while(TRUE) repeat j=j-1 until A[j]<=x repeat i=i+1 until A[i]>=x if i<j SWAP A[i] <=> ...
With Hoare partition the pivot and values equal to the pivot can end up anywhere. The returned index is not an index to the pivot, but just a separator. For the code above, when partition is done, then elements <= pivot will be at or to the left of j, and elements >= pivot will be to the right of j. After doing a parti...
72,090,297
72,090,874
Maximum sum subarray, C++, DSA
I had tried to write a program to find the maximum sum subarray, I am able to take the output correctly in a certain scenario but if I want to change it the output is not as desired. So anyone can help me? #include<iostream> using namespace std; int main(){ int minValue,n; int a[n]={4,-2,-3,4,-1,-2,1,5,-3};...
Here I made 2 changes: Used INT_MIN Used vector instead of array definition. #include<iostream> using namespace std; int main() { vector<int> a ={4,-2,-3,4,-1,-2,1,5,-3}; // <------------ here int minValue=INT_MIN, n= a.size(); // <--------- here int max_so_far = minValue; int max_ending_he...
72,090,569
72,094,168
Adding ACE+TAO with numerous compile errors
I am adding ACE TAO to my existing project, and I have compile errors after adding the projects. Most of the errors were "No such file or directory", and these errors can simply be fixed by changing the patch of the #include, but there are thousands of them, and I am thinking I must have done something wrong on my end....
For "No such file or directory" you should add the file path: Open the project's Property Pages dialog box. Select the Configuration Properties > C/C++ > General property page. Modify the Additional Include Directories property. Since you have other errors, I guess you may not have installed the Windows SDK for the ...
72,090,624
72,091,050
How to properly cleanup after google mock objects when calling exit(0)?
According to https://learn.microsoft.com/en-us/cpp/cpp/program-termination?view=msvc-170#exit-function, "Issuing a return statement from the main function is equivalent to calling the exit function with the return value as its argument.". Yet this proves to be wrong as the following example demonstrates: main.cpp #incl...
That seems like an information specific to MSVC compiler only. cppreference on std::exit says: Stack is not unwound: destructors of variables with automatic storage duration are not called. For comparison, a moment later returning from main is mentioned: Returning from the main function, either by a return statement...
72,092,205
72,092,427
googletest - mocking abstract class
I am learning mocking and using googletest I created MockServer class that should mock the abstract class IServer: class IServer { virtual void writeData(QString buffer) = 0; virtual QByteArray readData() = 0; protected: virtual ~IServer() = default; }; class MockServer: public:: testing:: Test, publi...
You are confusing a few things: You are using a test fixture, but a test fixture needs to be a standalone class. You are mixing it with your mock class. You need to create a separate class for it. The Car class should take a parameter of type mock class (not the test fixture). .Return should be used inside WillOnce ...
72,093,848
72,234,350
Is there a direct way to get clear details on gcc acceptable option values (e.g. for -std) without grep-ing through irrelevant material?
The gcc (or g++) compiler has a -std option to specify the language standard to use for compiling C or C++. At the top level one can see that this option exists. gcc --help -std=<standard> Assume that the input sources are for <standard> However, different versions of the gcc compilers will have a different s...
Sadly, it seems that no one knows of a feature in gcc itself that would provide what I was seeking, i.e. a direct way to use gcc --help to get the detailed information about a particular option for that version of gcc. I appreciate the comments by RetiredNinja that fall back on the web documentation. Even though that ...
72,094,435
72,095,485
Find the Longest Common starting substring of S2 in S1
I was solving a problem. i solved the Longest Common starting substring of S2 in S1 part but the time complexity was very high. In the below Code I have to find the Longest Common starting substring of str3 in s[i]. In the below code instead of find function i have also use KMP algorithm but i faced high time complexi...
Here is a solution that emits the faint aroma of a hack. Suppose s1 = 'snowballing' s2 = 'baller' Then form the string s = s2 + '|' + s1 #=> 'baller|snowballing' where the pipe ('|') can be any character that is not in either string. (If in doubt, one could use, say, "\x00".) We may then match s against the regular...
72,094,764
72,094,944
Most performant way to verify an element exists in a given set in C++
I've been trying to write a code that finds all the numbers which summed to its inverted counterpart would result in an odd number, as for "12 + 21 = 33", "605839 + 938506 = 1544345", and so on and so forth... I've reached the problem of accessing the values of a given unordered_set and checking if a value is within it...
As @JaMiT recognized, it's not the set that's the problem; it's the potentially unterminated C string. If you invert into another std::string, which knows its length, you won't run into that problem: string invertSequence(string sequence) { string inverted(' ', sequence.size()); for (int i = 0; i < sequence.length...
72,095,007
72,095,093
Undefined behaviour of delete operator
I am relatively new to C++ and I'm learning about pointers. I was trying to dynamically allocate some memory for an array and found this issue. Here is my code, #include <iostream> int main(){ int n = 5; int *arr = new int(n*(sizeof(int))); for(int i=0; i<n; i++) *(arr+i) = i+1; delete[] arr;...
In the small piece of code there are multiple errors and problems: The expression new int(n*(sizeof(int))) allocates a single int value and initializes it to the value n*(sizeof(int)). If you want to allocate space for an array of int values you need to use new[], as in new int[n] Because of the above problem, you wi...
72,095,192
72,095,234
use std::for_each with bind a member function on a std::set , the code can't be compile
I can compile normal,when I use vector: TEST(function_obj,bindMemeber1){ std::vector<Person> v {234,234,1241,1241,213,124,152,421}; std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) ); } but when I use set,something wrong: TEST(function_obj,bindMemeber1){ std::set<Person,Per...
Elements got from std::set are const-qualified; they're supposed to be non-modifiable. You should mark Person::print as const then it could be called on a const object. class Person { ... void print() const { // ^^^^^ std::cout<<no<<' '; } ... }; BTW: Better to mark operator() in ...
72,095,232
72,097,188
Cannot find source file: /home/tensorflow/core/util/stats_calculator.cc
I'm new to CMake and ROS. I've been following the tutorial on setting up tensorflow on ubuntu 20.0.4 (server) and rpi4, as well as building tensorflow lite with CMake for my turtlebot3 project. I added the following code to my CMakeLists.txt and modified my tensorflow source directory from "${TENSORFLOW_SOURCE_DIR}/ten...
As stated in your code, directory TENSORFLOW_SOURCE_DIR contains the TensorFlow project. In other words, content of this directory should look like that: https://github.com/tensorflow/tensorflow. And path to the tensorflow-lite should be exactly as written in the tutorial: ${TENSORFLOW_SOURCE_DIR}/tensorflow/lite If e...
72,095,414
72,095,558
Supersede c++ library printed lines
I have a c++ application, where I link my main.cpp with some pre-built libraries (.a files, I dont know their internal details). The main program looks something like this: int main() { printf("..this is my part of the code.\n"); // other code here } Then when I run my application, it produces the following ou...
As everyone has said in the comments, initializer code for statics and globals is executed before main(), and if this code prints a message, you cannot have something in main() supersede it. Suppose your main program is in main.cc, as you have it, and the library has a single file, thing.cc, like this: #include <iostre...
72,095,907
72,096,055
Is it possible to replace member function to a noop function?
I write c++ with c++11 and have a question as title. Ex. class Hi { public: Hi(){}; test() {cout << "test" << endl;}; } void noop(){ ; // noop }; int main(){ Hi hi(); hi.test = noop; // just example, not real case return 0; } Is that possible to replace test() of class Hi to a noop function in runtime!? Thanks.
You can't replace any function at runtime, whether class member or not. However, you can achieve the desired effect by using a variable. (This is yet another example of the "add a level of indirection" method of solving problems.) Example: class Hi { public: Hi(): test([this]() { do_test(); }) {} std::function<...
72,096,254
72,096,910
returning an array in C++ with templates
I have the following code, where the kronecker product of 2 arrays is computed. In this code I want to return the array C which is the kronecker product of the two arrays back to the main function. I have tried pointers instead of void but I am not able to do it. Also I want tje function to compute the kroecker product...
To return an array from a function, you must dynamically allocate it first. This is necessary as the array declared in the function statically is cleared after the function finishes its execution. To create an array of dimension m x n you can do something like this: int** c = new int*[m]; for (int i = 0; i < m; i++) {...
72,096,295
72,130,330
C++ google test, mocks not called on inherited classes
As said in the title, I try to test my code using google test, but I get some issue on inheritance of mocks. I will further present the structure of my code: file1.hpp struct A: virtual public testing::Test { //function with MocksA }; file2.hpp struct B: virtual public testing::Test { //function with MockB }; ...
The solution was to add EXPECT_CALLS in the 3rd file, not using the ones from file1 & file2
72,096,386
72,096,524
c++ precompiled headers vs. modules
I'm confused on the difference between precompiled headers and modules. What advantage does one have over the other? I've read the Microsoft documentation on both of them but it hasn't helped me much. Precompiled headers Modules
An advantage of modules is that they are a standard feature. All C++20 compilers must implement them as described in the language. Precompiled headers are not a standard feature. Not all compilers necessarily have that feature, and each compiler that has, implements them in their own way that isn't necessarily compatib...
72,096,817
72,376,393
Sending and receiving integers array by Linux socket
I am trying to pass an array of integers (file descriptors) via linux socket using C++. I used cmgs(3) and seccomp_unotify(2) to write the following send and receive functions: send: static bool send_fds(int socket) // send array of fds by socket { int myfds[] = {568, 519, 562, 572, 569 ,566}; //static values for te...
From Cloudflare blog: Technically you do not send “file descriptors”. The “file descriptors” you handle in the code are simply indices into the processes' local file descriptor table, which in turn points into the OS' open file table, that finally points to the vnode representing the file. Thus the “file descriptor” ...
72,096,849
72,100,148
How to create a portable C/C++ program on linux using additional libraries?
I need to create a portable linux program that uses a lot of additional libraries defined from yum (CentOS). It is forbidden to install new packages on portable machines. There are no necessary libraries there. How to assemble my program and all packages into a single folder through the gcc compiler? When I move this f...
This sounds like a doomed project, for anything non-trivial. Static libraries are not the issue though. Since they're just collections of .o files, you can unpack them. You can then state that you have just linked object files. Stupid rules give stupid results. I am ignoring software licensing here, though, but that se...
72,096,878
72,097,727
How can i call the parameterized constructor for all objects in my dynamic array of objects on allocation in c++?
When i define dynamic array of objects, i want to choose one parameterized constructor for all objects in my array. without having to write for each object the chosen constructor like this #include <iostream> using namespace std; class foo { public: foo () { cout << "default constructor" << endl; ...
The simplest solution to this problem would be to use std::vector which handles all those problems internally, e.g.: #include <vector> // skipping class declaration for brevity int main (void) { int size = 3, parameter = 10; std::vector<foo> array; array.reserve(size); cout << endl; for (int i = 0...
72,096,928
72,097,166
Is int byte size fixed or it occupy it accordingly in C/C++?
I have seen some program that use int instead of other type like int16_t or uint8_t even though there is no need to use int let me give an example, when you assign 9 to an int, i know that 9 takes only 1 byte to store, so is other 3 bytes free to use or are they occupied? all i'm saying is, does int always takes 4-byte...
The size of all types is constant. The value that you store in an integer has no effect on the size of the type. If you store a positive value smaller than maximum value representable by a single byte, then the more significant bytes (if any) will contain a zero value. The size of int is not necessarily 4 bytes. The by...
72,096,954
72,098,408
Does Eigen have arange function like numpy.arange() in Python
Do you know if Eigen has its own arange function, and if not, why? For now, I have written my own arange function using Eigen::VectorXd::LinSpaced() /* * Return evenly spaced values within a given interval. * Values are generated within the half-open interval [start, stop) * (in other words, the interval including s...
There is indeed LinSpaced currently available for such an operation, but apparently no direct equivalent of arange in Eigen. There are working notes related to this (eg. range and iota) but so far nothing appear to be included in the code for that. In the new Eigen 3.4 with a recent C++ version, you can use std::iota s...
72,097,177
72,106,908
Getting an unsupported media type error while having a json object posted and content-type set to application/json
I'm doing a small test projet, the goal is to log throught Keycloak API and get my access token. The problem i'm facing is that i got a 415 error "unsupported media type" as the following : HTTP error I've tried content type header as text/plain application/x-www-form-urlencoded application/json Here is my code : voi...
Try something like. Edit: add this note for clarity. "The protocol/openid-connect/token endpoint expects form encoded body, not a JSON body." req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QUrl body; body.addQueryItem("client_id","demo-client"); . . . networkManager->post(req,...
72,097,439
72,097,476
c++ converting const char* to char* for long buffer
I have an old function which I can't change the API void TraceMsg(const char* fmt, ...) { if (!m_MessageFunctions[TraceLevel]) return; char msgBuffer[MAX_LOG_MSG]; va_list argList; va_start(argList, fmt); vsnprintf(msgBuffer, MAX_LOG_MSG, fmt, argList); va_end(argList); m_MessageFunctions[...
The return value of vsnprintf is The number of characters that would have been written if n had been sufficiently large, not counting the terminating null character. So you need to add 1 to this to make room for the null terminator.
72,097,526
72,100,357
How to calculate a polynomial using matrix calculation with Eigen
I want to calculate a polynomial using matrix calculation and not for loops. Theory The equation of a polynomial of degree k: a: Coeficients of the polynomial t: X value v: Y value to calculate We can calutate all Y values for n X values with this matrix calculation: Question I have all coeficients. I have a vecto...
The usual approach to evaluate polynomials would be Horner's method. This avoids any complex functions (such as pow) , is fast and numerically stable. A version in Eigen could look something like this: /** Coefficients ordered from highest to lowest */ Eigen::VectorXd evaluate_poly( const Eigen::Ref<const Eigen::...
72,098,003
72,098,106
Does operator of `[]` of std::map always put the new item into the first place of iterator?
Hi I've met a problem relating to iterator order of inserted values in std::map by operator []. The code is a github program in line 265: many_async_rules[rstval].insert(sync_level); The definition of the map is std::map<RTLIL::SigSpec, std::set<RTLIL::SyncRule*>> many_async_rules; By testing cases and guessing its mea...
Elements of std::map are stored in order of the key established by the Compare predicate that was provided to the map (by default, std::less). If rstval is the least key according to the predicate, then it will be the first element. If rstval is the greatest key according to the predicate, then it will be the last elem...
72,098,313
72,098,358
Why am I getting an error on the makefile.win? (dev c++ 6.3)
I am using C++, I'm quite new to programming and wanted to try out some things. I have been smooth sailing until I reached multifile programming.. I tried putting all the contents of the 3 files into a single cpp file and it works: #include <iostream> using namespace std; const int numOf_people = 4; struct person { ...
The error is that you define the variable individual in the header file: struct person { std::string name; } individual[4]; That means the variable will defined in each translation unit where the header file was included, and C++ only allows variables (and functions) to be defined once. I suggest you split these i...
72,098,319
72,098,470
CMake string replace removes semi-colon
I have a template cpp file that will contain several placeholders. Excerpt: // WARNING! this file is autogenerated, do not edit manually QString appName() { return "APP_NAME_VALUE"; } Cmake will read this file in, fill in the placeholders and write it back out to the shadow build directory for compilation set(APP_NA...
From https://discourse.cmake.org/t/what-is-the-best-way-to-search-and-replace-strings-in-a-file/1879 In my CMake script, I need to modify other source files by searching and replacing specified strings. In my case, the configure_file 2 command is not a solution because I have no control over the input file. Previously...
72,098,438
72,098,910
How can a reference be present in a signature of a function callable from C code?
I'm a bit confused: I have a C++ API which is supposed to be called from C code and uses __cdecl in the function declarations. There's a vtable with function pointers like this: void (__cdecl *funptr) (const MyStruct& obj); references are a C++ construct, are they not? How can there be a __cdecl with references? And f...
These are apples and oranges. __cdecl is a non-standard keyword used to describe one of the more common x86 ABI calling conventions (together with __stdcall) which specifies how variables are passed/stacked between caller and callee. It has nothing to do with C specifically - some historic Microsoft C compiler just use...
72,098,489
72,098,566
Preprocessor directives in C++
I have read several articles about how Preprocessor directives work in C++. It's clear to me that Preprocessor directives are managed by the pre-processor before compilation phase. Let's consider this code: #include <iostream> #ifndef N #define N 10 #endif int main(){ int v[N]; return 0; } The Pre-processor will ela...
For the sake of illustration I removed the includes from your code: #ifndef INT_MIN #define INT_MIN 0 #endif int get_max(){ return 5; } #ifndef INT_MAX #define INT_MAX get_max() #endif int main() { return INT_MIN + INT_MAX; } Then I invoked gcc with -E to see the output after preprocessing: int get_max(){ ...
72,098,883
72,099,197
Can't deserialise from Json using nlohman json using custom class with private members
Really struggling to do this; it should be really simple, but I can't work out how. I've got it working for struct, but not for a class with private members. Following instructions from (https://github.com/nlohmann/json). I'm building this on Visual Studio 2019 and obtained the library from nuget, version 3.10.4. The e...
The problem is that your address1 type does not have a default constructor. From https://nlohmann.github.io/json/features/arbitrary_types/#basic-usage : When using get<your_type>(), your_type MUST be DefaultConstructible. (There is a way to bypass this requirement described later.) If I add address1() = default; to y...
72,099,169
72,099,249
What is lower_bound(B,B+N,goal) - B in C++
When I see some code I found lower_bound function which execute binary search. it is used like following. int pos1 = lower_bound(B, B + N, goal) - B; I understand that lower_bound returns iterators , but what is the role of -B in this sample. I totally confused about this, if someone has opinion will you please let me...
As mentioned in a comment, it calculates the difference between the iterator returned from lower_bound and B. pos can then be used as index to B: B[pos]. A cleaner way to get the distance between two iterators is using std::distance: auto it = std::lower_bound(....); auto offset = std::distance(B,it); However, there...
72,099,896
72,099,993
Use of deleted function when using fstream
I'm receiving the message "Use of deleted function" when I combine the use of an ofstream (which I later want to use to record information) and the placement of one class inside another. Here is my minimal example: #include <iostream> #include <unistd.h> #include <fstream> class Tracker { private: std::ofs...
In this line in the ctor of Penguin: ) : p_tracker(p_tracker) {} You attempt to initalize the Tracker p_tracker data member. Since you pass it an existing Tracker instance, it attempts to use the copy constuctor. But class Tracker does not have a copy constructor. This is the "deleted function" mentioned in the error ...
72,100,006
72,100,050
why non-movable Object still a copy
Consider the following code, Entity object is non-movable. I know that std::move(Obj) just cast the Obj to a rvalue reference Obj. And I also know that rvalue reference variable is still a lvalue object. But I still confusing why statement auto temp = std::move(a) can call copy constructor, statement a = std::move(b);...
Entity object is non-movable No. Even it doesn't have move constructor/assignment-operator, it has copy constructor/assignment-operator taking lvalue-reference to const. std::move(a) and std::move(b) are rvalue (xvalue) expressions and they could be bound to lvalue-reference to const. You might also check std::is_mov...
72,100,278
72,100,505
Boost Asio J1939 / Can-bus Multithreading
I am implementing a J1939 socket handler on top of Boost::ASIO and canary. My previous application had a socket to listen for devices and the each device discovered would also have a socket. Each socket would use the same interface (In this case can0). From my understanding of SocketCan and J1939 this is the correct ap...
Yes there is synchronization in the kernel. The same happens for example with TCP sockets. They also share a single network interface (like eth0). The linux network subsystem makes sure, that different sockets (used by different threads or even processes) can share one interface without colliding. You only need synchro...
72,100,304
72,100,448
I want to get an LED to blink using the millis() function but my LED stays constantly on, what's wrong with my code?
I know there are other ways but I'd like to know what's wrong with my code and why it doesn't work. Pin 2 seems to constantly stay 'HIGH' despite the 'else if' statement. const int led = 2; int ledState = digitalRead(led); const unsigned long interval = 1000; unsigned long previousTime = 0; void setup() { Serial.b...
The first comment said you did not update ledState. This is the problem. I believe a better solution to that is the following: const int led = 2; const unsigned long interval = 1000; unsigned long previousTime = 0; void setup() { Serial.begin(9600); pinMode(led,OUTPUT); } void loop() { unsigned long current = ...
72,100,341
72,100,607
Is it valid to call operator-- for an iterator when it points to std::begin()
Is it valid to call operator-- on an iterator that already points to the first element of the collection? Does the answer change for different collections (e.g. list vs vector vs set). E.g. see below #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> int main() { std::...
Let's take std::list as an example, because essentially the same reasoning will apply to the other containers. Looking at the member types of std::list, we see that std::list::iterator is a LegacyBidirectionalIterator. Checking the description there, we see the following precondition listed for operator-- to be valid: ...
72,100,483
72,193,004
Matrix multiplication of an Eigen Matrix for a subset of columns
What is the fastest method for matrix multiplication of an Eigen::Matrix over a random set of column indices? Eigen::MatrixXd mat = Eigen::MatrixXd::Random(100, 1000); // vector of random indices (linspaced here for brevity) Eigen::VectorXi idx = VectorXi::LinSpaced(8,1000,9); I'm using RcppEigen and R, which is still...
Exploiting symmetry You can exploit that the resulting matrix will be symmetric like so: Mat sub_mat = subset_cols(mat, idx); // From your original post Mat a = Mat::Zero(numRows, numRows); a.selfadjointView<Eigen::Lower>().rankUpdate(sub_mat); // (1) a.triangularView<Eigen::Upper>() = a.transpose(); // (2) Line (1) w...
72,100,838
72,100,984
Is there any standard functionality for creating a flattened view of a map with a container as the mapped_type?
Is there any standard functionality to create a range/view over all pairs? The following code illustrates the view I am looking to create: std::unordered_map<std::string, std::vector<int>> m{{"Foo", {1,2}}, {"Hello", {4,5}}}; auto view = ???; std::vector<std::pair<std::string, int>> v{view.begin(), view.end()}; std::v...
Yes, combine std::ranges::views::join with std::ranges::views::transform and some lambdas. using namespace std::ranges::views; auto to_pairs = [](auto & pair){ auto to_pair = [&key=pair.first](auto & value){ return std::pair{ key, value }; }; return pair.second | transform(to_pair); }; auto view = m | transfo...
72,101,010
72,101,725
replacing macro with a function causes "signed/unsigned mismatch" warning
For this snippet const std::vector<int> v; if (v.size() != 1) {} // could call operator!=() the code complies cleanly even at high warnings levels (all warnings enabled in Visual Studio 2022). However, if I pass the arguments to a function const auto f = [](auto&& lhs, auto&& rhs) { if (lhs != rhs) {}}; f...
Move the problem out of your code by calling std::cmp_not_equal const auto f = [](auto&& lhs, auto&& rhs) { if (std::cmp_not_equal(lhs, rhs)) { blah blah } }; This family of functions, added in C++20, is defined in a way that properly compares integer arguments even in the presence of a signed/unsigned mismatch. ...
72,101,735
72,101,864
Array of different data types
I need to store an array of newspapers and booklets And then in a loop, print out how much paper it takes to print each product, but when I call the price calculation function, the function is called from the main class and not from the child ones, how can I call the function from the child classes in an array with dif...
I need to store an array of newspapers and booklets This isn't possible. Arrays can only contain objects of one type. In case of new PrintedProduct[size] that array contains objects of type PrintedProduct. The elements of the array are not instances of classes derived from PrintedProduct. The solution to this is to u...
72,101,801
72,102,272
'Clang-Tidy: Do not implicitly decay an array into a pointer' when using std::forward and const char*
I do not understand why Clang-Tidy produces the error Clang-Tidy: Do not implicitly decay an array into a pointer in the following example: struct Foo { explicit Foo(std::string _identifier) : identifier(std::move(_identifier)) {} std::string identifier; }; struct Bar { template<typename... Ts> explicit Bar(...
This looks like a bogus diagnostic. I would disable it globally, since this usecase is so common.
72,101,936
72,104,249
QImage 16 bit grayscale with QQuickPaintedItem
I have unsigned 16 bit image data that I displayed by subclassing QQuickPaintedItem in Qt 5.12.3. I used QImage with Format_RGB32 and scaled the data from [0, 16383] to [0, 255] and set that as the color value for all three R,G,B. Now, I am using Qt 5.15.2 which has a QImage FORMAT_GrayScale16 that I'd like to use but ...
This worked for me (below is just fragments): class Widget : public QWidget { private: QImage m_image; QImage m_newImage; QGraphicsScene *m_scene; QPixmap m_pixmap; }; ... m_image.load("your/file/path/here"); m_newImage = m_image.convertToFormat(QImage::Format_Grayscale8); m_pixmap.convertFromImage(m_n...
72,101,951
72,103,495
Win32 Get unscaled Virtual Desktop size in C++
Working on a C++ application, trying to map the mouse from the coordinates to the full screen windows. Getting the mouse coordinates with GetPhysicalCursorPos(&mouse_point); which returns the coordinates relative to the origin 0,0. This is causing issues because the mouse is going "out of bounds" of the monitors becaus...
Thanks to @RaymondChen I was able to fix it by calling SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); prior to GetSystemMetricsForDpi. It now returns the full virtual desktop size.
72,101,958
72,102,091
Relationships between VS ans MSVC version
I can't make up a puzzle. I meet names like Visual C++15 (here for example: https://www.sfml-dev.org/download/sfml/2.5.1/). But other sources say that the last version to the moment is 14.31 (wikipedia stays with them: https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B). It's also gets challenging for me at the mom...
The Visual C++15, that you mention here, is in fact Visual Studio version 15(aka Visual Studio 2017). It isn't a compiler version but in fact a version of the IDE. There is no relation with VS versions directly with C++ standards. But it's more like, some versions of C++ can only be supported on the latest VS version...
72,102,506
72,103,317
Dynamically allocate ragged matrix
I'm trying to make a generic function which will dynamically allocate 2D structure. Number of elements in every row doesn't have to be same for all rows. Structure is represented as a container type, whose elements are again of a container type (for example a set of lists). The type of elements of that inner container ...
Here's one way to accomplish what you want: #include <iterator> #include <type_traits> template <typename tip> auto Make2DStructure(tip&& mat) { // create an alias for the value type: using value_type = std::decay_t<decltype(*std::begin(*std::begin(mat)))>; // allocate memory for the return value, the poi...
72,102,530
72,102,597
Can the compiler generates a default copy constructor that takes reference to different class type?
I have this example struct B { B(); }; struct D : B { }; D d{ B() }; // what happens here? or why it's well-formed This is an aggregate initialization, but I can't understand how d is constructed? Does the compiler generates implicitly a copy constructor with this signature D::D(const D&) or D::D(const B&) or what? It...
Can the compiler generates a default copy constructor that takes reference to different class type? By definition, no. A constructor that accepts an object of another type is not a copy constructor. It would be a converting constructor. No such converting constructor is implicitly generated. This is an aggregate ini...
72,103,012
72,103,152
Is it safe to pass a uint64_t containing a 32-bit value to an external function whose parameter is actually a uint32_t?
I'm working on a cross-platform program that calls a function from a dynamic library with C linkage. I need to support multiple versions of this dynamic library, but between two of the versions I need to support, there is a function parameter that has changed from uint32_t to uint64_t. If I pass this function a uint64_...
No, this is illegal. C++20 [basic.link] p11: After all adjustments of types (during which typedefs (9.2.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical. Moreover, it will actually fail on 32-bit x86 systems using the usual st...
72,103,570
72,105,010
SIMD - how to add corresponding values from 2 vectors of different element widths (char or uint8_t adding to int)
Please tell me how can add values from a SIMD vector of the same type, but the values themselves, which are occupied by a different number of bytes in these SIMD vectors. Here's an example: int main() { //-------------------------------------------------------------- int my_int_sequence[16] = { 0,1,2,3,4,5,6,7,...
Perhaps I need each byte of the vector my_char_mask_my_m128i - how to transform it into 4 bytes? You're looking for the SSE4.1 intrinsic _mm_cvtepi8_epi32(), which takes the first 4 (signed) 8-bit integers in the SSE vector and sign-extends them into 32-bit integers. Combine that with some shifting to move the next 4...
72,103,700
72,103,827
enable_if for class template specialization with argument other than void
I know that a C++ compiler picks a template specialization in preference to the primary template: template<class T, class Enable = void> class A {}; // primary template template<class T> class A<T, std::enable_if_t<std::is_floating_point_v<T>, void>> { }; // specialization for floating point types However, I don't un...
Specializations are irrelevant until the compiler knows which types it is going to use for the primary template. When you write A<double>, then the compiler looks only at the primary template and sees that you actually mean A<double,void>. And only then it is looking for specializations. Now, when your specialization i...
72,103,800
72,108,937
Lifetime of std::initializer_list when used recursively
I am trying to use std::initializer_list in order to define and output recursive data-structures. In the example below I am dealing with a list where each element can either be an integer or another instance of this same type of list. I do this with an intermediate variant type which can either be an initializer list o...
As far as I can tell the program has undefined behavior. The member declaration std::initializer_list<wrapped> lst; requires the type to be complete and hence will implicitly instantiate std::initializer_list<wrapped>. At this point wrapped is an incomplete type. According to [res.on.functions]/2.5, if no specific exce...
72,104,337
72,104,542
signal SIGSEGV, Segmentation fault. __strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:65
I have converted my old code: #define MAX_LOG_MSG 2048 in the *.h file typedef void (*LogMessageFunction)(char *); in the *.cpp file static LogMessageFunction m_MessageFunctions[LastLogCount] = {NULL}; void DebugMsg(const char* fmt, ...) { if (!m_MessageFunctions[DebugLevel]) return; char msgBuffer[MAX_LOG_...
I'd make a variadic template out of it instead and use a std::unique_ptr<char[]> for the memory allocation: #include <memory> template<class... Args> void DebugMsg(const char* fmt, Args&&... args) { if (!m_MessageFunctions[DebugLevel]) return; int size = std::snprintf(nullptr, 0, fmt, args...) + 1; if (si...
72,104,603
72,104,710
Assigning function to function pointer with template parameter
So I have these two functions: bool intComp(int a, int b) { return a > b; } bool stringComp(std::string a, std::string b) { return strcmp(a.c_str(), b.c_str()) > 0; } And in my sort function I want to assign either the stringComp or intComp function: template<typename T> void sort(std::vector<T>& vector) { ...
The problem is that all branches of a normal if need to be valid at compile time, but only one of the branches in yours is. If T is int, then compare = &stringComp is invalid. If T is std::string, then compare = &intComp is invalid. Instead, you need if constexpr, which was introduced in C++17 and does its comparison...
72,104,705
72,104,751
I can't use accents with string in C++
I can set the accents with SetConsoleOutputCP(1252) or locale::global(locale"FR-fr"), but I can't use it with strings. Seems like it's one or the other. I can output text with accents, or I can output the string with accents, not both. Any ideas? The code below can be used to reproduce the problem. Simply add locale::g...
I suggest that you set both the input and output code pages: SetConsoleCP(1252); // input SetConsoleOutputCP(1252); // output
72,104,836
72,105,217
Can WebView2 Navigate to an html resource embedded in the application?
I've been converting our application from using CHtmlView over to WebView2. Our application has a web-based start page that generally gets all its information from our servers, but we have local resources setup in the event of our servers being down or the client having internet trouble. Using CHtmlView we were able t...
WebView2 does not support the res URI scheme. For serving app content that is not on the disk, you can use: NavigateToString: You can provide app created HTML to render, however there is no way to additionally reference subresources that are dynamically app created. WebResourceRequested: You can use the CoreWebView2.W...
72,105,092
72,105,136
Virtual methods and overriding
What am I doing? I'm trying to do some basic inheritance for the game I'm working on. The idea is to have a base Entity class that the Player will inherit from. The Entity class has a virtual update or think method that each child will override to fit it's needs. This is how the engine handles the update loop: void Eng...
Change this: void Engine::update() { for (Entity entity : entities) { entity.update(deltaTime); } } To this: void Engine::update() { for (Entity& entity : entities) { entity.update(deltaTime); } } In the original implementation, your for loop makes a copy of the item in entities. You probably didn't w...
72,105,162
72,105,271
C++ Copy Map to Vector Templated
I have the following: template<typename MapT> std::vector<int> mapToVec(const MapT &_map) { std::vector<int> values; for(const auto &entry : _map) { values.push_back(entry.second); } return values; } Obviously this only works if the value type of the map is an int. How do I template this further t...
You can use typename MapT::mapped_type as the std::vector::value_type, eg: template<typename MapT> std::vector<typename MapT::mapped_type> mapToVec(const MapT &_map) { std::vector<typename MapT::mapped_type> values; values.reserve(_map.size()); for(const auto &entry : _map) { values.push_back(entry.se...
72,105,527
72,132,277
Linking C++ code to a DYLIB library in macOS
I was able to setup BlockSci on macOS v10.13 (High Sierra) 10.13.6. The setup installed header files in /usr/local/include and a libblocksci.dylib in /usr/local/lib. The C++ code I am trying to compile is: #include "blocksci.hpp" #include <iostream> #include <string> int main(int argc, const char * argv[]) { block...
I found this and this that were helpful. It finally compiled with: g++ hello.cpp -std=c++17 -I/usr/local/include/blocksci/external -o hello -L/usr/local/lib -lblocksci -Wl,-rpath,/usr/local/lib However, now I get a runtime error: libc++abi.dylib: terminating with uncaught exception of type std::runtime_error Abort tra...
72,105,682
72,108,027
How do you tell C++ to use a specific file from a folder when you don't always know the exact path?
Note: I only know C in depth at the moment, but I am enrolled in a summer course starting soon on modern C++, so methods for C++20 would be extremely helpful as well. If this is a dumb question or was already asked (I didn't find anything from googling), then links would be helpful as well. Question: Okay, so say I am ...
Here’s a little helper module to get a path to a creatable/writable directory for saving your program data. appdata_path.hpp #ifndef APPDATA_PATH_HPP #define APPDATA_PATH_HPP #include <filesystem> #include <string> std::filesystem::path get_appdata_path( const std::string & application_name ); #endif appdata_path.c...