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
64,968,354
64,968,436
Why std::chrono::day stored value is unspecified if d > 255
Quoted from std::literals::chrono_literals::operator""d A std::chrono::day storing d. If d > 255, the stored value is unspecified. What is the rationale behind this limit ?
The literal can't store more than std::chrono::day itself can, which is 0-255. This allows it to be implemented as a 1 byte data type, which as it usually will only store values between 1 and 31 is sufficient. If you're looking for a data type to store a duration of an arbitrary number of days use std::chrono::days ins...
64,968,568
64,968,659
std::sample() returns the same elements every time
Code: #include <iostream> #include <random> #include <string> #include <iterator> #include <algorithm> int main() { std::string in = "hgfedcba"; for (int i = 0; i < 5; i++) { std::string out; std::sample(in.begin(), in.end(), std::back_inserter(out), 5, std::mt19937{std::ran...
Every time in your loop you are constructing a new random engine with a default random_device. The standard library allows implementations of random_device to generate the same sequence of values for every instance, so your code could produce the same results in every iteration. In other words, given the current specif...
64,968,683
64,969,948
Thread safe queue implementation : Efficient implementation of pop()
I am trying to implement thread safe version of queue and facing problem in implementing wrapper around pop(). Refer code below. Can't paste entire code due to restriction. bool internal_pop_front_no_lock(T& item) { bool isDataAvailable = false; if (!m_Queue.empty()) { item = m_Queue.front(); ...
There is only one way to avoid copying, if you move this object and then return it. Because even if you can access m_Queue.front() without copying, as soon as you do m_Queue.pop(); this object will be destroyed, and if you need access to this object beyond this point you need to either copy or move this object. So some...
64,968,939
64,969,691
Clang options in VS2019
I am trying the Clang-CL compiler built into VS2019 under Windows 10, but cannot see how to set the compiler options, in particular, long doubles of more than 64-bits. In the Project settings, the Platform Toolset is LLVM (clang-cl). Then in C/C++ > All Options > Additional Options I added -mlong-double-80 and compiled...
clang-cl is a compatibility layer for MS Visual Studio and offers only the features that are compatible with the vc142 toolset and the Win32 ecosystem, which does not support 80-bit double (source). Otherwise "Additional Options" is the correct place to add compiler options.
64,969,767
64,977,154
Deallocate part of array in CUDA
Say I have an array of numbers on device (CUDA), something like float *d_x; cudaMalloc(&x, N*sizeof(float)); Where x will be something like [0,0,3,0,3,0,3,1,5,1,0]. I am performing two operations on the array. The details are unimportant, but the first operation will act as a sort of preprocessing, permuting the value...
Is it a good idea to deallocate the part of the array that will no longer be used after operation1? It is not so much a "good" idea as a completely unsupported one. There is no realloc style operation in the CUDA APIs, and given the cost and synchronous nature of memory allocation on GPUs, not a good idea from a perf...
64,970,050
65,088,197
Operation chmod 0777 not permitted inside a running Docker container
I am trying to execute some unit testing for my C++ code inside a Docker container that calls the command: ... if (chmod("/tmp/ipc_unixdomain", 0777) != 0) { ... In my PC outside of the container, I am able to run this command in both the terminal and the C++ code, but once I move inside the container I am only able t...
Most likely you created the docker user in a wrong way, or used the wrong workspace. Try this Ubuntu-18.04 based Dockerfile as an example: FROM ubuntu:18.04 RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y g++ RUN useradd -ms /bin/bash newuser USER newuser WORKDIR /home/newuser COPY script.sh sc...
64,970,066
65,000,720
cc1plus.exe - Entry Point Not Found
I am trying to run a c++ program on windows 10 #include <iostream> int main() { std::cout << "Hello World!"; return 0; } when I try to run g++ hello.cpp The procedure entry point libiconv could not be located in dynamic link library C:\mingw\bin..\libexec\gcc\mingw32\6.3.0\cc1plus.exe I reinstalled MinGW but ...
MinGW GCC 6.3.0 is really very old. Try with a newer version like MinGW-w64 GCC 10.2.0 from http://winlibs.com/ The error The procedure entry point libiconv could not be located indicates there is an issue loading the libiconv DLL, possibly because it's loading the wrong DLL with the same name in a different location. ...
64,970,184
64,971,260
c++ how to make constructor for typedef type
In my c++ project I have a type called Expression typedef std::function<uint64_t(uint64_t)> Expression; I also have a function which acts like a constructor Expression ExpressionConstructor(std::string Expr, MicroCodeDescriptor* descriptor) { //implementation doesn't matter in this case } This code works, I can use t...
Instead of typedef your Expression could be a class derived from std::function<uint64_t(uint64_t)>. Then you can define its constructor(s), destructor and call it as a std::function: struct Expression : public std::function<uint64_t(uint64_t)> { Expression(std::string Expr, MicroCodeDescriptor* descriptor) { ...
64,970,247
65,016,130
bison 3.5.1 insists on explicitly writing code for default action assuming a C style union
The bison version I was using before (2.4.1) did not explicitly write the default action for every semantic rule which used it -- but probably simply assigned $$ with $1 once without regard to any types for all default action rules. bison 3.5.1 insists on dumping this out by himself -- assuming that the stack is made u...
This change, which I believe was introduced in v3.2, applies only to the C++ skeleton (which happens to be the one you are requesting, lalr1.cc.) As far as I know, there is no way to disable it. Although both yacc and bison describe $$ = $1 as the "default action", that's not really the case. The historic implementatio...
64,971,220
64,973,443
Greyed out code in VS Code C/C++ Extension
i'm trying to solve the following issue with VS Code and the C/C++ Extension from Microsoft. The mentioned Extension adds a reference count above every function/object definition in the source code. That's a helpful feature so far, but for me it doesn't work as intended I think. In my example I started implementing a t...
As I mentioned in the updated question, the problem isn't realted to the C/C++ Extension. It is acutally the TypeLens extension that causes problems here. The best solution I have found is to configure TypeLens to not grey out unreferenced code. This way I can keep the reference counter and the code completion feature ...
64,971,238
64,972,150
Why is the red light not lighting up?
So I am very new to this IoT stuff and what I am trying to create here is somewhat like traffic violation detection. My idea is: when the red light is on and if the PIR sensor detects movement, the buzzer/LED turns on. Here's the image: Here's what the code looks like: int pir = 2; int rojo = 12; int amarillo = 11; i...
The problem is here: digitalWrite(rojo, HIGH); //It turns on the red led delay(15000); //wait 15 seconds digitalWrite(rojo, LOW); if (rojo == HIGH) { if (val == HIGH) { digitalWrite(led, HIGH); } else { digitalWrite(led, LOW); } delay(10); } First of all, rojo is a pin number, ...
64,971,594
64,971,859
Why does dividing with arrays generate random number?
So, here's my code #include <conio.h> #include <iostream> #include <string> #include <iomanip> using namespace std; int main() { int n; int kw[10]; int discount[10]; int total[10]; int final[10]; cout << "insert amount of data = "; cin >> n; cout << endl; for (int i = 0; i < n; i++...
You calculate discount only if the user first enters wrong value for kw, and then enters the right one.
64,971,690
64,979,017
How do I download and install the Qt library?
I want to use the QDirIterator Class for a University Project in Visual Studio, but for some reason I just can't include it. I tried downloading the libary somewhere but couldn't find the right website, the QT website itself seems to be a messy jungle of paywalls. The error message Visual Studio gives me is 'cannot ope...
I feel your pain, the Qt website is very hard to navigate. This is how I installed it. Open this link and hit "qt-unified-windows-x86-online.exe." (or the correct one for your operating system). Open the file and follow the steps. I would actually recommend you find a simpler library for your single needs because AFAIK...
64,971,731
64,971,998
Overload shallow and deep copy constructor cpp
I am starting with C++ environment, I hope I didn't mess up a lot with the concepts here. I have one task where I need to create an object that has to be able to be copied in two ways, with a shallow copy and a deep copy. The object has to allow two types of copies. Either the object is shallow copied or deep copy depe...
You can use a tag on the copy constructor to indicate it is making a shallow copy. Note carefully that a shallow copy does not own the resources. So when the owner gets destructed, any shallow copy will have dangling pointers. That's a very fragile situation, and easily the source of bugs. An alternative solution is ...
64,971,831
64,972,033
How to read from - "unsigned char const *" when use Media Foundation?
I have such an implementation void coAudioPlayerSampleGrabber::test(SoundDataType dataType, unsigned char const * pData, int64_t dataLen) { HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0); IMFSourceReader *pReader = NULL; IMFByteStream * spByteStream = NULL; HRESULT hr = S...
You can't cut corners like this: unsigned char const * pData; ... hr = MFCreateMFByteStreamOnStreamEx((IUnknown*)pData, &spByteStream); IUnknown is not yet another fancy alias for a byte. You are supposed to literally supply interface pointer representing stream, as documented. Media Foundation does offer you means to...
64,972,148
64,992,082
c# string to c++ wstring using Encoding.Unicode.Getbytes()
So the issue is that when using c# the char is 4 bytes so "abc" is (65 0 66 0 67 0). When inputing that to a wstring in c++ thru sending it in a socket i get the following output a. How i am able to convert such a string to a c++ string?
I have been able to solve the issue by using a std::u16string. Here is some example code std::vector<char> data = { 65, 0, 66, 0, 67, 0 }; std::u16string string(&data[0], data.size() / 2); // now string should be encoded right
64,972,297
64,973,661
How to stitch an array of images into an MxN image collage
So I have an array of Mat objects (jpeg images) and I want to convert that into an MxN array so the final output would be an image made of all the input images from the array, put into the matrix from left to right, then from up to down. Suppose all input images are the same size, how do I do this in C++ using Opencv? ...
This should do it: #include <opencv2/opencv.hpp> cv::Mat imageCollage( std::vector<cv::Mat> & array_of_images, int M, int N ) { // All images should be the same size const cv::Size images_size = array_of_images[0].size(); // Create a black canvas cv::Mat image_collage( images_size.height * N, images_size.width...
64,972,740
64,972,997
C++ class specifier alignas option via template
Can C++ template parameters be used to control specifiers on the class itself to minimize some code duplication? For example: I have a class that I'd like to use both in a concurrent context (and container) with the alignas specifier, and also in a single-threaded context without the alignas specifier. The size of the ...
You can do it like this: template <size_t alignment = 0> class alignas(alignment) C { // ... }; Now C<> will have the default alignment for its definition (since alignas(0) is ignored) while you could use e.g. C<16> to force an alignment of 16.
64,973,089
64,973,236
iterator don't print all map in C++
Why last cicle in main doesn't print all map? #include <map> #include <iostream> using namespace std; class NAME { private: string name; public: NAME(string name) { this->name = name; } string getName() const { return name; } friend bool operator< (const NAME& n1, cons...
Two elements in the map are considered equivalent when !(a < b) && !(b < a) As your operator< returns false always, any two elements are considered equivalent. Note that your operator< must implement a strict weak ordering. Your return n1.getName() < n2.getName(); does that.
64,973,785
64,974,888
Qt/C++ How can I disconnect a QProgressDialog::canceled signal to its QProgressDialog::cancel slot?
I have a QProgressDialog and I would like to override its cancel() slot to change its behavior. Instead of closing the dialog, I would like to do some other operations and then close the dialog after a QThread to finish before closing the dialog. I tried to disconnect the canceled/cancel signal/slot couples and the rec...
I don't know your whole code, but according to the documentation, the idea is more or less the same you're saying: a slot to connect the signal QProgressDialog::canceled(). The following code is just an example but it's working. In this case, instead of using the own Qt property wasCanceled, it is used a boolean to con...
64,973,824
70,734,388
What are the trade-offs between "separating module interface/implementation unit in a different source file" and using "private module fragment"
On the surface, using private module fragment to separate interface and implementation looks superior over separating module interface and implementation unit in a different source file since you only have to manage single source file when using private module fragment. But is using private module fragment simply bette...
The tradeoff is pretty obvious based on the limitations. A private module fragment (PMF) can only appear in a primary module interface unit, and there can be no other module units that contribute to a module that has a PMF. This means that the primary downside of using a PMF is that you're restricted to putting everyth...
64,973,963
64,974,379
(BST) Error: No matching overloaded function found
I just started learning Binary Search Trees. I have been trying to fix a couple of errors since yesterday. I looked at the reference links but I can't figure out what I'm doing wrong. The example below was copied from one of the slideshows provided to us by the lecturer but when I run it, I get the following errors: C...
In template<class ItemType> struct TreeNode { ItemType info; ItemType* left; ItemType* right; }; left and right are pointers to the data being stored in the TreeNode, not pointers to TreeNodes. Instead use template<class ItemType> struct TreeNode { ItemType info; TreeNode* left; TreeNode* right...
64,974,072
64,974,184
Why do I need to specify the argument list for a class template in a function?
So I have this really simple code that I'm using to get the hang on templates #include <iostream> using namespace std; template <typename T, typename U, typename V> class Foo{ private: T x; U y; V z; public: Foo(T a, U b, V c){ this->x = a; this->y = b; this->z = c; } ...
You need to make operator<< a template as well, so it can match to an appropriate template instantiation for Foo: template<typename A, typename B, typename C> ostream& operator<<(ostream& os, const Foo<A, B, C> &foo){ os << foo.x << ", " << foo.y << ", " << foo.z; // Changed -> to ., since foo is a reference, not p...
64,974,137
64,974,473
Exception thrown at 0x0037A5C2 project.exe: 0xC0000005: Access violation writing location 0xDDDDDDDD at the end of the program
I have encountered this runtime exception at the very end of the program by simply creating an instance of the specified class, so I presume the issue lies with either the constructor, copy constructor, copy assignment operator or destructor. I have read up on and followed the rule of three to the extent of my limited ...
At a quick glance I would say the issue is in your setColumns and setCommandData functions. (I might of course be wrong, I did not try to run the code you presented nor the changes I made -- so there might also be a typo somewhere.) There you use memcpy to copy the strings into your class. However, internally a C++ str...
64,974,505
64,974,618
Having issues drawing 3D cube's edges with OpenGL 3
I'm trying to draw 3D cube's vertices (edges only) using OpenGL (4.3 core profile), I know the glPolygonMode function but I'd like not to draw the intermediate diagonal lines. I declare my vertices and my indices like so : struct Vertex { glm::vec3 pos; glm::vec3 color; glm::vec3 normal; glm::vec2 uv; }...
Your indices form GL_TRIANGLES primitives rather than GL_LINES primitives. See GL_LINES: Vertices 0 and 1 are considered a line. Vertices 2 and 3 are considered a line. And so on. The indices form the primitives. Change the indices: GLuint indices[] = { 0, 1, 1, 2, 2, 3, 3, 0, // Front 4, 5, 5, 6, 6, 7, 7, 4...
64,974,994
64,975,782
Why C++ function template contains return type in its signature
For the following code: template <typename T> auto fun() { return T{}; } template <typename T> T fun2() { return T{}; } int fun3() { return 0; } template <typename T> void fun4(T) {} int main() { fun<int>(); fun2<int>(); fun3(); fun4(3); } When using clang / GCC to compile, the output contains the ...
Function template overloading can meaningfully depend on the return type: template<class T> T get_pi() {return 3;} template<class T> std::enable_if<std::is_floating_point_v<T>,T> get_pi() {return 3.2;} // closer It is of course possible to call the float specialization of the first function template, if only by putti...
64,975,105
64,975,397
Class object cannot access its own private member?
So basically I have this piece of class that's causing some big issues: namespace container { template<typename T, std::size_t size> class Array { private: T m_array[size]; /* Note: All elements must be of the same type, aka the type used to declare the Array object */ public: // Needed to create subarray ...
A simpler example for the same issue is this: template <int x> struct Foo { template <int y> void foo(const Foo<y>& other) { value = other.value; } private: int value = 0; }; int main() { Foo<1> a; Foo<2> b; a.foo(b); // ERROR ! cannot acces private member } Here Foo...
64,975,330
64,976,293
trying to parallelize my code however when I run it, it never gives the correct output
I have a program that initializes a vector of 1,000,000 size and then finds all the prime numbers in it. The primes are stored in a new vector, I then iterate through that vector and try to find all of the happy numbers in it. I am trying to use task parallelism to split the work between 2 threads however I never retur...
vector<int> num(size); for (int i = start; i < start + size; i++) num[i] = i + 1; This is obviously wrong unless start is zero. In all other cases, num[i] causes out-of-bound access of the num vector. You can switch to, for example: for (int i = 0; i < size; i++) num[i] = start + i + 1; Also, missing return state...
64,975,657
64,976,517
Is there a way to get an application's path to add it to the registry automatically and run alongside Windows startup in C++?
I'm developing an application and would like to know if there's a way to get it's executable path automatically and run alongside Windows startup by adding it to the registry. This is my function so far: void Open(){ HKEY hKey; WCHAR path[MAX_PATH]; //to store the directory DWORD size = GetModuleFileNameW(NULL, pat...
You are clearly compiling with UNICODE undefined in your project, which means RegOpenKeyEx() and RegSetValueEx() are actually calling the ANSI functions RegOpenKeyExA() and RegSetValueExA(), respectively (as evident by you being able to pass char* strings to them without compiler errors). But, you are retrieving the fi...
64,976,171
64,977,204
How to template Varaidic as return type in template?
I'm stuck with variadic template problem. Contexte On one hand, I use a library whose functions look like template<class ...Cols> void doForVars(Cols&... args) { ... } And on the other hand I have a lot of structs struct Foo { int id; std::string name; double length; } struct Bar { int id; dou...
Valid for C++17. What you want might get quite hard and I do not think there is a generic solution apart form using macros. The first part is actually easy, you can use std::tie and simply return tuples. auto listFields(Foo& foo) { return std::tie( foo.id, foo.name, foo.length); } I am generally against using tem...
64,976,193
64,978,430
A certain program only works if I do NOT use sudo when running
Problem I have a problem where if I run a program using sudo, I do not get the desired output, but if I run without sudo, it works correctly. I am using raspberry pi with c++, using wiringPi to access the GPIO. This program will eventually involve using PWM pins to set motor powers, for which wiringPi requires the use ...
Fix: update wiringPi to newest version :)
64,976,460
64,976,836
How should a setter be written with a constant variable inside a class?
I'm a newbie in developing with C++. I get an error in "this->Buchtitel = buchtitel;" and can't understand why. I have to use const when initializing the variables in Book.h. The Error-Code is: E0349 Book.h std::string const Buchtitel; std::string const Autor; std::string const Anschaffungsdatum; bool const Status; B...
The value of a const variable can only be set during initialization of the variable. For a member variable that's as a default member initializer std::string const Buchtitel = "Das Boot"; or in the constructor's member initializer list book(string titel): Buchtitel{titel} { } The value cannot be set anywhere else. In...
64,976,647
64,976,670
What's the point in passing I/O as parameters?
I am learning C++ Primer, Fifth Edition; and I still don't get it what's the point of passing a reference to a stream in the Sales_data class Sales_data(std::istream &is) Why do this if you can just use std::cout and std::cin explicitly?
You don't have to pass std::cin to such a function. You can also pass std::ifstream to read from a file, or std::istringstream to read from a string, and so on.
64,977,366
64,977,384
C++ User defined function to populate an array
I'm just using cout to check if the function worked correctly. The cout that's in the function works and the output is 17 which is the first number in the text file. However, the cout in the main() function outputs 0. Why is this? #include <iostream> #include <fstream> #include <cmath> #include <iomanip> using namespa...
You need to pass your array as a parameter to the method arrayPop(). Then you would have something like this: #include <iostream> #include <fstream> using namespace std; void arrayPop(double X[], double Y[], const int size); int main() { const int size = 10; double X[size]; double Y[size]; arrayPop(...
64,977,982
64,983,038
Why does MSVC fail to compile this CRTP code?
I wrote some code that compiles well on recent versions of GCC and Clang, but fails on MSVC: invalid template argument for template parameter 'TL', expected a class template Can anyone please explain is this a bug or have I misunderstood something? Without partial specialization of types_list it works fine on MSVC to...
It seems to be bug indeed. To refer to the current instantiation you can usually omit the template paramter of the current type. This is what MSVC seems to do here. It causes an error because the template expects a template template parameter. But why you want to use a template template parameter? For CRTP you use the ...
64,978,018
64,978,127
C++ : expression must be a modifiable lvalue then undefined reference to class
So basically at first I wanted to change the value of CSubject "AE" with the use of a get method but, after seeing some documentation about it, doing this will cause errors like "expression must be a modifiable lvalue". So it's not possible to do such thing . For something similar we can use a set method in this case, ...
You have declared a CSubject constructor taking a std::string and an unsigned argument but have never provided an actual definition for it! Thus, the linker fails when that (used) constructor is not present in the compiled code. To fix this, either add an 'inline' definition of that constructor, as shown here (using an...
64,978,042
64,978,135
Overflow in recursive function
So I was writing this exercise code that computes the maximum value of a vector using recursion and, for some reason, I'm getting overflow on the return statement. Heres the code: template<typename T> T max_helper(vector<T> v, T max, int i){ T m = v[i]; cout << "Max: " << max << "\n"; if (i < v.size()-1) { ...
In case i < v.size()-1) is true, max_helper does not return any value so your program has undefined behavior. You should return something. Example: template<typename T> T max_helper(vector<T> v, T max, int i){ T m = v[i]; cout << "Max: " << max << "\n"; if (i < v.size()-1) { if (m > max) return max_...
64,978,073
64,978,289
Are Windows executables forward and backwards compatible?
Say I'm building a C++ portable executable and I include the windows.h header. Also, let's stick to just Windows 10. If I use the most recent Windows 10 Visual C++ toolchain to build the binary, can I run the binary on earlier versions of Windows 10? If I use the earliest Windows 10 Visual C++ toolchain to build the...
Quoting from Microsoft's documentation under Update WINVER and _WIN32_WINNT. Visual Studio and the Microsoft C++ compiler support targeting Windows 7 SP1 and later. Older toolsets include support for Windows XP SP2, Windows Server 2003 SP1, Vista, and Windows Server 2008. Windows 95, Windows 98, Windows ME, Windows NT...
64,978,109
64,978,518
The connections of the redefined Winapi structures with their original state?
I'm aim to understand WinApi struct redefine. But I don't find any documentation, reference or manual in anywhere. Please explain me, how is related to redefine struct to its original form, in the example below. Does the compiler understand the name of the redefined structure and establish a relationship with the PEB_L...
Please explain me, how is related to redefine struct to its original form In memory, both structs have the same layout, assuming they both use the same data alignment settings for their respective fields. PEB_LDR_DATA::Reserved1 is an array holding 8 bytes. ULONG and BOOL are 4 bytes each, thus the offset of MY_PEB_...
64,978,675
64,990,589
Extracting STL Map from Boost Property Tree
I understand that boost::property_tree::ptree may contain key-value pairs where the 'value' may be of any type. Now my question is that, now my 'value' is a std::map, and when I attempt to pt.get<std::map<std::string, std::string>> where pt is a property tree, I get a compile time error. Hence, my question is: How to e...
Very simply: Live On Coliru ptree pt; std::map<std::string, ptree> m(pt.begin(), pt.end()); However, note that keys need not be unique: std::multimap<std::string, ptree> mm(pt.begin(), pt.end()); And if you are want to transform all values to std::string (assuming they all have a string value): std::map<std::string,...
64,978,775
64,978,956
Best practice for accessing a specific child window from the parent's wndproc
I keep running into scenarios where, from a parent window's wndproc function, I must modify a child window (ex: clicking a child button adds to a sibling combobox; sending a message to the parent which it then forwards to the appropriate child). As far as I can tell, this means somehow obtaining the child's HWND refer...
Most notifications based on WM_NOTIFY or WM_COMMAND, which includes BN_CLICKED, carry the child's HWND as well as the child's ID, eg: WM_NOTIFY wParam The identifier of the common control sending the message. This identifier is not guaranteed to be unique. An application should use the hwndFrom or idFrom member of the...
64,978,788
64,979,155
C++ gcc 9.3.0 typeid of derived pointer always return typeid(BaseClass*) but dynamic_cast<derived_ptr> works fine
There are a few similar posts, here is my minimal case code: bool useDerived=true; BaseClass* maker; if (useDerived) { maker = new DerivedClass(); } else { maker = new BaseClass(); } if (typeid(maker) == typeid(DerivedClass*)) { cerr << "is derived type\n"; } else { cerr << "not derived type\n"; } Deriv...
typeid is evaluated statically in this case. You should have dereferenced so you would give it a glvalue of polymorphic type, instead of some pointer type. This line: if (typeid(maker) == typeid(DerivedClass*)) { should be: if (typeid(*maker) == typeid(DerivedClass)) {
64,979,667
65,028,730
When I try to write to wav in c++, it says corrupt file
I am trying to write to wav by taking data from the microphone input, and other headers, and putting that into the wav file. I do that, but it still says corrupted file. One note about the code is that in the struct with the headers, it's not in the correct order. In the WriteToWav function I entered it in the correct ...
So the issue was that I had to keep in mind formatting and Endianess. Instead of using << or .write, you have to have a precise format for it. A way to write to the file in the correct format is to use the following function I used below, and enter the same WAV headers. template <typename T> std::ostream& LittleEnd...
64,980,070
64,983,849
gdb stops when using watchpoints (as if ctrl-Z)
I've been using gdb for years but have not seen this behavior before. To debug a SIGABRT coming from a double free() somewhere in the program, I've set a watch point on the pointer to the buffer. Now when I run the program again, gdb 'stops' as if I pressed ctrl-Z or it received SIGSTOP. Any idea what's going on there ...
This is a bug in GDB that was fixed with this commit: https://sourceware.org/legacy-ml/gdb-patches/2019-05/msg00361.html This commit was in GDB 9, and you are using 8.2. You'll need to update your version of GDB in order to avoid this issue.
64,980,557
64,980,824
Why am I getting hieroglyphic text in message box
I am creating a button on my Win32 Desktop App using C++ that when pressed, displays a message box that prints out the user input from a text box along with some additional text. However, the message box displays with hieroglyphic text and gives the error C6054: String 'buff' might not be zero-terminated. I'm not sure ...
First you need to initialize the array buff, otherwise there will be uninitialized characters garbled when outputting. Then you should use swprintf instead of _tprintf (wprintf) to output the string to the buff array I modified the code as follows, and you can refer to it: LRESULT CALLBACK WndProc(HWND hWnd, UINT messa...
64,980,878
64,981,004
When I try to read from a file, the first and third words of the file are skipped for some reason
In my program I'm trying to read from some files, store the data into structs, and sort/display the data for an assignment. However, it wasn't quite working right, and after some troubleshooting I noticed that from every read file, the first and third words are skipped for some reason. The relevant code: void fillArray...
while (ifile >> arr[count]) { getline(ifile, arr[count]); count++; } ifile >> arr[count] reads a word & without count being incremented, getline reads the rest of the line & overwrites what was read by ifile >> arr[count] That may be the cause of some words being skipped - the words read by ...
64,981,017
64,983,894
How to change a Callback signature that also accepts class methods and free functions?
I have a Callback which looks like this: typedef void(*Callback)(EventInfo event_info); This can be used with free functions, but when I try to use class methods it fails with the error : Error C2276 '&': illegal operation on bound member function expression How should I go about this and make it so that it als...
Pointers on function are limited to .. pointers on function. To allow any callable, you have to use template or type erasure as std::function: using Callback = std::function<void(EventInfo)>; struct MyClass { Callback callback; }; struct A { void foo(EventInfo) {} }; void bar(EventInfo) {} int main() { ...
64,981,611
64,981,814
How to deal with pointers to define a function? And problem to define a function which returns an array
Suppose I need a function which generates an array r[3] = {x, y, z} where x[1000], y[1000], z[1000] each one is an array and has 1000 double float points. I made a function which returns the location of r form where we need to access the x, y,z by unpacking the memory location. I have the code like: double cylinder(dou...
This can be easily fixed by using the Standard Library std::vector in conjunction with std::tuple which is like a really lightweight fixed-length array: #include <vector> #include <tuple> std::vector<std::tuple<double,double,double>> cylinder(double radius, double height) { std::vector<std::tuple<double,double,dou...
64,981,643
64,988,014
How to accurately measure time in c++?
I want to measure the execution time of a function very accurately, in picoseconds. Can it be so precise in C++? The methods I currently know to measure time are: __rdtscp() std::chrono clock clock.h clock_t Does anyone know how accurate these three functions can be? Which one can achieve picosecond time measurement,...
No clock on a consumer grade computer is going to measure with picosecond accuracy. The call to get the current time alone is going to take at least tens of nanoseconds. However you can time your target in a loop and measure the entire elapsed time. Then compute the average time per iteration. <chrono> allows you to ...
64,982,442
64,982,606
Error: ‘board’ was not declared in this scope (C++)
I am writing code for a board game and trying to test it out. I cannot figure out how to solve this error that gives the message: error: ‘board’ was not declared in this scope". This message comes up for line 9. I would really appreciate the help. #include <iostream> #include "Board.h" using namespace std; int main...
So you have a misunderstanding about how objects work. There is no need to pass member variables to a member function because member functions have access to member variables automatically. That is one of the major features of object orientated programming (in C++ at least). Rewrite your code like this struct Board { ...
64,982,732
64,982,924
How to properly supply a preprocessor variable for a Makefile?
I am working on a project made up of multiple files of c and c++ code. I did not write the code and I am just reformatting its structure. I am using visual studio code to edit my code. I was getting a warning that several variables were going unused when I issued the "make" command. After looking at my code, I realized...
Your makefile expects the DATAVIS macro to be defined (because of #ifdef DATAVIS), so your CFLAGS should just be -DDATAVIS what you wrote defines a macro var with contents DATAVIS.
64,982,811
64,984,760
C++ Program in vscode is only displaying last two elements of a 2D array
#include <iostream> using namespace std; int main() { system("cls"); int m,n; int ar[m][n]; cout<<"Enter the rows: "<<endl; cin>>m; cout<<"Enter the columns: "<<endl; cin>>n; cout<<m<<"x"<<n<<" Matrix"<<endl; for(int i=0;i<m;i++){ ...
Just move the declaration of the matrix after you get the values of 'm' and 'n'. Note, this will create the matrix on the stack, so for large matrices this is not a good idea. You can allocate memory dynamically as suggested in other posts. int main() { system("cls"); int m, n; cout << "Enter th...
64,982,836
64,989,566
How to suppress auto-searching when subclassing combobox (Win32/WinAPI)
I want to make a custom search but it's crippled by auto search. Here is what I mean, This is my subclassing function: LRESULT CALLBACK X(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam,UINT_PTR r1,DWORD_PTR r2) { switch(message) { case WM_KEYDOWN: { if(wParam>64&&wParam<91) //if ...
Per Default Combo Box Behavior, the default search behavior is triggered in response to WM_CHAR, not WM_KEY(DOWN|UP): WM_CHAR Processes character input. In drop-down list boxes, this message is passed to the list window, which moves the selection to the first item beginning with the specified character. In simple and ...
64,983,039
64,983,330
Inheriting from template abstract class
I have this code structure: An abstract class A (it has a pure virtual method) A class template B that inherits from A A class template C that inherits from B class A { protected: int u; int z; public: A(int uu, int zz) :u(uu), z(zz) {}; int get() const { return u; }; ...
This is a problem with a nondependent name - the member you're referring to does not depend on the template parameter. The compiler does not look in dependent base classes (like B<T>) when looking up nondependent names (like u). You can solve it by using this->u = this->u + qrqr; which specifies to the compiler which u...
64,983,117
64,984,157
Loss of floating point values :: reading JSON with rapidjson
In the project, the program reads JSON Document (using rapidjson) and then takes a part of that JSON document and tries to create new JSON Value. Following code is used for that # jsonstring is the JSON string rapidjson::Document firstJSON = readJsonString(jsonstring); # val is the Value which is a small part of firstJ...
Converted OP's comment to an answer: The precision was set at 1, that's the reason you are getting this output. So set the precision to 18 and this issue should be solved.
64,984,968
64,985,161
In C++ 64-bit environment, is there a case where the result Pointer of the new operator uses all 8 bytes?
I use Windows 10 OS Pc and build in environment debug x64 mode. I used Visual Studio 2019. example code int * d = new int; -Memory- &d is 30 45 0f 2f 12 02 00 00 Actually, in this case, it seems that the upper 2 bytes are not used. Is there a case to use up to this part?. I'm trying to put a memory usage count in th...
In C++ 64-bit environment, is there a case where the result Pointer of the new operator uses all 8 bytes? There is no general guarantee applying to all 64 bit CPU architectures, that some of the bytes of a pointer would be unused. In latest implementations of the x86-64 architecture, the high 16 bits of a virtual add...
64,985,070
64,985,687
C++ variadic template deduction fail
I have written a variadic template function with recursive evaluation. For the final parameter I implemented a specialization without the variadic pack and everything worked fine. Now I want to convert the variadic function parameters into template parameters. This is my try: template<typename N, int p> // specializati...
As noted in this answer, the variadic pack can be indeed empty. But you can specialize the case of a non-empty variadic pack with SFINAE. For example: #include <iostream> #include <type_traits> template<typename N, int p> // specialization N constexpr myadd(const N &n) { std::cout << "specialization" << std::endl;...
64,985,585
64,986,210
Trying to create something like command line game in C++
The code is giving me these errors Severity Code Description Project File Line Suppression State Error C2664 'int printf(const char *const ,...)': cannot convert argument 2 from 'void' to '...' game C:\Dev\game\game\game\player.h 20 Error C2664 'Player::Player(char *,int *)': cannot convert arg...
There are a lot of issues with your code. As has pointed out in @AriaN's answer, you mixed up the order of arguments in the Player constructor. You really should avoid these unnecessary pointers. In particular, you dereference hp in if (*hp <= 0). You check agains nullptr will never be carried out. You should check ...
64,985,752
64,986,499
Combining n vectors into one vector of n-tuples
I'm thinking about a function with signature template<typename ...Ts> std::vector<std::tuple<Ts...>> join_vectors(std::vector<Ts>&&...) { //... }; but probably a more general one accepting any iterable instead of just std::vector would be good. Probably it would have a signature like this? template<template<typena...
For any indexable containers with size something like this is possible: #include <tuple> #include <vector> #include <algorithm> // Copy from lvalue containers, move from rvalue containers. template<typename ...Cs> auto zip(Cs... vecs) { std::vector<std::tuple<typename std::decay_t<Cs>::value_type...>> vec; au...
64,986,334
65,023,296
Convert day of the year to date with QT
I am facing an issue, the API that I am using return the year and the day of the year. For example : year = 2020 & day = 328 and I should be able to convert it to 24/11/2020. I saw that QT implements a method called "daysInYear" in QDate which looks like to do the exact opposite of what I need. Does anyone knows a meth...
I think you can write that to obtain what you desire: QDate(year, 1, 1).addDays(day); // or addDays(day - 1) if your `day` starts at 1. But make sure to do a small test to check that it is correct, depending on whether your day equals 0 or 1 on January 1st ! CAUTION: daysInYear() returns the total number of days for a...
64,986,378
65,029,298
Makefile: No rule to make target. But from what I see It shoudl be covered
Hello Newcomer to makefiles here. I am having problems understanding why my makefile wont work. I get the following error: make: *** No rule to make target '../obj/StageObject.o', needed by 'test_distances'. Stop. My $(OBJ_FILES) contains the following string: ../obj/StageObject.o ../obj/Coordinate.o ../obj/Robot.o ...
As stated in the comments, changing from hpp to cpp solved my problem. Indeed i am using .h and not .hpp as file extension names. Running make with -d as also stated in the comments is quite usefull.
64,986,610
64,986,689
c++ : creating tuple & adding an element
I have several objects of custom classes and I try to create a class which can store all my previous objects using std::tuple. Unfortunately I'm new to c++ tuples. Below is what I've done so far: class Universe { public : std::tuple<Plain, Point, Rectangle> all_things; Universe() { this->all_things =...
The error that you see implies that one of the members that the tuple contains is not default-constructible. In such case you must initialise the member tuple with appropriate arguments to use the non-default constructors of the members of the tuple. Also I would like to know if there any tuple method for adding a thi...
64,986,755
64,986,830
What does 'template <typename> class X' mean?
Stan Lippman et. al (in "C++ Primer ", 5/e) , say : 1 // forward declarations needed for friend declarations in Blob 2 template <typename> class BlobPtr; 3 template <typename> class Blob; // needed for parameters in operator== 4 template <typename T> 5 bool operator==(const Blob<T>&, const Blob<T>&); 6 ...
template <typename> class BlobPtr; This is declaration of a class template. The name of the template is BlobPtr and it has one template type parameter.
64,987,105
65,000,784
Boost build a new version with VS 2019
I downloaded the latest version from https://www.boost.org/ and I need to build in VS2019 (C++, 32bits) when I build the files contains mt and the toolset My question is how I can remove the mt and the toolset from the lib and dlls ?
Boost library file names describe what they support and how they were built. In your case they support multithreading and were built with VS2019 (as opposed to MinGw, Clang or an earlier version of visual studio). For more information see: how can i decode boost library naming. boost uses auto linking with visual studi...
64,987,283
65,153,142
eigen3.3.7 segment fault when std::cout
Describe I'm writing a toy code with Eigen. But when I try to print the matrix I, unfortunately, meet the segment fault when cout. The following first code is my project code that meets the segmentation fault. I know that if I just write a tiny code as the second code, it works fine. So I don't know what's the matter ...
Yes, I finally successfully overcome the issue. It's the wrong with the #pragma pack. So, please use the sentence following the #pragma pop, just like the new and delete must be the same to make sure the program is right. pragma pack(push) without corresponding pop leads to stack smashing https://gitlab.com/libeigen/e...
64,987,457
64,988,181
QProgressBar updates as function progress
How to initializa the operation of QProgressBar, I already declare her maximum, minimum, range and values. I want to assimilate the progress of QProgressBar with the "sleep_for" function. Current code: void MainPrograma::on_pushCorre_clicked() { QPlainTextEdit *printNaTela = ui->plainTextEdit; printNaTela->move...
use a QTimer and in the slot update the value of the progressbar MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); t = new QTimer(this); t->setSingleShot(false); c = 0; connect(t, &QTimer::timeout, [this]() { c++; if (c==...
64,987,745
64,990,224
How to convert QString with special characters into a byte stream to send it via Linux pipe
I have a QString containing a special character (µ) encoded in UTF-8: QString data = "197,45 \xc2\xb5m"; I need to send that string via a Linux pipe to another program. I tried to convert the string into something like this: char msg[15]; for(int i = 0; i < data.length(); i++) { msg[i] = data.toUtf8()[i]; } ms...
What you are doing seems to be mainly "serializing the data" into a binary pipe, so an option that could make sense is to use a QDataStream which is designed for that purpose. Something like: QByteArray buffer; QDataStream stream(&buffer, QIODevice::WriteOnly); QString data = "197,45 \xc2\xb5m"; stream << data; sendT...
64,987,767
64,987,913
Non-template class with a template class as a field without specifying template parameters
Is there a way to have a template class such as this template<bool state = true> class A { }; and have another class which can accept both A<true> and A<false> as a argument or field, without being a template class itself. Like this: class B { public: B(A& arg_a) : a(arg_a) {} private: A& a; }; in...
Or is this simply impossible because two objects of the same class with different template arguments are treated as different types by the compiler? The two different specializations A<true> and A<false> of the class template A are indeed different types. You could either overload the constructors of B to allow each ...
64,987,921
64,988,916
CMake not finding package that is clearly there
I am trying to build a project via cmake in qtcreator, but am having trouble with the external package dependencies. There have been several packages that it could not find, but I added symlinks to the actual file locations into the directory cmake was looking in, afetr which they worked fine. However, this one librar...
Creating symlinks by hand suggests you have an incomplete installation. Clean up your manual symlinks, and figure out what's wrong with your installation. It is normal on Linux that the .so.x.y.z with the full numeric version is the runtime library. That is, the file that is required for applications to run. The ver...
64,988,289
64,999,272
Visual Studio can't find Installed version of SDK(10.0.17763.0) for a solution
So yesterday when I reopened an old work solution/project it failed to compile with: "error MSB8036: The Windows SDK version 10.0.17763.0 was not found. Install the required version of Windows SDK or change the SDK version in the project property pages or.." The problem is: I do have that SDK version installed but it...
First, you could check whether the solution platform settings are consistent. For example, both are x64: Second, you could set the SDK version in Properties->General. Then, check whether there is 10.0.17763.0 in Retarget Projects. If you still don't have this version, you can try to find Desktop development with C++...
64,988,379
64,988,491
std::enable_if ... else aka typename_if_else
Similar to std::enable_if I would like to have an else type info (I need this for dependent variadic template static_cast). I extended the possible implementation from the standard as follows: template<bool B, class T = void, class F = void> struct typename_if_else {}; template<class T, class F> struct typename_if_els...
Is there a way to get rid of the empty struct (first definition) which is not needed any more? Yes, thanks to std::conditional you can even get rid of the partial specializations: #include <type_traits> template<bool B, class T = void, class F = void> using typename_if_else = std::conditional_t<B, T, F>; // (can be ...
64,988,525
65,001,887
Bug related to g++/OpenMP when using std::thread?
I've distilled the problem I have to its bare essentials. Here is the first example piece of code: #include <vector> #include <math.h> #include <thread> std::vector<double> vec(10000); void run(void) { for(int l = 0; l < 500000; l++) { #pragma omp parallel for for(int idx = 0; idx < vec.size(); idx+...
Thank you to Hristo Iliev for useful comments, I now understand this and would like to answer my own question in case it's of use to anyone having similar issues. The problem is if any OpenMP code is executed in the main program thread, its state becomes "polluted" - specifically after the "#pragma omp parallel" direct...
64,988,540
64,988,811
Sort of copy constructor of derived class with base class parameter
So I want to have a constructor for my derived class to which I give an instance of my base class such that my base class is initialized with the input parameter and my derived class follows the default constructor. I came up with this (MWE): class Derived : public Base { Derived(){a = 0; b=3;}; Derived(Base * base): B...
The thing is, Derived(...):Derived(){}; calls default Base constructor. So adding additional call to constructor of Base confuses compiler - how should it know what you want? You can write it as follows if you wish to avoid code duplication: class Derived : public Base { public: Derived()=def...
64,989,711
64,989,801
Use switch cases in an if statement
Can we use a condition to include cases in a switch statement? My code: switch(menu_option) { if (g_logged_in) { case 'L': cout << "Login Menu\n"; break; case 'S': cout << "Signup Menu\n"; break; } case 'A': foo(); break; case 'B': bar(); break; default...
Currently, program control never reaches if (g_logged_in), so that's never evaluated. Your helpful compiler is issuing a warning. Really though a switch block is little more than a controlled set of goto statements. You could force it with switch(menu_option){ foo: if (g_logged_in){ with a goto foo; somewhere ...
64,989,922
64,990,012
CUDA is it safe to copy a single element from device memory by array offset?
int main() { int n = 1000; float *d_a; cudaMalloc(&d_a, n * sizeof(float)); // do something that gives d_a value; int index = rand() % n; // copy index float res; cudaMemcpy(&res, &d_a[index], sizeof(float), cudaMemcpyDeviceToHost); cudaMemcpy(&res, d_a + index, sizeof(float), cudaMemcp...
Yes, there is no problem with what you have shown. It is legal and should copy the element you desire from device to host. Regarding your two methods, they are the same (this is a C++ question, not specific to CUDA).
64,990,691
64,992,249
deleting object pointed to by two differnet pointers
I have created one Node object and the pointer named head is pointing to it. Then another pointer named newHead is created which points to the same object. Then I delete the memory by doing delete head and reassign head to a nullptr. However, this change is not reflected by the newHead pointer. From the attached code i...
The two pointers were pointing to the same memory, the nullptr is not put in there instead of the deleted object. head = nullptr; // this is not putting nullptr where the deleted object was! This is why, newHead is not pointing to nullptr but to a released memory. What you want is a Reference to pointer // CPP progra...
64,990,731
64,991,137
type trait to detect structs with specific methods which have const variants
I require a trait to detect when a struct has particular methods. For example, I would like to detect when a struct has the two methods void foo() and void bar(SomeData), and false otherwise. My attempt below works, except when the struct additionally has const variants of the required methods. I would like it to work ...
Note that your has_methods isn't actually testing for methods. &T::foo matches any member named foo. As mentioned in a comment you get a false positive for struct C { int foo; std::string bar; };. Fortunately the answer to your question also fixes that. You can use a static_cast to select the desired overload like this...
64,990,976
64,991,144
C++ Optimization Breaking Code That Stores References
I ran into an issue with my code that works fine without optimization, but breaks when optimization is enabled. After much investigating, I found the point at which the code breaks. It appears the problem has something to do with my use of references. I have a simple class as follows: template<typename T, typename U>...
You're on the right track: your rvalue reference-taking constructor is not "moving" the value correctly. In fact, it's not moving it at all, in the sense of move-constructing a value from it. Which makes sense. You haven't defined anywhere to move it to. Your class contains a couple of references, but nowhere to store ...
64,991,249
64,991,347
C++ class template inheritance and operator =
I have an "assignable" object derived from a template class. But this object's assignment operator is not properly called even though the types are clearly defined. #include "stdio.h" template <bool any> struct Base { void operator = ( const Base& arr ) { printf("base = base\n"); } }; // definition in advance tem...
From copy_assignment (emphasise mine): A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T, T&, const T&, volatile T&, or const volatile T&. And If no user-defined copy assignment operators are provided for a class type...
64,991,629
64,992,408
How to Get All Thread Details , Like ThreadId , Description , Status . Win32 API C++?
I need to get thread details like , All ThreadID , Thread Description , Thread Status. int ThrdID = osGetThreadID(); printf(chex(mOSThreadID)); printf(chex(getThreadDescr())); Tried the above code but not getting anything.
You can enumerate running threads using CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD) with Thread32First()/Thread32Next() (see Traversing the Thread List on MSDN). Most threads are not assigned a description at runtime. But, for those that are, they can have their descriptions assigned in one of two possible ways (see S...
64,991,792
65,018,652
boost::future does not compile
I have a Problem when attempting to compile my project that uses boost libraries. The error I get is: 1>f:\server\packages\boost.1.60.0.0\lib\native\include\boost\thread\future.hpp(156): error C3646: 'policy_': unknown override specifier 1>f:\server\packages\boost.1.60.0.0\lib\native\include\boost\thread\future.hpp(156...
So the problem was that the boost package on my computer was corrupted. Reinstalling it on the project (through the visual) did not help because it just took it from the cache that is on my computer (C:\Users\ofir\.nuget\packages\boost) and not really downloaded from the internet. My problem was that the cache was corr...
64,991,926
64,992,653
GLFW convert codepoints to characters in glfwCharCallback
I cant figure out how to parse the codepoint in a char in my glfwCharCallback: std::string currentText; void char_callback(GLFWwindow* window, unsigned int codepoint) { // currentText += codepoint ??? } ... glfwSetCharCallback(window, char_callback);
As a start, you can simply truncate the unsigned int to a unsigned char and appending it to your std::string: currentText += (unsigned char) codepoint; Note that this is criminally wrong for anything beyond basic ASCII. As I remarked in the comments, you probably want to either store UTF-32 codepoints for rendering us...
64,992,127
64,992,180
C++ - Return a template with unknown template argument
I would like to load images from a filetype which can hold many different kinds of data : the pixels can be encoded as floats, doubles, unsigned chars, chars (akin to TIF files). All the processing I'll be doing on the image data after loading depends on the type of the data loaded. I already have a function which can ...
Return something like this: std::variant< std::vector<int>, std::vector<unsigned char>, std::vector<double> > This isn't a template, because which template you call is determined at compile time. The caller can get which vector by doing a std::visit and get a compile-time instance of the data. The types supported have...
64,992,425
64,992,461
Looking for Explanation of pointer initializing to const int and int
I was working through exercises in C++ Primer and found online solutions for Exercise 2.32. I understood that the following code was illegal because initializing can't convert from int to int*: int null = 0, *p = null; However, two of the solutions that were mentioned, that I did not come up with were: const int nu...
0 is one way of denoting a null pointer constant. (It's an integer type that evaluates to zero.) In other words it is a special case and you are allowed to assign a pointer type to it. A standards compliant compiler should issue a diagnostic for the assignments of a pointer type to null3 and null4. (It should also issu...
64,992,652
64,993,445
Access function from another class without having any relations
I'm still new to C++ and I'm trying to know if it is possible to access a function from another class knowing that no one is the father class here . This is a piece of my program to show you what I want to do exactly . class CSubject { public: CSubject() = default; CSubject(std::string m_Name){this->Name = m_Name...
Forget about classes for a second. You want to call Method2(), and from there, print information that was put into the AE. Suppose you didn't have two classes of your own, but rather, say: void Method2(); int main() { const char* AE = "Test"; // ... Method2(); } That wouldn't work, right? And it shouldn't...
64,992,788
64,992,948
How to print a message one time after all the iterations in the loop "for" are done?
My program analyzes the array in the loop "for". If all elements satisfy the condition, it should print a message one time, but my program does it after each iteration. Here's my code: #include <iostream> using namespace std; int main() { const int size = 32; int ARR[size]; cout << "The size of the set is " << size <...
It's pretty easy, just use a boolean flag to determine if the condition is met: bool isReflexive = true; for (int i = 0; i < size; i++) { if (ARR[i] <= ARR[i]) { isReflexive = false; break; } } if(isReflexive) cout << "\nThe relation is reflexive." << endl; else cout << "\nThe relation i...
64,992,803
64,999,697
C++ Template: typenames and ||s in the angle brackets
I'm browsing this piece of code right here, the TensorRT Engine serialization and deserialization source code. I stumbled across some syntax I've never seen before. struct Serializer<T, // ?? typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value || std::is_pod<T>::value>::type> { // ... Wh...
The syntax evaluates to void (to match the presumable default template argument) or fails to do so. You may need to review C++ templates again. SFINAE is a technique used to constrain template specializations via that failure. Since C++20 concepts provide a much better mechanism.
64,993,081
65,074,532
HLSL Alignment issues
I have issues with HLSL Buffer alignment. I have a light struct in an array of size 48 (i.e. a shader is meant to hold atmost 48 lights). (Divisiors are markers of 16 byte boundaries) struct RendererLight { float4 Position; //---// float4 Color; //---// float4 Direction; //---// float Intens...
As you've correctly noted on the C++ side, your ShaderLight data just contains 72 Bytes of 'used' data and has therefore 8 bytes of padding at the end. However, on the HLSL side, these 8 padding bytes are not needed for the last element in your array, as the follow-up element (the NumLight integer) can be packed inside...
64,993,190
65,012,747
How to detect ALT key press regardless focus in C++ Win32 application
Am I correct, that the only way to detect an ALT key press in a C++ Windows application is the keyboard hook? Could be multiple child windows and setting WM_KEYDOWN for each of them is not an option. Accelerator "VK_MENU, some_id, VIRTKEY" doesn't seem to work. There is no main menu to steal ALT functionality. Plain Wi...
Found the solution: // Main message loop: while (GetMessage(&msg, nullptr, 0, 0)) { if (msg.message == WM_SYSKEYDOWN && msg.wParam == VK_MENU) { // single ALT key pressed, do something } if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage...
64,993,450
64,993,692
Declaring a template member function in a tpp file
I have a class A that contains a template member function AFunc. To separate definition from declaration, I declare A and AFunc together in A.h. I then define the member function AFunc in A.tpp and #include "A.tpp" at the bottom of the file A.h. To me, this all appears like valid C++. However, the Visual Studio compile...
Are you giving the compiler the file "A.tpp", or another C++ source file that includes "A.h"? The way you have this structured, I would think the latter would give you the behavior you expect. Apologies, I don't have much VS experience.
64,993,455
64,993,674
In C++ why have va_start immediately followed by va_end?
I see the following code in a few functions in a project I am trying to read and understand: void Algo::descend(const enc_node* node, const char* option, ...) { ... va_list va; va_start(va, option); va_end(va); ... } I understand variadic functions in principle but why would someone make a variadic...
In C++ why have va_start immediately followed by va_end? No idea. why would someone make a variadic function and then call va_start() followed immediately by va_end() with nothing in between? No idea, that doesn't make much sense. It's like writing int a; and never using that variable. (Probably a sign of not enoug...
64,993,563
64,993,914
CUDA access matrix stored in RAM and possibility of being implemented
Recently I started working with numerical computation and solving mathematical problems numerically, programing in C++ with OpenMP. But now my problem is to big and take days to solve even parallelized. So, I’m thinking in start learning CUDA to reduce the time, but I have some doubts. The heart of my code is the follo...
Can I program, at least the central part of this function, in CUDA? I only parallelized with OpenMP the internals loops because was giving the wrong answer when I parallelized all the loops. Yes, you should be able to program the portion that you currently have in the OpenMP scope, as a CUDA kernel. The function tab...
64,993,672
64,993,767
If an integer is signed by default, why does the signed keyword exist?
I'm curious why the signed keyword exists because I believe most integers and other variables are signed by default. Putting the signed keyword before int virtually does nothing. What is it used for, and why does it exist?
There are at least two places where the signed keyword is not a no-op: With char: the signedness of "plain" char is implementation-defined. On implementations where it's an unsigned type, signed char is needed to get the signed variant. Even if char is a signed type, signed char, char, and unsigned char are all distin...
64,993,943
64,994,218
What / where is __scrt_common_main_seh?
A third party library in my program is trying to call __scrt_common_main_seh by way of the Microsoft library msvcrt.lib, but is defined by some unknown library and therefore gives a linker error. I don't know what this function is supposed to do or where it is defined. I looked online for this function, but did not fin...
Summary For non-console applications having error error LNK2019: unresolved external symbol main referenced in function "int __cdecl __scrt_common_main_seh(void)" try adding linker flag /ENTRY:wWinMainCRTStartup or /ENTRY:WinMainCRTStartup For console applications having that error, make sure to implement a main() func...
64,993,955
64,994,159
How to create the Comparable interface in C++ and pass an array of comparables?
Runnable code sample: run this code here online I do know the correct full example should be use template classes, but for the sake of simplicity I would like to see a naive implementation without templates. I also know that virtual operator overload of the < or > operator would be more appropriate in C++ instead of th...
(Comparable **)rectangles You're getting strange results because this cast is an invalid reinterpret_cast. This invalid cast is causing undefined behavior. In your case, the undefined behavior represented itself as calling a different method, rather than deleting your files, so you were lucky. C++ arrays are not covari...
64,994,501
64,994,739
Is it possible to execute "cout" by order?
Is it possible to get the raw output as shown but with specific order(from bottom to top)? cout<<R"(programming )";sleep(10); cout<<R"( newbie at )";sleep(5); cout<<R"( i'm )"; sleep(1); output: programming------>printed third at the first line newbie at------->printed second a...
#include <chrono> #include <future> #include <iostream> #include <thread> int main() { using namespace std::chrono_literals; auto print_first_line = std::async(std::launch::async, []() { std::this_thread::sleep_for(6s); std::cout << "programming\n" << std::flush; }); auto print_second_...
64,994,575
64,994,635
Strange Node Deletion in Binary Search Tree
I'm writing out a BST that holds some data, and I'm trying to implement the function for removing a single element from the BST. Currently, my recursiveDelete() function looks as follows, and it works! Depending on your definition of works. It takes some other nodes along with it. template <typename ItemType, typename ...
else if (subtree->getRight() == nullptr) { BNode<ItemType> *temp = subtree; subtree = subtree->getRight(); // this is nullptr delete temp; } That getRight should be getLeft.
64,995,066
64,998,145
Google RE2 doesn't recognize Unicode escape in regex
I am developing an application, in C++, that validates configuration files with regex by using the Google RE2 library. The contents of the configuration files are read into an std::string; So far, I declared this string that contains the regex expression: const string EXPR_FAILED_FILE(R"([^\u0020-\u007E\n]|(\b.*(Mensag...
Each regex engine has its own syntax and in RE2 you need to use [^\x{0020}-\x{007E}\n] instead of [^\u0020-\u007E\n]. See the syntax document: Escape sequences: \a bell (== \007) \f form feed (== \014) \t horizontal tab (== \011) \n newline (== \012) \r carriage return (== \015) \v vertical tab character (== \013...
64,995,129
65,013,103
curl.lib missing (Visual Studio 2019, C++)
I have a project that require curl.lib but i tried every single tutorial that i have found online but noone helped me. The first method that i have tried is just downloading curl, going to winbuild and to run some stuff with nmake but i'm getting some errors and after downloading nmake and cl i'm still getting an error...
Finally i solved the issue using vcpkg, i discovered that this issue enter-vsdevshell error was the problem and if someone had my same problem that's the fix.
64,995,205
64,995,560
std::async execution order guarantee
I am trying to introduce logging to a multithreaded application. Currently, I am just using std::cout from the different threads. However, in that case, the order of the output is getting jumbled, even though one thread logged early, its output in stdout is coming after the log of another thread. So, one solution can b...
The whole point of std::async(std::launch::async, ...) is that it's asynchronous (thus using not only "async" in the name, but repeating it in the first parameter). You're not guaranteed much of anything about the relative order of things happening in threads created with std::async, unless you force synchronization us...