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
70,976,442
70,978,196
node not getting deleted if it's the head
This is my code, the important part at least. Whenever I run it and try to delete the head node, it won't work (the output will be a large negative number). It will work for all other nodes. Is it something with my code, or you just can't replace the head? node* displayList(node* head) { node* curr = head; whi...
deleteVal() is coded wrong. When NOT removing the head node, your while loop will exhibit undefined behavior if val is not found in the list. In that situation, cur will become NULL after the last node is checked, and then the loop will try to access cur->data one more time, which is UB. You need to swap the condition...
70,976,880
70,977,109
Multithreaded server don't switch between threads cpp
I'm trying to make a multithreaded server, but for some reason, the threads of my server aren't switching. Only the last thread that was create is running, the other threads aren't running. This is the code of the main server: void Server::serve(int port) { struct sockaddr_in sa = { 0 }; sa.sin_port = htons(p...
One main error in your code is that client_socket is passed by reference, and then it is modified by the server thread. A fix is to pass it by value. Another error is that _vectorOfSockets.push_back is modified by multiple threads - a race condition. You need to use a mutex to fix that. accept may fail when a client ha...
70,977,185
70,985,230
How to change Qt's default selection behavior?
I am new to QGraphicsView. So for the practice purpose I was drawing some shapes like Rectangle, Ellipse, Polygon, Polyline, Text etc. I observed here that, whenever we click on these drawn objects ( select them using mouse click ) dotted line rectangle appears around the object which indicates that, object is selected...
As far as I'm aware there isn't any 'built in' facility to fo what you want. In the current code base you'll see... void QGraphicsEllipseItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_D(QGraphicsEllipseItem); Q_UNUSED(widget); pa...
70,978,945
70,980,345
How to use "*" to make letters using rows and columns
Here is the code of which I'm writing to create the letter "Z" for example just cant figure out how to connect the rows and columns. Also don't know why its re-writing the code as many times by the user input. ex: user inputs 5 rows, it produces the "letter" 5 times over. if anyone is able to help me resolve this issue...
In order to draw the Z you need to add the horizontal "*" line at the beginning and the end. In addition you have to remove the outer loop, to avoid the letter to be drawn multiple times. This loop needs to be seperate at the beginning and the end, to draw the horizontal line: if (option == 'a') { // box ...
70,979,101
70,984,013
Why is my insertion sort algorithm altering numbers in the given array? (C++)
I have a C++n insertion sort function template, and it works fine when I give the function an array of integers, but when I give the function an array of doubles, although the array is indeed sorted afterwards, for some reason it alters the numbers in the sorted array. The code: #include <iostream> #include <stdlib.h> ...
The problem is, you want to compare the double numbers, but when you're going through the loop, you use the int i and int j variables. Result is incorrect due to incompatible data type. if you covert "double" the "int" data types, your problem will be solved. Also you must change your array type to double.
70,979,238
70,979,531
expected identifier before ')' token
When I tried to compile my game; and it says like Networking/Sockets/Socket.hpp:18:81: error: expected identifier before ')' token so if you want to see the source code I've in github here the link: https://github.com/suky637/ServerPlusPlus for peaple that do not want to go to github I will send you the Socket.hpp (th...
You seem to have missed that actual answer. interface is used as a typedef in some windows headers see What is the "interface" keyword in MSVC? change the name to iface or something like that
70,979,477
70,979,835
offsetof macro in c++
#define offsetof(s,m) ((::size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m))) I've been looking for this code for several minutes and I still don't understand what the const char volatile reference thing is, it's giving me a headache. #define offsetof(s,m) ((size_t)&(((s*)0)->m)) This one is pretty clear, d...
If s::m is of a class type, it could overload operator&, so &(((s*)0)->m) would be the same as (((s*)0)->m).operator&(), which could do something unexpected. To not use any custom operator&, it is cast to a const volatile char& first (which will have the same address). It needs to be both const and volatile because s::...
70,979,534
70,979,755
#include errors detected based on information provided by the configurationProvider setting
I keep getting three errors when I try including a header file that looks like this: #include <iostream> #include <"maximum.h"> // *** Header file that is getting the three errors *** These are the errors I am getting: #include errors detected. based on information provided by the configurationProvider setting. cannot...
You are trying to find file .../"maximum.h" which obviously in not existing. Use either <maximum.h> which first will search your file inside compiler directories or "maximum.h" which first will search near your current file.
70,979,849
71,081,818
Windows 10 detect keyboard layout change
I'm trying to implement a service that would monitor language/layout changes. I switch between English and Russian languages. So far I've found this question and tried to implement and install both sinks suggested there. However, there are problems. ITfActiveLanguageProfileNotifySink::OnActivated is not triggered at al...
I found another way to detect such changes: to use SetWindowsHookEx with WH_SHELL. One of the available event is HSHELL_LANGUAGE which is exactly what I need and the test project seems to work just fine. There's an article by Alexander Shestakov that describes a program very similar to what I'm trying to achieve and it...
70,979,883
70,981,622
Can I reset shared_ptr without deleting object so that weak_ptr loses a reference to it
I'd like to reset a shared_ptr without deleting its object and let weak_ptr of it loses a reference to it. However, shared_ptr doesn't have release() member function for reasons, so I can't directly do it. The easiest solution for this is just to call weak_ptr's reset() but the class which owns the shared_ptr and wants...
std::shared_ptr and std::weak_ptr are made to model the concept of RAII. When you use a std::shared_ptr, you already made the decision that it owns the resource, and that it should release the resource on destruction. The clunkiness you face is due to a rebellion against RAII: you want std::shared_ptr to own the resour...
70,979,884
70,980,047
How can I interrupt boost message queue send & receive that are being blocked by signals?
I have a process which is using boost message queue. When it is being blocked in either send or receive due to queue size limit has been reached, if I send a signal, it seemed the function call remained blocking. I expected the call to cancel or raise an exception but it didn't behave that way. How can I interrupt the ...
The way is to use the timed interfaces: for (int i = 0; i < 100 && !do_exit; ++i) { while (!do_exit) { if (mq.timed_send(&i, sizeof(i), 0, now() + 10ms)) { printf("%i\n", i); break; } } sleep_for(50ms); } E.g.: #include <boost/interprocess/ipc/message_queue.hpp> #in...
70,980,038
70,980,492
How to properly access packed struct members
What is the correct way to access packed struct's members? struct __attribute__ ((packed)) MyData { char ch; int i; } void g(int *x); // do something with x void foo(MyData m) { g(&m.i); } void bar(MyData m) { int x = m.i; g(&x); } My IDE gives warning/suggestion for foo that I might be accessing...
Is it incorrect to access misaligned pointer data but okay to use it to initialize a properly aligned type? (as in bar). As far as the C++ language is concerned, there is no such thing as a packed class nor such thing as improperly aligned object. Hence, an improperly aligned pointer would necessarily be invalid. Whe...
70,980,050
70,980,129
Why this shift operation plus bitwise works only up to 31?
Why shift operation below works and end up equal? Is there any name for this pattern? I am trying to find out what was going on in the head of the person who wrote this code! int i = 0x1; i |= 0x1 << 1; i |= 0x1 << 2; i |= 0x1 << 3; i |= 0x1 << 4; i |= 0x1 << 5; int j = 5; if( ((0x1 << (j + 1)) - 1) == i) { // WH...
Is there any name for this pattern? 0x1u << pos (or just 1u << pos) is a pattern for getting a number with only the bit in position pos is set. Using signed 0x1 is usually an anti-pattern. i |= 1u << pos is a pattern for setting a bit in position pos of the integer i. (1u << pos) - 1 is a pattern for creating a patte...
70,980,151
70,980,233
Outputting the objects out of a vector<object*> c++
I have two classes: class Transactions { public: std::string type= ""; double value = 0; void toString(); Transactions(std::string transT, double transVal) { type = transT; value = transVal; } }; class account { private: double balance = 0; std::vector <Transactions*> ...
this: class Transactions { public: std::string type= ""; double value = 0; void toString(); Transactions(std::string transT, double transVal) { type = transT; value = transVal; } }; should be class Transactions { public: std::string type= ""; double value = 0; ...
70,980,500
70,981,303
What does #ifndef _Python_CALL mean in a C++ code?
I am debugging a C++ code which contains something related to Python. In a function: void normalize(string &text) { ... #ifdef _Python_CALL newContentStr = contentStr; #endif #ifndef _Python_CALL ... ... #endif return 0; } I am using GDB to keep track of the code logic, and I found that after it reaches ...
Judging from the code fragment you've shown, _Python_CALL is a macro name, possibly defined somewhere via #define _Python_CALL (or maybe by some other means, such as using a command line argument to the C++ compiler during compilation). Then, line #ifdef _Python_CALL means that everything that follows it until the line...
70,980,598
70,980,651
How to intersect of more than 2 arrays?
I would like to intersect of more than 2 arrays. Here's incomplete version of my coding : #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { int n; cin >> n; cout << "\n"; string rock[n]; for(int i=0;i<n;i++) { cin >> rock[i]; cout <<...
Note: Variable length arrays are not standard in C++ and at best are a compiler-specific feature. In this case because length is not known at compile time, you'd be best off using a std::vector. Now, we just need to know how to find the intersection of two strings, and do that across the entire vector. I'm sure there's...
70,980,688
70,980,711
Undefined Reference to vtable After Adding Destructor
I looked at Undefined reference to vtable, but even after adding a destructor I am still met with a similar error: main.cpp:(.text._ZN8isStringC2Ev[_ZN8isStringC5Ev]+0xf): undefined reference to `vtable for isString' /usr/bin/ld: /tmp/ccVCX8sf.o: in function `isString::~isString()': main.cpp:(.text._ZN8isStringD2Ev[_ZN...
You didn't define the member functions isString::getBuffer and isString::size. You need to define them. If you don't want the class to have definitions for these functions, you must mark them as pure virtual, making isString an abstract base class which cannot be instantiated directly: virtual const char* getBuffer() c...
70,980,743
70,990,005
Passing arguments by template -- for efficiency?
There are two standard methods of passing arguments -- by value, and constant reference. Each has its trade-offs, with value being preferable in most cases that the data is very small. However, I just recently looked into templates more, and the way I understand it, they act more like a macro. Could you use templates t...
I think you are misunderstanding what templates are. Template arguments are not another way of passing runtime arguments to a function. Templates are a way essentially of doing code generation if you want to use the exact same code multiple times but with different types and/or constants when you know all the types and...
70,981,770
70,982,277
How to declare an array without size known at compile-time?
I am trying to implement random_function(), which outputs the amount of random numbers within a range (user input), and count_function() to count for the value that the user wants to look up in the outputted random numbers. I made the random numbers to be saved in an array called randomlist[] so that it can be used to ...
When you want to use an array, but the size cannot be known at compile-time, the generally accepted approach in C++ is to use a std::vector.
70,981,797
70,981,895
align the first digit for floats C++
Needing to align floats by the first digit, not by the decimal. I'm not 100% on the intricacies of setw(), so not sure if the output I'm looking for is even possible. Tried searching for an answer for a couple hours now, and nothing seems to be exactly what I'm looking for. The field width isn't accurate here, they're ...
You can try using left function for streaming your output as below: std::cout.width(6); std::cout << std::left << n << '\n';
70,982,566
70,983,535
c++ SFINAE - checking class has typedef, why is void_t required?
template <class T> struct has_iterator_typedefs { private: struct __two {char dummy[2];}; template <class U> static __two test( ... ); template <class U> static char test( typename __void_t<typename U::iterator_category>::type* = NULL, //NOTE: require __void_t , == NULL ? ...
you cannot have pointer to reference using X = int&; using T = X*; // fail so at least U::reference* is pretty likely to fail. I don't think NULLs are really necessary since the caller do provide all the value. note: I'm assuming __void_t is the same as std::void_t
70,982,750
70,983,510
How do I use std::is_same_v in a using statement?
Consider the following code: template<typename T> using IsInt = std::is_same<T, int>::value; template<class SrcType, class DstType> constexpr DstType As(SrcType val) { if constexpr (IsInt<SrcType>) return val; } This code compiles fine with C++17 but if I use std::is_same_v<...> instead of std::is_same<...>::value,...
Actually, the sample code doesn't compile. #include <type_traits> template<typename T> using IsInt = std::is_same<T, int>::value; The using declaration here is for type aliases. In C++17, it would have to be template<typename T> using IsInt = typename std::is_same<T, int>::value; However, this is incorrect, because ...
70,983,374
70,983,949
Armadillo C++ fails to diagonalize bigger matrices
I'm working with the Armadillo linear algebra library for C++ to diagonalize large matrices up to 65k x 65k on a cluster operating with SLURM. For matrices larger than 30k x 30k i get the following error message: Intel MKL ERROR: Parameter 9 was incorrect on entry to DSYTRD. Intel MKL ERROR: Parameter 8 was incorrect ...
Sorry, I do not have enough reputation to comment below so I have to make it an answer. During my use of Armadillo, I find the current version of Armadillo and Intel MKL does not work properly and can be buggy (Ubuntu 20). Indeed there have been a lot of reports of that but it's hard for us to do anything for it is the...
70,983,517
70,983,693
How to make the compiler 'paste' specific code to an area
i was working on an educationary project to study C++ where specific labels include code to that specific topic being studied. However, at the end of each code block i want the compiler to ask if the user wants to exit or countine from beginning: void main(void) { beginning: printf("goto : \...
The proper way to structure the code would be (pseudocode follows): Do PrintPrompt() input = ReadInput() switch (input) case 1: DoFirstThing() case 2: DoSecondThing() ... default: PrintError() While (UserWantsToContinue()) There's really no justification to using goto here (or almost anywhere, ...
70,983,595
70,988,240
Deducing extent when passing std::array to function expecting std::span
I have a function expecting a std::span parameter. This function is called by passing an std::array. This works fine if the std::span argument is declared with template parameter Extent set to std::dynamic_extent. But if the function is templated on Extent, the compiler is unable to deduce this value from std::array ar...
So why is the compiler unable to do the same deduction ? Because class template argument deduction is a different process from function template argument deduction. In the case of g, the compiler has no idea what the constructors of span are because... it's not a class yet. It's a template. And since template special...
70,984,103
71,008,828
Learning Curve in Q-learning
My question is I wrote the Q-learning algorithm in c++ with epsilon greedy policy now I have to plot the learning curve for the Q-values. What exactly I should have to plot because I have an 11x5 Q matrix, so should I take one Q value and plot its learning or should I have to take the whole matrix for a learning curve,...
Learning curves in RL are typically plots of returns over time, not Q-losses or anything like this. So you should run your environment, compute the total reward (aka return) and plot it at a corresponding time.
70,984,611
70,985,040
C++ program stuck in an infinite loop
Please note that I am a complete beginner at C++. I'm trying to write a simple program for an ATM and I have to account for all errors. User may use only integers for input so I need to check if input value is indeed an integer, and my program (this one is shortened) works for the most part. The problem arises when I t...
There are a few things mixed up in your code. Always try to compile your code with maximum warnings turned on, e.g., for GCC add at least the -Wall flag. Then your compiler would warn you of some of the mistakes you made. First, it seems like you are confusing string choice and int choice. Two different variables in di...
70,984,963
70,985,223
Selecting container type at compile time
I want to select one of the standard containers with one template parameter at compile time. Something like template<typename T> void foo() { using Container = std::conditional_t< std::is_same_v<T, int>, std::vector, // T is int std::set>; // any other T C...
The simplest way seems to be using Container = std::conditional_t< std::is_same_v<T, int>, std::vector<T>, // T is int std::set<T>>; Container bar; std::conditional_t allows you to select a type. There is no standard conditional template that would allow to select a template. You can write one...
70,985,020
70,988,136
Should I just believe that std::thread is implemented not by creating user threads only?
I learned that all of user threads mapped with a kernel thread be blocked if one of the threads calls some system call likes I/O System Call. If std::thread is implemented by creating only a user thread in some environment, then a thread for I/O in some programs can block a thread for Rendering. So I think distinguishi...
I learned that all of user threads mapped with a kernel thread be blocked if one of the threads calls some system call likes I/O System Call. Yes, however it's rare for anything to use kernel's system calls directly. Typically they use a user-space library. For a normally blocking "system" call (e.g. the read() funct...
70,985,072
70,985,157
Run time choice of method using std::bind. Problem with access to variable
I need to choice the particular method of the class at the run time. To do it I use std::bind. Below is an example demonstrating what I do: #include<iostream> #include<functional> class bc { public: bc(int, double); std::function<double(double)> f; //pointer to function which will be binded with f1 or f2 v...
*this causes a copy of the current object to be bound, use this or std::ref(*this) instead.
70,985,164
70,985,217
How can I choose the algorithm of a code only once at the beginning in C++?
There are two different algorithms being used throughout the code. Which one is chosen is determined at runtime by a parameter (e.g. true or false). I do not want to use if-statements each time the algorithm comes up. So instead of writing the following every time if (parameter==true) algorithmOne(); else algor...
You're almost there: auto algorithm = parameter ? algorithmOne : algorithmTwo. No (), you're not trying to call any function here.
70,985,312
70,985,613
unique_ptr to a derived class as an argument to a function that takes a unique_ptr to a base class and take owenership
I have already read various comments similar to this question here on stack overflow without finding exactly the solution to my problem. I have a Base class and Derived class an also a class that contain and also keep the ownership of this objects. class Base { }; class Derived: public Base { }; class MyClass { std:...
The function must accept the unique_ptr by value: void addElement (std::unique_ptr<Base> base) { myVector.push_back(std::move(base)); } and then call the member function like this: MyClass myClass; auto b = std::make_unique<Base>(); myClass.addElement(std::move(b)); auto d = std::make_unique<Derived>(); my...
70,986,423
70,986,707
Segfault 11 binary tree paths
I have to make a function in C++ that finds the external path and the internal path of a binary tree and prints them. I'm having trouble with a segfault 11 once the function for finding the paths is called, but I can't figure out where the segfault is. I don't have a very clear understanding of what a segfault is, all ...
In trovaCamminoRic, radice can be NULL, but you don't check that, and dereferencing NULL like in radice->prev is undefined behaviour, which usually crashes your program with a segfault. Simply add this check and it should work: void Albero::trovaCamminoRic(Nodo*& radice, int& contInt, int& contEst, int curr) { if (ra...
70,986,572
70,986,653
Problem with Output with Static keyword in C/C++
Output wrt my reasoning should be 0456 but the compiler shows 0415 and I debugged it a little and realised it is targeting both "i" differently. I'll be grateful if someone can explain the reasoning behind it. Thank You :) #include <iostream> using namespace std; int main() { static int i; for(int j = 0; j<2; j...
You should expect the output to be as follow: Loop pass #1: print 0 (top-level block scope i) followed by 4 (for loop block scope i). Loop pass #2: print 1 (top-level block scope i) followed by 5 (for loop block scope i). Thus 0415. static int i; // declares i at block-scope; denote as (i1) for(int j = 0; j<...
70,987,185
70,987,823
How long will QueryPerformanceCounter() return the correct value for 32 bit machine (without overflows)?
Will QueryPerformanceCounter return the correct value for 32-bit computer that is up for more than month or even a couple of months or years? Thanks
Microsoft guarantees that QueryPerformanceCounter will not roll over sooner than 100 years from boot: quoting https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps#general-faq-about-qpc-and-tsc How often does QPC roll over? Not less than 100 years from the most recent system boo...
70,987,238
70,987,971
Is there a C++ template way to loop on different enums?
In this topic I would like to know if a C++ way is possible to loop on different given enums ? The following source code is my proposition but doesn't compile. enum class Fruit : int { UNKNOWN = 0, APPLE = 1 }; enum class Vegetable : int { UNKNOWN = 0, CARROT = 1 }; static const std::map<std::str...
You can fix your code simply by adding constexpr in the lines: if constexpr (std::is_same<T, Fruit>::value) ... else if constexpr (std::is_same<T, Vegetable>::value) And use it like: std::cout << static_cast<int>(myFunction<Fruit>("apple")) << std::endl; std::cout << static_cast<int>(myFunction<Vegetable>("carrot")) <...
70,987,449
70,987,526
How can I skip the goto statement if the user enters marks less than 100
Note: I am a beginner. I have used goto statement to execute if the user enters marks more than 200 but if the user has entered marks less than 100 then the rest of the code should run. How can I do that ? Here is the piece of code #include <iostream> using namespace std; int main() { int a, b, c, d, e; float s...
Just use do-while loop as for example bool success = false; do { cout << "Enter marks for English" << endl; cin >> a; cout << "Enter marks for Urdu" << endl; cin >> b; cout << "Enter marks for Maths" << endl; cin >> c; cout << "Enter marks for Computer" << endl; cin >> d; cout << "E...
70,987,585
70,987,722
How to initialize shared_ptr not knowing its type?
I have a template function, that should get std::shared_ptr<sometype>. Inside of function I want to make a temporary variable with std::shared_ptr<sometype>, but I can't put sometype as template param because I don't know it. #include <memory> template<typename sometypePtr> void foo() { sometypePtr tmp_ptr = std::...
Assuming that sometypePtr is a non-array std::shared_ptr, then you can use sometypePtr::element_type. template<typename sometypePtr> void foo() { sometypePtr ptr = std::make_shared<typename sometypePtr::element_type>(); } If sometypePtr is an array std::shared_ptr, you will have to supply the extent as well as the...
70,987,964
70,988,078
C++14: enumeration previously declared with fixed underlying type: different behavior between compilers
Sample code: enum E : char; enum E; Invocations: $ g++ -std=c++14 -pedantic -Wall -Wextra -c <nothing> $ clang++ -std=c++14 -pedantic -Wall -Wextra -c <source>:2:6: error: enumeration previously declared with fixed underlying type $ icc -std=c++14 -pedantic -Wall -Wextra -c <nothing> $ cl /std:c++14 /Za <source>(2)...
From [dcl.enum]/3: An unscoped enumeration shall not be later redeclared as scoped and each redeclaration shall include an enum-base specifying the same underlying type as in the original declaration. Emphasis added. Clang is correct.
70,988,138
70,988,249
Sort elements alphabetically but keep one always at the beginning
I have elements of the following type stored in a collection. class Element { public: bool IsDefault { false }; std::wstring Name { }; Element() = default; Element(const bool isDefault, std::wstring name) : IsDefault { isDefault }, Name { std::move(name) } {} bool operator==(const Element& oth...
Include the default in the comparison: if(a.default != b.default) return b.default < a.default; // true, if a is true -> a is less // or more elegant (thanks, Adrian, for the hint): simply return a.default; // rest of comparison
70,988,185
70,988,294
C++ class question: why this "get" method exists
In my textbook on the chapter introducing classes it gives this example class: class clockType { public: void setTime(int, int, int); void getTime(int&, int&, int&) const; void printTIme() const; void incrementSeconds(); void incrementMinutes(); void incrementHours(); bool equalTime(const cl...
You are passing to your function getTime 3 references and these in the getTime function are filled with the private time values. Then once this function is called you will be able to access the time values ​​simply by using the variables you passed by reference. Note that unless you create a Time object that contains t...
70,988,313
70,988,342
In headers, should variables be declared as "extern" even if they are class data members?
I read in other posts that header variables should be declared using "extern" to prevent multiple definitions / memory allocation if the header is imported into several .cpp files. Is it also the case when these variables are class data members? I think not because including the class header don't create instances, so ...
The answer is no. To do so generates a compiler error.
70,988,402
70,989,879
SFINAE User-Defined-Conversion Operator
I'm trying to do a templated user-defined-conversion that uses design by introspection. In C++20 I can do the following: template<typename T> operator T() const { if constexpr( requires { PFMeta<T>::from_cursor(*this); } ) { return PFMeta<T>::from_cursor(*this); } ...
Can I do effectively what I can do with concepts with just SFINAE in C++17 for the user defined conversion operator? Consider that C++17 support if constepr. Given that you've developed a has_from_cursor custom type traits that inherit from std::true_type or from std::false_type, you can use it for if constexp. I mea...
70,989,133
70,989,209
Overloading operator () instead of [] for indexing
An old code base I'm refactoring has a rather unorthodox way to access n dimensional vectors by overloading the () operator instead of the [] operator. To illustrate, suppose Vec is a class that overloads both operators for indexing purpose of an internal list of doubles. Vec v, w; int index = 651; double x = v(index);...
One "problem" with [] is when you have multiple dimensions. With an array you can do arr[val1][val2], and arr[val1] will give you an array you can index with [val2]. With a class type this isn't as simple. There is no [][] operator so the [val1] needs to return an object that [val2] can be applied to. This means yo...
70,989,159
70,989,374
Check product in range postive or negative
You are given two integers A and B. Your task is to determine if the product of the integers A,A+1,A+2,...,B is positive, negative or zero. Input The input contains two integers A and B (−109≤A≤B≤109). Output If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero. #incl...
You probably remember from when you were little that the product of two positive numbers is positive. You probably also remember that the product of two negative numbers is positive, and that the product of one negative and one positive number is negative. In other words, multiplying by a positive number has no effect ...
70,989,165
70,989,539
How to support a range based loop in polymorphic classes (containing vector and set)?
I would like to iterate over some items in my class for (const auto i: myclass) { /* do stuff with i */} For this I want to expose the iterator of whatever STL container happens to be storing my data inside myclass. My class is polymorphic and has the following hierarchy: #include <set> #include <vector> class Base_t...
You're attempting to force runtime polymorphism into a box designed for compile-time polymorphism. That will naturally create problems. The iterator mechanism is based on compile-time mechanisms being able to ask questions of the iterator. Iterator tags are nothing like base classes. Iterator tag types do not do anythi...
70,989,418
70,989,494
Undefined struct 'addrinfo' winsock2
I encountered an error and I didn't find any solution (even over the internet) I created aQt app to receive data using a TCP protocol and plot them using QcustomPlot. I have the following files: mainwindow.h : #pragma once #include <QtWidgets/QMainWindow> #include "ui_mainwindow.h" #include <QVector> #include <iostrea...
You need to #include something in your mainwindow.h that defines struct addrinfo, because your MainWindow class has a member variable of that type. At the moment you include all the socket stuff only in your *.cpp file.
70,990,248
70,990,326
Extract list of types from std::tuple for template class
Suppose I have the following class class Example { public: using value_type = std::tuple< uint8_t, uint8_t, uint16_t >; private: value_type _value; }; Now, I want to be able to create another class based upon this type that wraps each of the classes types in another type. Based up...
You can use template partial specialization to get ARGS: template <typename T> class Wrapper; template <typename Tuple> class ExampleWrapper; template <typename ... ARGS> class ExampleWrapper<std::tuple<ARGS...>> { private: std::tuple<Wrapper<ARGS>...> _args; }; Then: ExampleWrapper<Example::value_type> myWrappe...
70,990,743
70,997,791
How to tell QPluginLoader to check for dll dependencies in containing folder instead of exe folder
I have a dll which is some kind of plugin and I intend to deploy it as a package, the dll and all it's dependencies (also dlls) in one package. The issue that I have is that the dll is checking for it's dependencies in the exe folder instead of its own folder, its dependencies are next to it. Is there a way to tell it ...
As @Alex Reinking pointed out the loader is responsible for finding the dlls, in my case the loading was done by QPluginLoader and a solution was to set the current directory to the plugin directory as the loader looks in the current directory for dlls: QDir pluginsDir(QLatin1String("../src/")); QDir::setCurrent(plugin...
70,990,821
70,990,939
How create method for get the child (QWebEngineView) of th curent view tab (QTabWidget)?
I'm trying to make some project with QTabWidget (a litle browser and a text editor with multiple tab like notepad++) but I'm stuck in 2 project when I try to edit a value of widget (QWebEngine or QTextEdit) inside of QTabWidget. This is the code for the litle browser project: fp.h : #ifndef FP_H #define FP_H #include ...
Try something like: QWebEngineView *view = qobject_cast<QWebEngineView *>( this->ui->onglet->widget(0) ); Note to put above somewhere in fp's methods (where you need the reference). I could use ui->onglet->currentWidget(), but the difference is, that will not work once you have multiple tabs.
70,990,839
70,995,175
How to link SDL_ttf and SDL_image libraries using cmake in windows?
I have trouble including and linking SDL_ttf and SDL_image to my project. I have a cmake file that works only for SDL and SDL_gfx on Clion. I guess the problem is from the cmake file. I got several errors when I build the project: undefined reference to `FUNCTION' The libraries which I used for my project: https://gith...
I found the problem: In sdl2-image-lib and sdl2-ttf-lib directory there are libSDL2_image.dll.a and libSDL2_ttf.dll.a binary files that must be linked instead of libSDL2_image.a and libSDL2_ttf.a files. dll files must be copied to the directory where the EXE file is located. the dll files are in bin folders of the li...
70,991,106
70,993,917
In a variadic function template can the return type be deduced from the template parameter pack elements
I am trying to write a variadic function template. The first argument to the function is an integer index value. The rest of the (variable number of) arguments represent the variable number of arguments. This function must return the argument at the location index. For example, if function is invoked as `find_item(1, -...
I want to know if there is any way that this can be achieved. No. In C/C++ (that are statically typed languages) the type returned from a function must depends from the types of the arguments, not from the values. So the types returned from the following calls find_item(1, -1, "hello", 'Z', 10.03); find_item(2, -1, "...
70,991,246
70,991,575
How to format output like this
My code is like this so far : void matrix::print(int colWidth) const { cout << getRows() << " x " << getCols() << endl; cout << "-"; for (unsigned int d = 0; d < getCols(); d++) { cout << "--------"; } cout << endl; for (unsigned x = 0; x < getRows(); x++) { cout << "|"; ...
If the column width is a parameter, you're almost done with your code. Just turn the cout<<"--------" into: std::cout << std::string(getCols()*(colWidth + 2) + 1, '-'); That code prints a string of dashes, which width is: number of matrix columns, times column width plus 2, plus 1: Plus 2 because you are appending a "...
70,992,159
70,992,244
can someone explain to me why my string is not not showing in output it happens to me a lot and this is a simple example,
can someone tell me why s is not showing up. #include <string> #include <iostream> using namespace std; int main() { string a="1 23"; string s=""; if(a[1]==' '){s[0]=a[1]; cout<<s; } return 0; }
You are not allocating any character memory for s to refer to, so s.size() is 0 and thus [0] is out of bounds, and writing anything to it is undefined behavior 1. 1: in C++11 and later, you can safely write '\0' to s[s.size()], but you are not doing that here. Try this instead: #include <string> #include <iostream> usi...
70,992,743
70,993,738
i am getting this error while making a build for opencv project on mac os (intel chip)
i am running any code(over xcodes)even "hello world" and i am getting the same error all the time how can i fix this ????? dyld: Library not loaded: /usr/local/opt/opencv/lib/libopencv_stitching.4.5.dylib Referenced from: /Users/khaledzbidat/Library/Developer/Xcode/DerivedData/OpencvCourse_-hhaivjyxxrgltdhgizcoxxkwob...
It looks like you need to disable library validation for your app to load this library. Apple are getting stricter and stricter about what will and will not run on macOS. You can do this in the 'Signing and Capabilities' tab of your project settings for your app build target (my app is called VinylStudio, in this exam...
70,992,965
71,057,524
How do I deliver OpenAL32.dll with my application without requiring OpenAL installation on the client machine?
I have a 32-bit C++ Windows application using the OpenAL library. I am using the official OpenAL setup to install the required DLL file, but when I publish my application, I would like to find a way to deliver it without requiring the user to install OpenAL seperately like I did. With other DLL files, I simply add them...
Apparently, I mixed up the System32 and SysWow64 folders in Windows. It should be the other way around! System32 on 64-bit Windows contains 64-bit .dll files SysWow64 on 64-bit Windows contains 32-bit .dll files For reference: https://www.howtogeek.com/326509/whats-the-difference-between-the-system32-and-syswow64-fol...
70,993,273
70,993,360
Is MSVC correct in refusing to compile this code?
Consider this code (godbolt): #include <type_traits> #include <memory> #include <cstdlib> using namespace std; template<auto L, class T = decltype(L)> using constant = integral_constant<T, L>; int main() { unique_ptr<void, constant<&free>> p1; unique_ptr<void, constant<free>> p2; // <-- MSVC refuses to c...
Pre-C++20 it looks like a MSVC bug. After C++20, the behavior is unspecified (thanks @heapunderrun) since free is not in the list of functions you're allowed to take the addresses of. But I'd argue that it's still a bug (even if conformant), since MSVC lets you take the address of the same function if you use &. Templ...
70,993,333
71,011,814
Why my Qt test (which uses a QProcess) fails?
I created a Qt test which invokes another program thanks to a QProcess. After calling the QProcess::start method, my test waits for it to finish with the QProcess::waitForFinished method. When I run this test with Qt Creator, there's no problem. But when I run it with CTest, the QProcess::waitForFinished function alway...
Finally, I found a solution : the QProcess:start method couldn't find the program because the working directory of my Qt test wasn't good. So, I changed it with the QDir::setCurrent and now, it works.
70,993,819
70,993,882
Is "this" a default parameter in a class method?
I've read somewhere that the "this" keyword is a default parameter (I suppose it's invisible or something) in any method of a class. Is this true?
"default parameter" is the wrong term. this can be thought of as an implicit paramter passed to member functions. If there were no member functions then you could emulate them with free functions like this: struct Foo { int x = 0; }; void set_x(Foo* THIS, int x) { THIS->x = x; } However, member functions do e...
70,993,901
70,993,930
C++ How can I combine and add functionality to the same inherited method by a class with multiple inheritance?
So say I have the class empire. empire inherits populationContainer and landContainer as such: class empire : public populationContainer, public landContainer Both of those parent classes have the method update(), each of which do their own thing; for example, the pop container calculates pop growth and the land conta...
My solution would be: // If you add more base classes here, add them also to the 'update' method class empire : public populationContainer, public landContainer
70,994,145
71,030,164
Python Compile Mixed C and C++ Extension
I'm attempting to compile libspng with PyBind11 so I can easily convert image data into a numpy array. The compilation process requires compiling a few C files and then linking them to C++. However, I'm not sure how to do this with Python setuptools. I've so far been compiling all C++ or all C modules in my practice, b...
In case it's helpful (and because I am procrastinating) I built a small demo based on the spng example // pywrappers.cpp #include <pybind11/pybind11.h> #include <utility> #include <cstdio> extern "C" { #include <spng/spng.h> } namespace py = pybind11; std::pair<size_t, size_t> get_size(const std::string& filename...
70,994,567
70,994,601
Lambda functions with "=" capture and memory usage
In my mind when I create a lambda [=]{...} all variables from parent function clones to the lambda. So the following code will use too much memory because variables a...z will be copied to lambda function: void foo() { long double a = 0.123456789; long double b = 0.123456789; long double c = 0.123456789; ...
[=] will cause only the variables that are actually used in the lambda to be captured by it. In your case val will have a copy of a and z. Assuming there is no padding (which there shouldn't be), then sizeof(val) == 2*sizeof(long double).
70,994,857
70,994,884
Should explicit keyword be used for move constructors?
This code does not compile. But if I remove the explicit keyword from the move constructor then it works. Why? struct Bar { Bar() {} explicit Bar(const Bar& x) {} explicit Bar(Bar&& x) {} }; Bar bar() { Bar x; return x; } The compilation error is: error: no matching function for call to 'Bar::Bar(...
The return statement copy-initializes the return value from the operand. Copy-initialization doesn't consider explicit constructors. But explicit doesn't change that the constructors you defined are copy and move constructors. Therefore no other implicit constructors will be declared. In effect, there is no viable cons...
70,994,879
70,996,278
No suitable user-defined conversion with inherited classes
I'm struggling with casing a subclass as a superclass to store in a vector of superclass pointers. The objective is to have a vector of ContainerObjects which can be both bins and boxes. This is a barebones example - in my code, I am passing in a definition of stuff to store in the box and then add the box to my invent...
Firstly, you should make your inheritance publicly. class Box : ContainerObject -> class Box : public ContainerObject class Bin : ContainerObject -> class Bin : public ContainerObject Secondly, std::unique_ptr implies only one owner, so it has no copy constructor/asignment only move constructor/asignment. So you should...
70,995,081
70,995,312
Switch-Case Range C++20 in Visual Studio Syntax Error '...'
Maybe a similar topic has already been discussed. But, I have a different problem. Here, I'm using C++ 20 in Visual Studio I have code #include<iostream> using namespace std; int main() { int a; cin >> a; switch (a) { case 1 ... 9: cout << "satuan" << endl; break; case 10 ... 99: ...
Hey you can use if else statement instead #include<iostream> using namespace std; int main() { int a; cin >> a; if(a <= 9) cout << "satuan" << endl; else if(a <= 99) cout << "puluhan" << endl; else if(a <= 999) cout << "ratusan" << endl; else if(a <= 9999) cout ...
70,995,142
70,996,114
two triangles, line, and border in OpenGL
I'm quite confused on how I can make two triangles that are not beside each other (they have a gap between them) along with a line and a border. I have a code done already, but for some reason the triangles and line won't show up, only the border is the one showing up when I comment the triangle and line codes. The tri...
The problem is that the color buffer is cleared before each mesh is drawn. This "clears" the previous draw mesh. Call glClear(GL_COLOR_BUFFER_BIT) once before drawing the scene in display, but don't clear the color buffer in triangle, line and border. Just remove glClear(GL_COLOR_BUFFER_BIT) from these functions.
70,995,704
70,995,904
Using for_each on container with const_iterators?
If you iterate on an std container with this elegant formula: for (auto& item: queue) {} It will be using queue's begin and end functions. Is there a way to use cbegin and cend without modifying the queue's source? I tried with for (const auto& item: queue) {} But if begin or end is missing, it doesn't compile.
Is there a way to use cbegin and cend without modifying the queue's source? In C++20, you can use queue.cbegin() and queue.cend() to construct a ranges::subrange: #include <ranges> for (auto& item: std::ranges::subrange(queue.cbegin(), queue.cend())) {}
70,995,866
70,996,036
Why does std::distance doesn't work on iterator of unordered_map?
I have this code: #include <bits/stdc++.h> #include <iostream> using namespace std; int main() { unordered_map<int, int> umap; unordered_map<int, int>::iterator itr1, itr2; itr1 = umap.begin(); itr2 = std::next(itr1, 3); cout << distance(itr2, itr1); return 0; } It compiles fine. But produces ...
Your code has undefined behavior. umap is empty, then std::next(itr1, 3) returns an invalid iterator. Change the order of the arguments passed to std::distance. InputIt must meet the requirements of LegacyInputIterator. The operation is more efficient if InputIt additionally meets the requirements of LegacyRandomA...
70,995,922
70,995,935
How does C/CPP know how to point to "next" struct node when the struct node is not yet defined?
When creating singly linked lists, it is common to create a Node struct as follows: struct node { int data; struct node *next; } However, I was wondering how does the pointer to the next node next knows what struct node is if node's definition has not been done yet. I have read from quora that the compiler...
Because next is a pointer to node, the type does not need to be complete in order for compilation to succeed. Consider also a simple example in C++. The type of A does not need to be complete in order to have a pointer to it in struct B. Be prepared to see this pattern used to resolve circular dependencies. struct A; ...
70,996,358
70,996,495
Error: GCC parenthesized initializer in array new
In template class constructor,initialize a array by T *p = new T[10](userInputData) But the G++ parenthesized initializer in array new, how to deal with it?
The problem is that although we can use empty parentheses to value initialize the elements of an array, we cannot supply an element initializer inside the parentheses. This means, int *pia2 = new int[10](); //VALID, block of 10 ints value initialized to 0 int *pia3 = new int[10](55); //NOT VALID For the same reason ...
70,996,748
70,999,739
Warning haswell support is incomplete
Pretty much the title, when I call (through the hpp header) instance.enumeratePhysical devices() I am getting the warning: MESA-INTEL: warning: Haswell Vulkan support is incomplete Thing is, that's not a validation layer error (my error message would append a lot of info not present here), it's not one of my print stat...
Why is this message showing? Because the "anvil" ICD (the Intel Vulkan driver from the mesa project) is present on your system and detected an Intel iGPU from the Haswell generation. This is basically what the physical device enumeration is about: checking all the installed ICDs and finding all the devices on your ma...
70,996,920
70,997,031
Why destructor is called if the return operation is elided?
I have the following code that mimics an elision testcase class Obj { public: int x = 0; Obj(int y) : x(y) {std::cout << "C\n"; } ~Obj() { std::cout << "D\n"; } }; auto factory() { std::vector<Obj> vec {1,2,3}; std::cout<< &vec[0] << std::endl; return vec; } int main() { auto vec = factory(); ...
With the initializer list construction: std::vector<Obj> vec {1,2,3}; First the initializer_list is constructed, with all 3 Obj objects. Only then is the constructor of std::vector invoked, coping the three objects. What you see as 3 destructor calls is actually the destruction of the initializer_list, not the vector ...
70,997,011
70,997,141
Overloading ostream << operator for a class with private key member
I am trying to overload the ostream << operator for class List class Node { public: int data; Node *next; }; class List { private: Node *head; public: List() : head(NULL) {} void insert(int d, int index){ ... } ...} To my humble knowledge (overload ostream functions) must be written outside the cl...
You can solve this by adding a friend declaration for the overloaded operator<< inside class' definition as shown below: class List { //add friend declaration friend std::ostream& operator<<(std::ostream &out, List L); //other member here };
70,997,021
70,997,233
How would you word this function differently?
My calculations are incorrect in the sense that my program thinks, for example, that 2022 is a leap year and 2024 is not. How do I fix this, please?? I've tried changing the bool statement but nothing seems to work. #include <iostream> int leapYear(int year) { return (((year % 400) == 0) || ((year % 4 == 0)&& !(ye...
Try like this in the leap Year function return (((year % 400) == 0) || ((year % 4 == 0)&& !(year % 100 == 0)));
70,997,431
72,242,742
How to check c++ pointer pointing to invalid memory address?
Is there anyone show me how to check my pointer is pointing to an invalid memory address. #include<iostream> class Node{ public: int data; Node * next , * prev; }; // Driver Code int main () { Node * node = new Node{ 3 , nullptr , nullptr }; Node * ptr = node; delete node; // here node gets delete...
I end up with this solution It may help someone who runs into the same problem #include<iostream> class Node{ public: int data; Node * next , * prev; }; template<class T> void DeletePtr (T*** ptr) { T** auxiliary = &(**ptr); delete *auxiliary; **ptr = nullptr; *ptr = n...
70,997,693
71,037,709
Why does Valgrind return executable file's exit code?
I want to run Valgrind in cp Linux command and watch the XML result of Valgrind. when I run the below command to get XML output, the exit code is 1. because Valgrind runs the cp command. valgrind --xml=yes --leak-check=full --verbose --track-origins=no --xml-file=/home/user/Desktop/test/cp_valgrind.xml --log-file=/home...
Valgrind will return the guest return value by default. If you specify --error-exitcode then it will return that value if there is an error from the view of the Valgrind tool and the guest returns 0. It will still return the guest return value of the Valgrind tool detects no errors. It does not translate a guest error ...
70,997,820
70,998,607
Bison shift/reduce conflict in "else"
Consider the following grammar: %start stmt; %right "else"; stmt: "foo" | "if" "(" exp ")" stmt | "if" "(" exp ")" stmt "else" stmt exp: "foo2" On running bison (with producing counter examples) I get: parser.yy: warning: 1 shift/reduce conflict [-Wconflicts-sr] parser.yy: warning: shift/reduce conflict on to...
In your counterexample, you can see that bison does not know if it should shift or reduce the "if" "(" exp ")" that is the stmt after your first ")". In other words, if it should group your first if with the else: if(exp) (if(exp) stmt) else stmt or the second if with the else: if(exp) (if(exp) stmt else stmt) To sol...
70,998,237
71,000,047
Redefinition error when defining friend function inside class template
I am learning friend declarations in C++ using the books listed here. So after reading, to test my understanding of the concept, i wrote the following program whose output i am unable to understand: template<typename T> struct Name { friend void anotherFeed(int x)//anotherFeed is implicitly inline and its definiti...
This issue is addressed here. However, for the purpose of determining whether an instantiated redeclaration is valid according to [basic.def.odr] and [class.mem], a declaration that corresponds to a definition in the template is considered to be a definition. So even though there is no actual instantiation of the def...
70,999,195
70,999,245
I have used enum in my code and it is crashing
I am using enum in the below code and using operator overloading but it is crashing. Could anyone explain why? #include<iostream> using namespace std; enum E{M, T= 3, W, Th, F, Sa, Su}; E operator+(const E &a, const E &b){ unsigned int ea = a, eb = b; unsigned int ec = (a+b)%7; return E(ec); } int main()...
E operator+(const E &a, const E &b){ This defines the + operator for two objects who are instances of class E. unsigned int ec = (a+b)%7; Both a and b are instances of class E, therefore the + operation will be done by calling your operator+ overload. Except that this is your operator+ overload in the first place. So...
70,999,852
71,000,070
Error When Passing String array to function in C++
Hi guys I've some errors when passing some strings of array in C++, do you know what's wrong with this code guys?, Thankyou #include <iostream> #include <string> void showData(string data[]); int main() { string namaMahasiswa[] = {"Nico", "Yonathan", "Andre", "Ratu"}; enum option{ SHOW = 5 }; switch (5...
As an alternative to the answer provided by @ACB, you can use a std::array. #include <array> #include <string> #include <iostream> template <std::size_t S> void foo(std::array<std::string, S> &bar) { for (auto &i : bar) { std::cout << i << std::endl; } } int main() { std::array<std::string, 3> baz...
71,000,168
71,001,240
Use a compiled dart executable as DynamicLibrary in Flutter
Since a longer time now it is possible to open a DynamicLibrary (dylib, dll, so) in Flutter. Those libraries are written in C or C++. I've now tried to build a basic dart command line application, compiled it using dart compile exe and tried to load it in my Flutter application using DynamicLibrary.open(), as you would...
Dart cannot create shared libraries like other languages can do because it needs to be run in an embedder/DartVM. This issue has a good explanation: https://github.com/dart-lang/sdk/issues/37480
71,000,795
71,000,893
Why can't I wrap a template parameter with parentheses?
to avoid XY, I will start by explaining my overall goal. I'm trying to make a choice between two different generic containers at compile-time. The solutions I came up with is very straightforward using macros. For the sake of demonstaration here is how it would look with std::vector and std::set (in practice they're ot...
Premised that I think that C/C++ macros are distilled evil (and that seems to me that you can substitute Container() using using) you can pass throug a type alias using pair_i_i = std::pair<int, int>; CONTAINER(pair_i_i) cont;
71,001,083
71,003,005
Use existing Static library in C++ WinRT UWP app
I have an existing third-party static library that I want to use in my project C++WinRT UWP app. Can I do that? I have read the documentation. But it has me confused. Documentation talk about "Using a native C++ static library in a UWP App" what is a native c++ library?. Also, I do not have the source code for this lib...
The primary limitation for UWP is that the library: (a) Must use the subset of Win32 imports that are supported for use in WINAPI_PARTITION_APP (b) It needs to have been built with VS 2015 Update 3 or later in order to be 'binary compatible' with modern Visual C++ tooling used for UWP. (c) Some APIs that are used by th...
71,001,327
71,001,382
argument of type "const char *" is incompatible with parameter of type "char *" & expression must be a modifiable lvalue
#include <iostream> class House { private: char name[20]; char date[10]; float width; float height; float age; public: void set(char n[20], char d[10], float w, float h, float a) { name = n; date = d; width = w; height = h; age = a; } void get() {...
The short answer is to use std::string instead. It's easier and safer. But if you must use arrays, keep in mind that you cannot assign an array to another like that. What you must instead do is copy elements from one array to another. Since you're dealing with char arrays, the obvious solution is to use strcpy: #includ...
71,001,409
71,001,507
Can I create a set of list::iterators? Will they still point to the same node after I erase/insert other nodes from the same list?
I want to create a set of list::iterators, so that when I update other nodes in the list, my iterator still points to the same node. int n; string s; cin >> n >> s; list<char> str; for (char c : s) { str.push_back(c); } vector<set<list<char>::iterator>> locations(10); for (auto it = str.begin(); it != str.end(); ...
You'd need a custom comparator. E.g. something like this: struct CompareIterators { template <typename It> bool operator()(It iter1, It iter2) const { using Ptr = decltype(&*iter1); return std::less<Ptr>{}(&*iter1, &*iter2); } }; using MySet = set<list<char>::iterator, CompareIterators>; vector<MySet> lo...
71,001,458
71,019,939
Constructing register map using templated class
I'm working on modelling some hardware in SystemC (although that's not relevant to the question). The goal is to be able to declare a bunch of registers in a block (class) which are used directly in the class implementation. The external software/firmware will access the registers through a register map to decode based...
[this](uint64_t address, uint32_t val) { myCallback(address, val); } worked struct my_reg_st { uint64_t data; uint64_t size(void) { return 8; }; void setValue(uint32_t val) { data = val; }; uint64_t value(void) {return data; }; }; class test { public: test() { myMap.addReg(0, &myReg...
71,001,735
71,002,826
How do I build a parameterized third-party library in cmake?
I have a project in which I have a third party library checked out as a git submodule. The third party library is just source code with no build system. In addition, The third party library must configured on a per-executable basis by way of compiler definitions and selectively compiling only the parts of the library t...
Let's sum up: The third-party library does not provide its own build. You need many instantiations of the library within a single build. You use these instantiations across multiple different repositories. I think you're pretty much taking the right approach. Let's call the third-party library libFoo for brevity. Her...
71,002,059
71,002,588
Do languages like JS with a copying GC ever store anything on the cpu registers?
I am learning about GC's and I know there's a thing called HandleScope which 'protects' your local variables from the GC and updates them if a gc heap copy happens. For example, if I have a routine which adds togother 2 values and I call it, it may invoke the garbage collector which will copy the Object that my value i...
(V8 developer here.) Do languages like JS with a copying GC ever store anything on the cpu registers? Yes, of course. Pretty much anything at all that a CPU does involves its registers. That said, JavaScript objects are generally allocated on the heap anyway, for at least the following reasons: (1) They are bigger th...
71,002,088
71,020,351
Export c++ code from simulink scheme with s-function
I have a simulink working simulink schema in which there are some s-function, I want to export this code in c++ and compile it. I already tried to export and compile a simple schema and it works, but when i try to compile the exported code of my project I get a lot of errors like error: #error Unrecognized use error...
At the end I found an answer that I post here in case someone else has my same problem. The solution that worked form my is: First of all once you have the generated zip file with all the sources and headers open it and load on the Matlab workspace the file buldinfo.mat then in the Matlab shell run packNGo(buildInfo) ...
71,002,089
71,002,883
std::cin don't break program when reading incorrect int
I have a program I made that will check your age and gender. I am using visual studio 2022 to see what happens when debugging. If I put random letters for the age it skips the cin > gender part which is so weird and the locals shows that age is set to 0 but gender is -52'' . What can I do so it still atleast takes your...
When you type bad data for the age and the conversion fails, cin enters an error state. When it's in an error state, it refuses to read anything. The simplest fix would be to just clear the stream after the first cout << "What is your age? \n" << endl; cin >> age; cin.clear(); // But now, the bad integer will become...
71,002,139
71,003,755
What is the fastest way to calculate the logical_and (&&) between elements of two __m256i variables, looking for any pair of non-zero elements
As far as I know, integers in C++ can be treated like booleans, and we can have a code like this: int a = 6, b = 10; if (a && b) do something ---> true as both a and b are non-zero Now, assume that we have: __m256i a, b; I need to apply logical_and (&&) for all 4 long variables in __m256i, and return true if one pair...
You can cleverly combine a vpcmpeqq with a vptest: __m256i mask = _mm256_cmpeq_epi64(a, _mm256_set1_epi64x(0)); bool result = ! _mm256_testc_si256(mask, b); The result is true if and only if (~mask & b) != 0 or ((a[i]==0 ? 0 : -1) & b[i]) != 0 // for some i // equivalent to ((a[i]==0 ? 0 : b[i])) != 0 // for some...
71,002,193
71,002,294
Partial specialization for class method
I'm trying to specialize a method of a (non-templated!) class. Apparently, it's not possible, however I am struggling to figure out why, or how to overcome the problem. class MyClass { public: template <typename... T> auto MyMethod(T... t) -> void { std::cout << "Original" << std::endl; } temp...
Only classes can be partially specialized; methods can only be fully specialized. As your methods still have template arguments (T) that are not specified, this means a partial method specialization. If you would use these template arguments for a class (and call a non-templated member function of that class) then this...
71,002,525
71,002,583
Using the "!" operator during file input/output operations in C++
I'm reviewing a project that does file input/output operations in C++. There are uses for the overloaded ! operator defined in std::ios that I have not encountered before. I know that the ! operator is used to check if a file has been opened. However, I did not understand why the author used the fstream object by using...
The ! operator is overloaded for classes derived from std::basic_ios (such as std::fstream) to indicate whether or not an error has occurred following an operation, or that has not been cleared after an earlier operation. From cppreference: Returns true if an error has occurred on the associated stream. Specifically, ...
71,002,556
71,002,585
Using two time values in while loop. The while loop doesn't stop when condition no longer 1. C++
My while loop isn't stopping even though one of the values becomes 'greater than' and the condition changes from 1 to 0. Before the while loops starts I set the time now in milliseconds. milliseconds_now I also set a time five seconds in the future. milliseconds_then I have (milliseconds_now < milliseconds_then) in the...
the milliseconds_now inside the loop is not the same milliseconds_now being tested in the while loop. Change it to while (milliseconds_now < milliseconds_then) { auto now = high_resolution_clock::now(); milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count(); cout << milliseconds_no...
71,002,931
71,003,042
Understanding capture by reference in C++ lamdba functions
I thought I understood how capture by reference works in C++ until I faced this situation: auto inrcrementer = []() { int counter = 0; return [&counter]() { return counter++; }; }; int main() { auto inc = inrcrementer(); cout << inc() << ", " << inc() << ", " << inc() << ", " << endl; ...
After expanding the outer lambda, your first example can be written as sth like this: struct incrementer { auto operator()() { int counter = 0; return [&counter]() { return counter++;} } }; As it's become more visible now counter is a local variable and the inner lambda operates on a reference to lo...
71,002,951
71,003,103
Win32 CryptProtectData Method
I was reading this: https://learn.microsoft.com/en-us/windows/win32/seccrypto/example-c-program-using-cryptprotectdata I was wondering about this method. Does this only store it in the process memory while the process is running? If so, is there a persistent data storage that the win32 api provides that's secure and do...
There's nothing wrong with storing your login token in a file (or in the registry, which I personally would prefer) provided that you encrypt it properly. The documentation for CryptProtectData has this to say: Typically, only a user with the same logon credential as the user who encrypted the data can decrypt the d...
71,003,073
71,003,110
C++ doesn't give me an output
I'm trying to loop through a 2d array and find the sum of some numbers but for some reason, I don't get any output from the compilier. Here is my code: #include <iostream> using namespace std; int main() { int arr[3][3] = { {2,5,7}, {3,6,8}, {5,8,6} }; int oddSum = ...
As arr[i][j] is not updated within your while loops, if that condition is true, it will never be false and the loop will never exit.
71,003,471
71,003,509
Template partial specialization issues "template parameters not deducible in partial specialization"
I am trying to understand why there is a "template parameters not deducible in partial specialization". I could not find an answer to this with current answers. Pre: template<std::size_t, class T, class F> struct IF { using type = T; }; template<class T, class F> struct IF<0, T, F> { using type = F; }; Actual...
Inserting the type alias, your partial specialization reads template <std::size_t x, std::size_t y> struct XTyp< typename Selector<x, y>::type > : std::integral_constant<std::size_t, x> { }; When the compiler needs to check whether this partial specialization should be chosen for a given specialization XTyp<Arg>, it h...
71,003,780
71,004,000
Standard compliant host to network endianess conversion
I am amazed at how many topics on StackOverflow deal with finding out the endianess of the system and converting endianess. I am even more amazed that there are hundreds of different answers to these two questions. All proposed solutions that I have seen so far are based on undefined behaviour, non-standard compiler ex...
compile time-enabled solution. Consider whether this is useful requirement in the first place. The program isn't going to be communicating with another system at compile time. What is the case where you would need to use the serialised integer in a compile time constant context? Starting at what C++ standard is the...
71,003,820
71,004,006
Unable to receive integer return value when calling Python function from C++
I am calling a Python function from my C++ code. The Python function takes two numbers as input and returns the sum. I am unable to retrieve the sum value in C++ code. Below are code for both C++ and Python files. C++ code: #include<iostream> #include "Python.h" int main() { Py_Initialize(); PyRun_SimpleStrin...
I got the solution by replacing auto result = _PyUnicode_AsString(pValue); with int result = PyFloat_AsDouble(pValue);. But I am not fully convinced as I needed an integer, but I had to use a function which looks to be meant for dealing with Float/Double. So, waiting for an accurate answer. Thanks!