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
69,206,266
69,348,778
Subgroups with the same name in different groups
I just started using Doxygen for the first time and ran into the following problem: I'm trying to create multiple subgroups with the same name like this: - Group 1 - Constructors - Other - Group 2 - Constructors - Other Instead what I get is this: - Group 1 - Constructors - (Constructors bo...
Short answer: Make sure to declare groups in doxygen commments (/**), not just C comments group definition takes a name and a title. The name (Constructors_1) must be globally unique, and acts as an identifier. The title (Constructors) is what is rendered, and does not need to be unique. Nesting groups can be used to ...
69,206,296
69,206,563
Are uninitialized references zero-initialized and uninitialized scalars default-initialized?
Are the following statements correct? An uninitialized reference is considered zero-initialized. An uninitialized scalar is considered default-initialized. Any other uninitialized entity is not considered zero-initialized nor default-initialized. They are based on [dcl.init.general/6] (bold emphasis mine): To zero-i...
Are the following statements correct? No, you are flipping the logical connections on their heads. The definitions of "zero-initialization" and "default-initialization" specify what it means if something else in the standard says "the object is zero-initialized". When the standard says that, you use the definition of...
69,207,095
69,207,307
c++ code not working, my output screen crashes
My output screen crashes whenever I try to execute my code. This is the part of the question: Declare a class named House for a real estate locator service. The following information should be included: Owner: (a string of up to 20 characters) Address: (a string of up to 20 characters) Bedrooms: (an integer) Price (f...
The most obvious problem is that you do the following: House* h[100]; /* ... */ h[time]->getData(); The definition of h creates an array of 100 pointers to House; it does not create a single house! With h[time]-> you try to access a house supposedly pointed to by h[time] but that house does not exist. A "C...
69,207,222
69,207,390
Insert (dynamic) command string in ShellExecute function in C++
Using C++ (on Windows 10), I'm trying to execute a command in cmd.exe that execute a python file that takes in another file (in csv format). What I would like to do is the same thing as if I were typing on the command line something like this: python3 .\plotCSV.py .\filetoplot.csv Or in better mode: python3 C:\...\Doc...
You are trying to write code inside a string literal. That is not possible in C++! You need to first create your dynamic parameter string, then pass it to a function. std::string has an overloaded + operator that supports string literals (const char *). std::string param1 = "/c \"python3 C:\\...\\Documents\\plotCSV.py ...
69,207,733
69,208,214
How can i store data in a 2d vector?
I have a piece of code where i read a CSV file and prints it contents. Now the issue is that I want to run my code on ESP32 and because of some limitations of micropython I can't upload my file in the spiffs storage. So is there any way I can store the csv file content in the code itself instead of reading it from the ...
The most obvious possiblities are .... Hardcode the values directly in your code: std::vector<std::vector<double>> csv_data{ { 0.2,....},{....}, ...}; Another possiblity is to include your text file as string. For details I refer you to this answer: https://stackoverflow.com/a/25021520/4117728. You basically would add...
69,208,079
69,208,731
After fork, execv communicates with the parent process when executing the target program
I know that the signal handler cannot be inherited when call execv in the child process of fork, so I wonder if the execv process can be piped to communicate with the parent process. As far as I know, pipe communication requires parenthood or a common ancestor. But I don't know if the pipe mechanism still works in exec...
I'm not sure if I fully understand your question, but I think you're trying to set up signal handlers in the child process, then call execv, with your signals handlers still ready ? You can't. Upon calling execv, the calling process is replaced by the executed program. Your file descriptor manipulation are preserved by...
69,208,445
69,208,571
Is there a way to call a template constructor from a specialized constructor?
Lets say I have this class: template <class T> class Test { Test(T* x); const T* const t; int i{0}; }; I want t to always be initialized with x: template <class T> Test<T>::Test(T* x) : t{x} {} And I have two specializations: template <> Test<Foo>::Test(Foo* x) : t{x} { i = 1; } template <> Test<Bar>::Te...
You can use a delegating constructor for this. You can create a private constructor, that takes the pointer for t, and an int for i. Then you can use that to set x and i, and run all of the shared code. That would look like: template <class T> class Test { public: Test(T* x) : Test(x, 0) { /*code for default case, ...
69,208,473
69,208,801
How to enter commands/(SSH password) within the output of a command when using system() in C++?
My objective is to connect to an ssh server and enter commands automatically using c++ and system. When running: #include<iostream> #include<string> #include<stdlib.h> using namespace std; int main() { string user = "user"; string forwarded = "0.tcp.ngrok.io"; string port = "00000"; string command = "ssh "+user+ "...
No, you can not. But perhaps you can use std::cin and std::cout for that, which I would NOT recommend. I assume you are looking for a library similar to paramiko which is, however, in python.
69,208,576
69,208,752
How to search a substring of a LPWSTR?
Is there any function that is used for searching a substring of LPWSTR? LPWSTR a_string = _T("abcdef"); if (a_string .find(L"def") != std::string::npos) { }
That initialization of a_string is invalid, LPWSTR can't be initialized pointing to a string literal, you need LPCWSTR. This being a glorified pointer to wchar_t, or more accurately a macro that will end up expanding to wchar_t*, it does not have member methods, it is not a class like std::string. You will need to do i...
69,209,070
69,209,828
Is there some std::count_if() for counting multiple different properties in a single scan?
Is there some std::count_if-like function for counting multiple different properties in a single scan? E.g. it might expect a tuple of function objects and return a tuple of ptrdiff_t. Or the passed function might return a tuple of bool.
You can use accumulate, as suggested: #include <array> #include <iostream> #include <numeric> #include <vector> int main() { std::vector<int> v{1,2,3,4,5,6,7,8,9,10}; // two properties, each returning a bool auto constexpr is_even = [](int x){ return x % 2 == 0; }; auto constexpr is_div_by_3 = [](int ...
69,209,072
69,214,787
Omnet++ fatal error: 'inet/common/INETDefs.h' file not found
I am trying to extent a mobility module in Inet 4.2 under Onmet++ v5.6, the issue is that I get the "fatal error: 'inet/common/INETDefs.h' file not found" error during importing the INETDefs.h file. #ifndef CustomizedMobility_H_ #define CustomizedMobility_H_ #include "inet/common/INETDefs.h" #include "inet/mobility/si...
Solved just wright click on the project, choose properties, then under omnet++ section choose MakeMake and click on the src folder. After that choose option from the right side section. then have a look at the following figure.
69,209,172
69,209,215
Do I need a .h for a class with only a main method in C++
I need to create 2 classes, with their respective .h and .cc, and then another class with a main, let's call them A, B and C, being the C class the one with the main. Given that the C class is used only to contain that main and doesn't need either instance or class variables, or other methods, do I need to create C.h o...
Well technically, you don't need headers ever, you could simply copy-paste declarations in every .cpp files. If you don't need a declaration in any other file, I'd suggest this is a good practice to place it in the relevant .cpp file to keep it private. This can be couple with a namespace { ... } or declare them as sta...
69,209,414
69,209,547
How to write function with rest/spred operator (from js) on c++?
How to write such function on C++? function executor (foo, ...args) { return foo(...args) } I don't understand how to declare template on C++
Your question is not really clear to me what you are asking, or what you are trying to do. Here's an example of an invoke template function that calls the passed function and passes in the arguments to the function's parameters. That seems to be what your code snippet is trying to do. The code is just for quick-and-di...
69,209,713
69,210,181
Converting a TCHAR to wstring
TCHAR path[_MAX_PATH+1]; std::wstring ws(&path[0], sizeof(path)/sizeof(path[0])); or TCHAR path[_MAX_PATH]; std::wstring ws(&path[0]); While converting a TCHAR to wstring both are correct? I'm asking just for clarification, I'm in doubt if I'm converting it correctly.
The code is problematic in several ways. First, std::wstring is a string of wchar_t (aka WCHAR) while TCHAR may be either CHAR or WCHAR, depending on configuration. So either use WCHAR and std::wstring, or TCHAR and std::basic_string<TCHAR> (remembering that std::wstring is just a typedef for std::basic_string<WCHAR>)....
69,209,803
69,213,264
Launch file to start ROS Services?
I created ROS Service with a client and server node. I created a ROS Service that pass the IMU sensors values from the Server to Client. And Im able to call the server and client node and get the values. But when call them with the launch file I got zero Here the server node #include "ros/ros.h" #include <sen...
The reason you're getting 0 back is because the client immediately calls the service on startup. Since it also immediately returns the last cached value and they're both started at almost the same time via roslaunch this means there's essentially no way a message will be received on the topic by the service is called. ...
69,209,842
69,209,929
C++ Find & Change Value in Map
I've scoured but not finding a solution; this is part of a homework assignment so looking more for tips/explanation than outright solution. Problem: I am parsing a file and extracting key elements into a map. I've declared my standard non-const map as : map<label,element>. In a second phase of the program, I am needing...
you made a simple mistake which is el.second == value_i; - you didn't assign value for second, you checked if its equal value_i. If your compiler didn't give you any warning about it, I recommend setting a higher level of warnings ( you can read online on how to do it on probably every compiler), that way you won't mis...
69,209,852
69,211,855
C++ How to correctly print value of templated type from module
I have a vector class inside a module: // other_library.cpp module; #include <iostream> export module mylibrary.other; export template<class T> class Vector { private: T x, y; public: Vector(T _x, T _y) : x(_x), y(_y) {} void Write() { std::cout << "Vector{" << x << ", " << y << "}\n"; }...
So it seems that there are still some challenges with modules. Example: I cannot use std::endl inside the Vector.Write member function. A solution is to precompile the iostream standard header, which can be done like this: g++-11 -std=c++20 -fmodules-ts -xc++-system-header iostream The precompiled module will be store...
69,210,118
69,215,395
Linking .res file with an Executable (CMake)
i've been trying to link compiled .res file with CMake for some time, i searched internet but there is no much info bout it. I tried adding this into my CMakeList.txt SET(RESOURCE_FILE scac.res) file(GLOB src_files "${RESOURCE_FILE}" ADD_EXECUTABLE( FOO ${FOO_SRCS} ) TARGET_LINK_LIBRARIES( FOO ${FOO_LIBS} ) SET( FOO_L...
After 6 hours, problem is solved just added "${CMAKE_CURRENT_SOURCE_DIR}/res.rc" into line add_executable(${EXAMPLE_TARGET} ${EXAMPLE_HEADER_FILES} ${EXAMPLE_INLINE_FILES} "examples/${EXAMPLE_SOURCE_FILE}" to finally get add_executable(${EXAMPLE_TARGET} ${EXAMPLE_HEADER_FILES} ${EXAMPLE_INLINE_FILES} "examples/${EXAM...
69,210,212
69,210,494
Double linked list in Data Structures and Algorithms in c++
So i saw this code fragment in Data Structures and Algorithm in c and c++: class DLinkedList { // doubly linked list public: DLinkedList(); // constructor ~DLinkedList(); // destructor bool empty() const; // is list empty? const Elem& front() const; // get front element const Elem& back() const; // ...
you use protected when you don't want the API to view certain methods but do want to access the method from the class and its subclasses(outside or within package) and classes from the same package the reason add() and remove() are protected is to provide data abstraction and to prevent unauthorized personnel from usin...
69,210,475
69,215,787
Using std::span with buffers - C++
I am exploring a possibly safer and more convenient way to handle buffers, either with fixed size known at compile time size known at runtime What is the advice of using static extent vs dynamic extent? The answer may seem obvious but I got confused when testing with examples below. It looks like I can manipulate ext...
(the part on runtime error was removed from the question) In a nutshell: use dynamic extent, and initialize in the simplest way, like: wchar_t buffer1[appconsts::buffersize]; ir = FormatBuffer(buffer1); wchar_t* buffer2 = new wchar_t[appconsts::buffersize]; ir = FormatBuffer({buffer2, appconsts::buffersize}); // won’t...
69,210,489
69,213,038
Using base class constructor in derived class contructor
Let's say that I want to make use of base class constructor in order to create derived class objects. This is my approach on how to do it: class base { int x, y, z; public: base(int x, int y, int z) : x(x), y(y), z(z) { std::cout << "base class constructor called\n"; ...
Adding an appropriate base class constructor 'call' in the initialization list for your derived class constructor is perfectly acceptable and normal. (In fact, for the example that you've shown, omitting that constructor from the initialization list will cause the code to be ill-formed: the compiler will then attempt t...
69,210,553
69,211,443
How do I change variables in main function that are in a struct?
I'm quite new to C++ and coding in general and I have been stuck on this bug for forever it seems. My eventual goal is to create a tic-tac-toe algorithm but at the moment I am having an issue with using struct variables outside of the struct. I have tried using classes and structs, using static etc., I know I am missin...
I have made some changes and below is the complete working program. You can see that depending on the user input the corresponding Pos data member is changed. #include <iostream> #include <string> //Class to monitor board positions struct boardPos { bool Pos1 = 0; bool Pos2 = 0; bool Pos3 = 0; bool Po...
69,211,027
69,214,336
Problem with multi-threading and waiting on events
I have a problem with my code: #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <windows.h> #include <string.h> #include <math.h> HANDLE event; HANDLE mutex; int runner = 0; DWORD WINAPI thread_fun(LPVOID lpParam) { int* data = (int*)lpParam; for (int j = 0; j < 4; j++) { //this loop necessary in...
As we found out in the comments section, the problem was that although the event was created in the initial state of being non-signalled event = CreateEvent(NULL, TRUE, FALSE, NULL); it was being set to the signalled state immediately afterwards: SetEvent(event); Due to this, at least on the first iteration of the lo...
69,211,303
69,211,459
Why does the following program - passing c string to function - not produce the desired output?
I have a simple question C++ (or C). Why does the following program, passing c string to function, not produce the desired output? #include <cstdio> #include <cstring> void fillMeUpSomeMore( char** strOut ) { strcpy( *strOut, "Hello Tommy" ); } int main() { char str[30]; //char* strNew = new char[30]; ...
char ** is a pointer to a pointer to a character. This means, if it is not a null pointer, it should be the address of some place in memory where there is a pointer. char str[30] defines an array of 30 char. &str is the address of that array. There is no pointer there, just 30 char. Therefore, &str is not a char **. So...
69,212,169
69,212,191
How does happen the destruction of variables with a goto statement in C++?
#include <iostream> using namespace std; int main() { if (true) { int b = 3; label_one: cout << b << endl; int j = 10; goto label_one; } } In the code above goto jumps to label_one, making the variable j be destroyed and reconstructed in each cycle. But what happens to the b...
As the quoted text says, a variable is destroyed during the goto only if it is in scope at the point of the goto statement, but not in scope at the destination label. b is in scope at both points, so it is not destroyed. Only j is destroyed.
69,212,217
69,212,342
How Can I Write a C++ Template Which is Inferred From a Function Argument?
I'm trying to write a C++ function which generates a vector from two calls to an argument function. The argument function accepts an integer pointer and a pointer to an array of elements. If called with nullptr for elements, it will fill the integer with how many elements it has to produce. Then on the second call, it ...
A simple-ish way to do this is to delay the lookup until you are within the function by having it return auto. Something along these general lines: // The stolen function_traits struct...thing template<typename T> struct load_array_cb_traits; template<typename Ret, typename Arg2> struct load_array_cb_traits<std::funct...
69,213,150
69,213,872
std::vector of Derived class instances whose Bases contain a (raw) pointer
Say I had the following structure class BaseKernel { // ....... } class DerivedKernel : public BaseKernel { // ....... } class A { public: A(BaseKernel* kernel) : kernel(kernel) {} A(const A& a) : kernel(a.kernel) {} ~A() {delete kernel;} BaseKernel* kernel; } class B : public A { public: ...
I see some problems. I'll see if I can understand your real question. Let's start with this: class A { public: A(BaseKernel* kernel) : kernel(kernel) {} A(const A& a) : kernel(a.kernel) {} ~A() {delete kernel;} BaseKernel* kernel; } This is bad. If you use your copy constructor, you'll end up deletin...
69,213,287
69,215,058
merge sort algorithm: std::out_of_range
I am currently making a merge sort algorithm but when i run the code i get an error says "terminate called after throwing an instance of 'std::out_of_range". This is my code. template<typename T> void merge(std::vector<T> &vec, int l, int m, int r){ int i = l; int j = m + 1; int k = l; //CREATE TEM...
A few issues in your merge function (which you can spot easily through debugging): vec.at(i) <= m compares a value with an index. These two are unrelated. So change: while(vec.at(i) <= m && j <= r){ with: while(i <= m && j <= r){ The final loop starts with p = 1 which is an index that in many cases is out of the ...
69,213,313
69,213,430
Pointer to a Superclass object may serve as pointers to subclass objects. But can't call memeber functions of the subclass. why?
I am enrolled in a C++ course, where i have the following code snippet: class Pet { protected: string name; public: Pet(string n) { name = n; } void run() { cout << name << ": I'm running" << endl; } }; class Dog : public Pet { public: Dog(string n) : Pet(n) {}; vo...
In C++, the types and names of variables at any point is what the compiler permits itself to know. Each line of code is checked against the types and names of variables in the current scope. When you have a pointer to a base class, the type of the variable remains pointer to the base class. The actual object it is poi...
69,213,645
69,228,455
how do I forward the templates arguments onto the std::make_unique when creating policy based class?
Lets assume I'm using policy based templates design pattern (see https://en.wikipedia.org/wiki/Modern_C%2B%2B_Design). I'm having some issue related to how would I use std::make_shared (or std::make_unique for that matter) for creating new type Bar, that has some optional template arguments. If I don't want to change d...
Figured this out. It's turns out the syntax: auto bar = std::make_unique<Bar<Policy2, Policy3>>(); works after all (on C++20, using MSVC v16.10.2). It requires the following declaration to work: std::unique_ptr<Bar<T,V>> _bar; in addition I had to provide on CPP this as well (to avoid linker error): template class Ba...
69,213,753
69,214,034
Understanding segmentation fault in core dump on NULL pointer check
I am having difficulty understanding how this segmentation fault is possible. The architecture of the machine is armv7l. The core dump: Dump of assembler code for function DLL_Disconnect: 0x6cd3a460 <+0>: 15 4b ldr r3, [pc, #84] ; (0x6cd3a4b8 <DLL_Disconnect+88>) 0x6cd3a462 <+2>: 00 21 movs r...
The assembly code resolves the address of global variable gl_pClient using dll relocations, which are loaded using program-counter-relative addressing. Then the code loads from that address and crashes. It looks like the relocations got corrupted, so that the resolved address is invalid. There isn't much else can be sa...
69,214,107
69,214,194
How do you declare a generic type of an expression in a `requires` constraint?
I may be asking a wrong question here, but what exactly am I doing wrong that it causes the compiler to think that the constraint I'm expecting on pop method of the stack is std::same_as<void, T>? #include <concepts> #include <stack> template <typename S, typename T> concept generic_stack = requires(S s, T t) { s....
This is because stack.pop() returns void, as per documented in std::stack::pop. The constraint is not right, you should check for top instead: template <typename S, typename T> concept generic_stack = requires(S s, T t) { s.push(t); { s.top() } -> std::same_as<T const&>; };
69,214,574
69,215,279
Why does std::function not work with function templates?
I am starting to work with templates and I am trying to figure out why the following does not work. class testclass1 { public: template <typename...Ts> using TFunc = std::function<void(Ts*...)>; template <typename...Ts> void SetFunction(TFunc<Ts...> tf) { // Do something } }; ...
it seems that you cannot use std::function with template functions No, the issue has nothing to do with std::function. The problem is the failed deduction of the template parameter pack. Normally, when you specify all template arguments explicitly, no deduction is performed. tc1.SetFunction<std::string, double>(s...
69,214,646
69,230,979
C++ Is it a bad idea to initialise class members by assigning them other constructor initialised class members?
I discovered a query way of initialising a class member q by assigning it to a different class member that is initialised through the constructor i: class test{ public: test(int c) : i(c) { } int i; int q = i; }; int main() { std::cout << test(1).q << std::endl; //outputs 1 } However if I swap ar...
Yes, you've outlined the conditions of failure. It's not hard to imagine someone unintentionally breaking your code due to reordering. If you wanted to do something like this, it's best to assign both in the constructor from the input source. test(int c) : q(c), i(c) {} This has less confusion about initialization or...
69,214,921
69,215,089
Array of Arrays for use in a For loop
array<string, 7> month31={"January","March","May","July","August","October","December"}; array<string, 4> month30 ={"April","June","September","November"}; array<string, 1> month29 = {"February"}; array<string, 1> month28 = {"February"}; array<string, 4> months= {month31,month30,month29,month28}; I know in python thi...
You'll likely be better off using std::vector<std::string> for your (individual) month lists and then a std::array< std::vector<string> > for your composite (note that a std::array of std::array<string, n> would require the element arrays to all be the same length). Here's a short, illustrative example: #include <iostr...
69,214,987
69,215,138
Initialization order: An array with a separate pointer to that same array
I have a line of code that declares a static array of char, like so: char buf[7]; I would like to traverse this array using a pointer, but buf itself obviously can't be incremented or decremented. My question is basically, is this legal, or is this undefined behavior: // Does this guarantee ptr == buf? char buf[7], *p...
is this legal Yes is this undefined behavior No would the compiler be allowed by the C++ standard to reorder these declarations so that ptr is initialized to some junk value? No, it initializes ptr with the char* that buf decays into. If a compiler would be allowed to initialize them in the other order, it would ...
69,215,014
69,215,325
Global variable pointer vs local variable pointer
so I understand that global variables are evil, and programmers should avoid them. However, I have been doing some studying regarding potential vulnerabilities behind it, so that is the reason why I'm using it at the moment. I have this toy example: #define MAX_LENGTH 8 int counter = MAX_LENGTH; int *size; int main(i...
Think of a pointer as a place in memory meant to store an address so that int *test, a pointer to an int, stores an address containing an int. When you first declare it, int *test, test has garbage as its value since you didn't initialize it. You were lucky that the garbage happened to be the value of "some address". W...
69,215,139
69,215,627
How do I incorporate the getline function so my program will read data from the file correctly?
I have this code as my default constructor. I am trying to read all the values correctly from my file (census2020_data.txt). The file contains letters and numbers, made up of states and a value representing population. One of the values in the data file has spaces (it is multiple words) and it makes my program not read...
operator>> stops reading on whitespace, which is not what you need in this case. I would suggest using std::getline() to read an entire line, then use std::string::rfind() to find the last space character before the numbers, and then use std::string::substr() to split the text from the numbers. For example: state_clas...
69,215,214
69,215,441
Loop and object intialization question (C++)
I'm trying to use a loop to infinitely create objects from a class unless a specific input is entered. I think I have everything done except the loop. I know how to initialize one object in my main function, but I'm stuck as to how to use a loop to do this infinitely. My code is below. Driver File: #include <iostre...
You could add a do ... while loop around your code in main and store the squares in a vector<square>. Example: #include <limits> // you use numeric_limits from this header #include <utility> // move #include <vector> // vector int main() { std::vector<square> squares; std::string answer; do { squ...
69,215,239
69,216,015
Explicitly using the namespace of the class attributes in methods to make code more readable?
This question is about writing good code in terms of readability/best practices. Especially when working with a larger class and methods, I would prefer to be verbose when using attributes of the class. A simple example would be changing the value of an attribute through a method. In python, this would be done like "se...
In Python, self. is critical because Python is a dynamic language. Imagine that self. wouldn’t be required: class A: def f(): x = 42 # whoops, is that a local or a member variable? del x # what is deleted here? return x # totally OK if there was another x in scope? (the same problem effectively kills wit...
69,215,464
69,233,247
Pybind11: How to assign default value for a struct member variable?
I am trying to create python bindings for the below struct example { int a = 1; int b = 2; }; This is what I have so far PYBIND11_MODULE(example_python, m) { py::class_<example>(m, "example") .def_readwrite("a", &example::a) .def_readwrite("b", &example::b); } when I checked in python, both a and b are...
Your code doesn't compile, at least on my machine, because you didn't bind any constructor. However, if you do so then the default values become populated (because that's part of what a constructor does!). In other words, just use this: PYBIND11_MODULE(example_python, m) { py::class_<example>(m, "example") .def(...
69,215,509
69,215,562
Why we need std::partition_point whereas we can use std::find_if_not algorithm?
Here is my possible implementation of the algorithm std::partition_point is : template <typename In_It, typename FUNC> In_It partitionPoint(In_It b, In_It e, FUNC pred){ int len = e - b; while (len > 0){ int half = len >> 1; In_It middle = b + half; if( pred(*middle) ){ b = ...
std::find_if_not has O(N) complexity as it does a linear traversal. std::partition_point on the other hand has O(logN) complexity as it takes advantage the fact that the set is partitioned and does a binary search to find the element. Depending on the situation, this could be a big performance win.
69,215,568
69,390,107
How can i count percentage CPU for each process by PID
I am trying to code task manager and i stuck with %CPU for each process dy PID. I wrote something like, that: static float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks) { static unsigned long long _previousTotalTicks = 0; static unsigned long long _previousIdleTicks = 0; u...
This is how i get_CPU in percent. I use hash_map in order to have PID-time connection static to update it. First time usage get_cpu_usage(int pid) returns zero every time,but with each next usage it will be more and more accurate(I use it with 0.5 sec period). static int get_processor_number() { SYSTEM_INFO...
69,215,862
69,216,007
How can solve vs2019 C++ template function trait problem?
I found a solution on Understanding how the function traits template works. In particular, what is the deal with the pointer to member function to get type of function parameters types by using templates. But following code gets "error C2760: syntax error: unexpected token '<', expected 'declaration'" on VS2019. It w...
You need to add the template keyword to make argument a dependent template name: template < typename _ChClass, typename _ChFunction> void ChTemplate( _ChClass cl, _ChFunction fn) { typename function_traits<_ChFunction>::template argument<0> a; // ^^^...
69,215,985
69,230,368
Why is `std::is_constant_evaluated()` false for this constant-initialized variable?
Note 2 to [expr.const]/2 implies that if we have a variable o such that: the full-expression of its initialization is a constant expression when interpreted as a constant-expression, except that if o is an object, that full-expression may also invoke constexpr constructors for o and its subobjects even if those object...
The full quote here is A variable or temporary object o is constant-initialized if (2.1) either it has an initializer or its default-initialization results in some initialization being performed, and (2.2) the full-expression of its initialization is a constant expression when interpreted as a constant-expression, ex...
69,215,991
69,216,120
Where is my memory leaking in my program and how would I fix it?
so i'm working on an assignment for my c++ class and I am attempting to do different functions using my class with arrays. It works mostly until the overload operator where the memory leak seems to happen. #include <iostream> #include <algorithm> // for std::copy_n using namespace std; class MyArray{ private: double...
The problem is that your class has no copy constructor. MyArray(const MyArray & a2, int n) is not a copy constructor because it requires an additional argument, n. Which you don’t actually need as you have a2.n. Also, you leak a in push_begin, and forget to resize it at all in push_end (as well as in setN but you don’t...
69,216,077
69,216,306
Initializing multi-dimensional std::vector without knowing dimensions in advance
Context: I have a class, E (think of it as an organism) and a struct, H (a single cell within the organism). The goal is to estimate some characterizing parameters of E. H has some properties that are stored in multi-dimensional matrices. But, the dimensions depend on the parameters of E. E reads a set of parameters fr...
Using push_back() should be fine, as long as the vector has reserved the appropriate capacity. If your only hesitancy to using push_back() is the copy overhead when a reallocation is performed, there is a straightforward way to resolve that issue. You use the reserve() method to inform the vector how many elements the ...
69,216,803
69,219,384
SDL_Log doesn't seem to support %g and %e specifiers
I'm using SDL 2.0.12 with Visual Studio 2013, and I'm seeing this: SDL_Log("%f", 1.0); // fine SDL_Log("%g", 1.0); // no luck; prints blank line Do I need to switch to a newer/older version of SDL or something?
SDL_Log delegates to SDL_vsnprintf. There are three possibilities: #if defined(HAVE_LIBC) && defined(__WATCOMC__) This seems to check for the Watcom C compiler. Not for you. #elif defined(HAVE_VSNPRINTF) This case delegates to your compiler's implementation of vsnprintf if that symbol was defined at compilation time....
69,216,934
69,217,518
Unable to use std::apply on user-defined types
While implementing a compressed_tuple class for some project I'm working on, I ran into the following issue: I can't seem to pass instances of this type to std::apply, even though this should be possible according to: https://en.cppreference.com/w/cpp/utility/apply. I managed to reproduce the issue quite easily, using ...
So my question is whether this is expected behavior and it's simply not possible to use std::apply with user-defined types? No, there is currently no way. In libstdc++, libc++, and MSVC-STL implementations, std::apply uses std::get internally instead of unqualified get, since users are prohibited from defining get un...
69,217,027
69,217,104
How to overload the = in c++ in order to use it when creating an object?
I have created a class that is meant to be initialized also with an initializer list: #include <iostream> #include<vector> using namespace std; class A{ public: A() = default; A(vector<int> values){ a1 = values; } A& operator=( vector<int> values){ a1 = values; return *this...
You should probably use initializer lists instead of vector in args. The following seems to work: #include <iostream> #include<vector> using namespace std; class A{ public: A() = default; A(initializer_list<int> values){ // <<<<<<<<<<< a1 = values; } A& operator=(initializer_list<int> values){ // <<<<<<<<...
69,217,219
69,217,346
c++ stringstream read doesn't seem to read the whole buffer
I have the following code: https://godbolt.org/z/9aqqe5eYh #include<string> #include<sstream> #include<iomanip> #include<iostream> int main() { std::string line = "fa0834dd"; for(int i = 0; i < line.length(); i += 2) { std::stringstream ss; std::uint8_t byte; ss << std::hex << line.substr(i, 2); ...
stringstream is not eligible for parsing the character representation into a value in byte. You may use something lik strtol to actually parse the string into value. #include<string> #include<sstream> #include<iomanip> #include<iostream> int main() { std::string line = "fa0834dd"; for(int i = 0; i < line.length()...
69,217,539
69,231,382
Problem with GLFW linking, as it used in SharedLib (DLL)
Environment : Visual Studio 2019. I'm developing an Engine as a SharedLib (DLL) and I made an example that uses this DLL so I can launch the Engine. at this stage I have to add GLFW library to the engine, so I added GLFW as a submodule (git) to my project and built this library as a StaticLib (.lib) with static runtime...
Thank you Everyone for your help. I got relatively a solution and I want to share it with you in case someone fall in the same situation. Short Answer: I converted the GLFW from static library to shared library while the building, and the linking errors just gone. Long Answer I wrote a Premake script to generate th...
69,217,597
69,218,017
How to create an array from an input txt file
I am new to c++ and fstream (infile) and wanted to know how data is read from a txt file and how can I put that data in an array. Basically I am trying to make this korean game called omok. where the number of times a player gets their move 4 times simultaneously either vertically, horizontally or diagonally. Input fro...
In any software project one of the key aspect you have to think about are your data structures: what do you need to store, what is the best format to store it, etc. Very often the data structures will define a lot of the resulting performance and clarity of your software. In your case you decided to use char**, which...
69,218,343
69,236,342
Pybind11: How to create bindings for a function that takes in a struct as an argument?
Please see below C++ code that I am trying to create python bindings for struct Config { int a; int b; }; void myfunction(const Config &config); Here is what I have so far, PYBIND11_MODULE(example, m) { py::class_<Config>(m, "Config") .def_readwrite("a", &Config::a) .def_readwrite("b", &Config::b); m...
As hinted by @eyllanesc, the problem will be solved by adding a default constructor: PYBIND11_MODULE(example, m) { py::class_<Config>(m, "Config") .def(py::init<>()) .def_readwrite("a", &Config::a) .def_readwrite("b", &Config::b); m.def("myfunction", &myfunction); } import example config = example.Co...
69,218,470
69,218,775
How to find a list that only contains a certain field and no other fields?
How to find a list that only contains a certain field and no other fields? eg: [a, b, c, d] [a, b, c] [a, b] find the list containing only a and b: [a, b]
Here I have implemented what you need. The input is 2d vector, which contains the input that you have mentioned as three lists. The check vector contains the list which you want to check if exists in the input. #include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector<vector...
69,218,661
69,219,047
" undefined reference to `toppers::recordTop' " error?
My problem was: Write a program that has a class Student to store the details of students in a class. Derive another class Toppers from the Student that stores records of only top 3 students of the class Here, In the inherited class toppers , I have take taken a data member(recordTop[3]) of derived class(Toppers) and i...
I just changed your static topper recordTop[3] to students recordTop[3]. The code works as you might expect. Instantiation of a class member inside the class somehow creates infinite recursion like conditions. I have added a couple of \ns to see all statements clearly. #include<iostream> #include<string> using namespac...
69,218,804
69,218,922
Difference between Reference to a const Callable and Reference to a Callable in C++
I want to know what happens if we have a function parameter that is a reference to a const function as shown below. Version 1 int anotherFunc() { std::cout<<"inside anotherFunc"<<std::endl; return 5; } void func(decltype(anotherFunc) const &someFunction)//note the const here { std::cout<<"inside func"<<std:...
Yes, the const qualifier is ignored when added to an alias for a function type. From the standard, [dcl.fct]/7: The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored. [Note 4: A function type t...
69,219,832
69,220,159
Unresolved overloaded function type in std::transfrom
I am trying to write an overload function for both double and vector<double>. I just did the following: constexpr double degrees(double val) { return v * M_1_PI * 180.0; } std::vector<double> degrees(const std::vector<double>& val) { std::vector<double> out; out.reserve(val.size()); std::transform(val.beg...
I don't want to believe that the asker didn't know they are defining two functions with the same name degrees, so I'll give another shade to my answer. How is it possible, in this call std::transform(val.begin(), val.end(), std::back_inserter(out), degrees); that degrees is not known? I mean, std::transform should try...
69,220,040
69,220,283
Lambda to compose lambdas
I tried to write a function in C++ which can compose a variable amount of lambdas. My first attempt kind of works (even though I suspect it isn't perfect) template <typename F, typename G> auto compose(F f, G g) { return [f, g](auto &&...xs) { return g(f(std::forward<decltype(xs)>(xs)...)); }; } template <type...
You can use the y combinator to make a recursive lambda. template<class Fun> class y_combinator_result { Fun fun_; public: template<class T> explicit y_combinator_result(T &&fun): fun_(std::forward<T>(fun)) {} template<class ...Args> decltype(auto) operator()(Args &&...args) { return fun_(s...
69,220,047
69,220,796
Is there a way in C++ to make scoped global variables?
Let's say I have a program which uses n big modules: A) Network/Communication B) I/O files C) I/O database D) GUI E) ... Of course, a list of modules could be bigger. Let's say I want to have some global variable, but with a scope limited to a single module. As an example, let's say that I/O database module will consis...
You don't need globals for that, I strongly advise you to learn about dependency injection. Basically you have one "factory" module. And each module has an interface on you can inject an interface that has getters to access the centralized data. (e.g. members of a n instance of a class). This also allows you to test th...
69,220,608
69,221,378
How to debug C++-Program which triggers internal bug in gdb?
In one of my C++-projects I found an issue related to a linked library which results in a segfault directly after starting the compiled executable. I tried to dive into the issue using gdb, but it fails with the output: ../../gdb/dwarf2/read.c:1857: internal-error: bool dwarf2_per_objfile::symtab_set_p(const dwarf2_per...
Most likely this is already fixed gdb bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28160. It has Target Milestone 11.1, so update to a latest version of gdb which is 11.1 now. It should be fixed in that version.
69,221,161
69,254,554
Why is the concept of vacuous initialization necessary?
The concept of vacuous initialization is introduced and used at [basic.life/1], and it does not seem to be used anywhere else in the C++ standard: The lifetime of an object or reference is a runtime property of the object or reference. A variable is said to have vacuous initialization if it is default-initialized and,...
The current draft standard, quoted by the OP, has reached its state via CWG issue 2256 (2256. Lifetime of trivially-destructible objects) and P1787R6 (P1787R6: Declarations and where to find them), after which, if any, the term (rather than "the concept") can be used to collective refer to cases where "initialization" ...
69,221,487
69,227,482
MSVC - Using namespace directive in caller of generic lambda leaks into the lambda's body
Consider the following toy code: #include <boost/hana/transform.hpp> #include <range/v3/view/transform.hpp> auto constexpr f = [](auto) { using namespace ranges::views; auto xxx = transform; }; void caller() { using boost::hana::transform; f(1); } It compiles fine with GCC and MS' compiler, which mea...
It is an MSVC bug that has to do with generic lambdas. A minimal example is void foo() {} namespace B { void foo() {} } auto moo = [](auto) { foo(); }; int main() { using namespace B; moo(1); } It reproduces with c++17 and c++20 settings. MSVC is known to have non-conforming handling of template instant...
69,221,539
69,229,855
Does GetKeyState() detect if the key is being released?
Is there a way to detect if the key is being released using GetKeyState()? I read about it, and it only has 2 states, Toggled 0x8000 and Pressed 0x01. I want something like this: short Input(int Key, int Mode) { if (Mode == KEY_RELEASE) if (GetKeyState(Key) & KEY_PRESS) //Wait for the key to be releas...
GetKeyState returns information about the key state of the current input queue (your thread and attached threads). You can get similar information for all the keys with GetKeyboardState. Those two functions should only be used in response to some event, you should not be polling over and over to detect changes. The bes...
69,221,619
69,230,429
Transform functor struct to take a different argument
I got the following (unconstrained quadratic objective) defined borrowing matrices and vectors from the Eigen-library: #ifndef QP_UNCON_HPP #define QP_UNCON_HPP #include "EigenDataTypes.hpp" template <int Nx> struct objective { private: const spMat Q; const Vec<Nx> c; public: objective(spMat Q_, Vec<Nx> c...
I want to create a functor struct p_objective that works as a lambda for struct objective. If you have already written the objective, you can also similarly make a p_objective. Following is an example. Here is the (demo) template <int Nx> class p_objective { objective<Nx> f; const spMat x; const Vec<Nx> p...
69,221,638
69,221,677
Find max value in std::vector of structure of specified variable
I have vector of structure described below: struct Point { double x,y; }; And now I have vector<Point> which contains about 2000 elements. I want to find element which contains maximum value of variable y in Point. I know there is std::max_element but I don't know if it works with variables stored in structures in...
I don't know if it works with variables stored in structures inside vector. Yes it does. Use a custom comparator: auto it = std::max_element(v.begin(), v.end(), [](const auto& a,const auto& b) { return a.y < b.y; ...
69,221,887
69,221,946
How does sorting algorithms sort containers and ranges of floats?
Since comparing floats is evil then if I have a container of floats and I sort it using some standard library sorting algorithm like std::sort then how does the algorithm sort them? std::vector<float> vf{2.4f, 1.05f, 1.05f, 2.39f}; std::sort( vf.begin(), vf.end() ); So does the algorithm compare 1.05f and 1.05f? Doe...
So does the algorithm compare 1.05f and 1.05f? Yes Does it internally uses something like: std::fabs( 1.05f - 1.05f ) < 0.1;? No, it uses operator <, e.g. 1.05f < 1.05f. It doesn't ever need to compare for equality, so the comparison using epsilon value is not needed. Does this apply too to containers of doubles? ...
69,221,924
69,222,165
How to make restrictions about the derived class?
Consider the curiously recurring template pattern, can you prevent the following unsafe code to compile? template <class Derived> class Base { public: void foo() { // do something assuming "this" is of type Derived: static_cast<Derived*>(this)->bar(); } }; // This is OK class A: public Base...
You can make Base<D> constructor (or destructor) private and friend D. You'll need to add A()=default; B()=default; publicly, but when you do, B can't be created. Which is good.
69,222,373
69,223,055
Fastest way for wrapping a value in an interval
I am curious about the ways to wrap a floating-point value x in a semi-closed interval [0; a[. For instance, I could have an arbitrary real number, say x = 354638.515, that I wish to fold into [0; 2π[ because I have a good sin approximation for that range. The fmod standard C functions show up quite high in my benchmar...
Assuming that the range is constant and positive you can compute its reciprocal to avoid costly division. void fast_fmod(float * restrict dst, const float * restrict src, size_t n, float divisor) { float reciprocal = 1.0f / divisor; for (size_t i = 0; i < n; ++i) dst[i] = src[i] - divisor * (int)(src[i] * re...
69,222,391
69,224,317
multiple optional members in class template without overhead
If I want a class with an optional member, I'm using template specialization: template<class T> struct X { T t; void print() { cout << "t is " << t << '\n'; } }; template<> struct X<void> { void print() { cout << "without T\n"; } }; This is nice as there is no runtime overhead and little code duplication. Howeve...
With an optional_member class, template <class T> struct OptionalMember { T t; static constexpr bool has_member = true; }; template<> struct X<void> { static constexpr bool has_member = false; }; you might use inheritance (as long as their types differ) and EBO to avoid extra memory. template<class T1, cl...
69,222,631
69,266,317
46: regex error 17 for `(dryad-bibo/v)[0-9].[0-9]', (match failed)
I'm trying to determine the mime-type for several types of files using libmagic and the following bit of code: auto handle = ::magic_open(MAGIC_MIME_TYPE); ::magic_load(handle, NULL); // Both of these fail with the same error // file_path being a const char* with the path to the file. auto type2 = ::magic_file(handle,...
Very dissatisfying answer, but it was linking against GoogleTest causing this error somehow, not even running any tests, just linking against it. I switched to using Catch2 instead and the issue was resolved.
69,222,691
69,298,714
C++: Get the last week day of any month
i am working on a code to parse cron format After going through the different syntax i got stuck on the 'L' operator, specifically on the '3L' which will give me the last Wednesday of the month (e.g the last Wednesday of September 2021 is going to be 29th ) the number 3 is the number of day : 0 = Sunday 1 = Monday . . ...
I found a solution for my problem and I want to share it with you, maybe someone can find it helpful. I mentioned in my question that i want to get the day of month of the last weekday of any month. First, in the cron format, if you want to specify that you could write it like this: "0 14 10 ? SEP 3L ?" this means, exe...
69,223,831
69,223,897
Problems with Glm functions
Why does this code compile [[nodiscard]] glm::mat4 rotationX(double theta) { return glm::rotate(glm::mat4(1.0), static_cast<float>(theta), glm::vec3(1.0, 0.0, 0.0)); } and this one not [[nodiscard]] glm::mat4 rotationX(double theta) { return glm::rotate(glm::mat4(1.0), theta, glm::v...
When using glm::rotate with vec3 and mat4, the type of theta must be float, because the element type of mat4 and vec3 is float: typedef mat<4, 4, f32, defaultp> mat4; typedef vec<3, float, defaultp> vec3; The corresponding double precision data types are damt4 and dvec3: typedef mat<4, 4, f64, defaultp> dmat4; ty...
69,224,065
69,263,374
"undefined reference" and includes not found when using OpenCV in C++
I'm very newbie with c++ and I need some help with libraries Here's the case, This simple code: #include <opencv2/objdetect.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/videoio.hpp> #include <iostream> int main() { cv::CascadeClassifier eye_detection; return 1; } compiling ...
Finally I figured it out, I created the CMakeList file as the library website says and still didn't worked, so I decided to uninstall my package from my system's package manager and installed it manually downloading the code and compiling it with cmake, and it did work now, even though I changed nothing (it might just ...
69,224,093
69,224,292
Structs without ifdefs in C or C++
There are some C projects with structs full of ifdefs (for ex. WolfSSL https://github.com/wolfSSL/wolfssl/blob/bb70fee1ecff8945af8179f48e90d78ea7007c66/wolfssl/internal.h#L2792) struct { int filed_1; int field_2; #ifdef SETTING_A int filed_b; #endif #ifdef SETTING_B int field_b; #endif } The reason is to reduc...
You can do it in C++20 with [[no_unique_address]] and some chicanary. This isn't guaranteed result in smaller types however, so I still suggest you use the #defines template<typename> struct Empty {}; template<typename T, bool enable, typename uniquer> using MaybeEmpty = std::conditional_t<enable, T, Empty<uniquer>>; ...
69,224,905
69,226,384
Inheritance and accessing attributes
I am learning OOP in C++, and I have written this piece of code to learn more about inheritance. #include<bits/stdc++.h> using namespace std; class Employee { public: string name; int age; int weight; Employee(string N, int a, int w) { name = N; age = a; weight = w; ...
There are 2 solutions(straightforward) to this. Solution 1 Replace the class keywords for both the Employee and Developer class with the keyword struct. Note even if you replace class keyword for Developer with struct and leave the class keyword as it is for Employee then also this will work. Solution 2 Add the keyword...
69,225,287
69,226,908
Pointer issues when upgrading to openSSL 1.1.1
I was using openSSL 1.0.2 and decided to upgrade to version 1.1.1k. However, I have some problems with some pointers: X509_STORE_CTX *vrfy_ctx = X509_STORE_CTX_new(); X509_STORE_CTX_init(vrfy_ctx, store, cert_x509, NULL); if(X509_verify_cert(vrfy_ctx) != 1) { if(ignore_date) { ...
Many structures are opaque in OpenSSL 1.1.1, which means you are not allowed to dive into the structure internals to access values. Instead you need to use accessor functions: Replace any instances of vrfy_ctx->error with X509_STORE_CTX_get_error(vrfy_ctx) Replace any instances of pkey->type with EVP_PKEY_id(pkey). Re...
69,225,503
69,225,804
how to generate the same random number in two different environments?
I compiled exactly the same code that generate random numbers in two different environments ( Linux and visual studio ). But I noticed that the outputs are different. I searched online and understand that the two implementations generate different random numbers. But I need the Linux to generate the same random numbers...
You can use a the mersenne twister it has reproducable output (it is standardized). Use the same seed on 2 machines and you're good to go. #include <random> #include <iostream> int main() { std::mt19937 engine; engine.seed(1); for (std::size_t n = 0; n < 10; ++n) { std::cout << engine() << st...
69,225,658
69,226,143
Why am I getting the last sum as largest sum of subarray?
#include <bits/stdc++.h> using namespace std; void printpair(int ar[], int n) { int largestsum = INT_MIN, currentsum = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { currentsum = 0; largestsum = INT_MIN; for (int k = i; k <= j; k++) ...
You are not saving the max sum value, you need to do it within the loop: void printpair(int ar[], int n) { int largestsum = INT_MIN, currentsum = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { currentsum = 0; largestsum = INT_MIN; for (int ...
69,226,084
69,261,298
Why might I get heap corruption using Armadillo matrices with pybind11?
I've worked on this for a couple weeks and can't make a reproducible example outside my codebase. That's why I need help! I'm not sure if this is a problem with pybind11 or Armadillo. It's not a problem with Carma since it happens in situations with no conversion going on. EDIT: This actually does appear to be a bug in...
Credit to the carma developer, @RUrlus, for the answer: The problem is due to the bindings module, linked to carma, being linked to a library that hasn't been linked to carma. The external library (mc in the MRE) was allocating memory using the standard malloc while pybind11 was using Carma's free on destruction. The m...
69,226,390
69,226,621
Is a for(auto ...) of list where we append new elements within the loop guaranteed to work against all the elements?
I have a class with an f_next field that looks like so: class process { public: typedef std::shared_ptr<process> pointer_t; typedef std::list<pointer_t> list_t; void add_next_process(pointer_t p); void wait(); private: list_t f_next = list_t(); }; The add_next_process() simply appends p to f_next...
For-range is just a syntactic sugar for a classic for loop operating on iterators. As long as your container implements begin and end (or you have free overloads), and don't invalidate the iterator in the process, this should technically be fine. Other thing is whether this is a good and maintainable idea. Before C++17...
69,226,393
69,226,807
How to properly use the for-range statements syntax in C++?
iteration-statement: while ( condition ) statement do statement while ( expression ) ; for ( init-statement conditionopt ; expressionopt ) statement for ( init-statementopt for-range-declaration : for-range-initializer ) statement for-range-declaration: attribute-specifier-seqopt decl-specifier-seq ...
This part of the grammar attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ] is to allow for structured bindings in a loop. e.g. you could do something like this: struct S { int i,j; }; std::vector<S> v; for (auto [a, b] : v) // ... a and b simply refer to i and j Note that the identi...
69,226,565
69,226,965
Reinterpret_cast sent data
The code below is just an example. Function1 is a dllexport, how do I properly convert/read the value of data inside of Foo2? When I print the value, it returns 000001DFA1C501F3. Function1(PVOID InPassThruBuffer, ULONG InPassThruSize); void Foo(std::wstring* data) { Function1(&data, sizeof(wchar_t)) } // ===...
Try something more like this instead: void Foo(std::wstring* data) { Function1(const_cast<wchar_t*>(data->c_str()), data->size() * sizeof(wchar_t)); // or, in C++17 and later: // Function1(data->data(), data->size() * sizeof(wchar_t)); } void __stdcall Foo2(REMOTE_ENTRY_INFO* inRemoteInfo) { wchar_t *w...
69,226,612
69,226,645
Which of the following is the correct behavior (g++ vs clang++-12)?
The following is the code: #include <iostream> const int& temp_func() { return 3; } int main() { std::cout << temp_func() << std::endl; } When compiled with g++ (Ubuntu 9.3.0-17ubuntu1~20.04), the result: [1] 402809 segmentation fault ... On the other hand, when compiled with clang++-12, the result: 3
Both are correct. Your code has undefined behavior. When you do return 3 a temporary int object is created, and the reference the function returns is bound to that temporary object. After the return statement finishes, that temporary is destroyed leaving the reference dangling. Any access though that reference has ...
69,227,220
69,228,049
Expanding QChartView
A little at lost as to why QChartView will expand when put inside of a QTabWidget. Here's a picture of the application when QChartView is not expanding (because it's hidden). The black portion of the app is QOpenGLWidget. When I click on the chart view, it will gradually increase in size until QOpenGLWidget is hidden....
The problem is caused because the QChartView has the expansion sizePolicy as opposed to the QOpenGLWidget, so when it becomes visible it expands, hiding the other widget. The solution is to set a stretch factor associated with each widget in the layout: layout.addWidget(&gl_widget, 1); layout.addWidget(&tab_widget, 1)...
69,227,273
69,227,438
Are the data members in Stack or Heap memory in C++
Just want to know where the data members are in the memory, heap or stack. Here's my code: #include <iostream> #define p(s) std::cout << s << std::endl class Fook { public: char c = 'c'; // Fook() { p(c); } }; class IDK { public: int* arr = new int[1]; // IDK() { Fook fook3; ...
First of all: stacks and heaps are not C++ language concepts, but are implementation concepts. The C++ standard talks about automatic and dynamic storage instead. But for simplicity lets just talk about stacks and heaps. Typically the new operator will put your object on the heap (unless new operator is overloaded). Ot...
69,228,373
69,229,404
Efficiently take N lowest bits of GMP mpz_t
There is mpz_class C++ wrapper of GMP type mpz_t. Having mpz_class number what is the most efficient way to take its N lowest bits to create another mpz_class number? Of course I can do following masking operation size_t N = 273; // how many lo bits to take mpz_class x = ... ; // fill with something... mpz_class mask =...
Although there's no C++ operator overload or function for mpz_class, you can indeed use: mpz_tdiv_r_2exp provided by the C API. e.g., mpz_tdiv_r_2exp(result.get_mpz_t(), x.get_mpz_t(), N); note: cdiv and fdiv variants are available too. Using mp_bitcnt_t as the type for (N), or static_cast<mp_bitcnt_t>(N) as the argum...
69,228,813
69,228,838
How to make std::map::find function case sensitive?
I had interviewed with a MNC company. He gave me the following code and asked me to make find() function as case-sensitive. I tried, but failed to understand how to make inbuilt find function as case-sensitive. Is there any way to make it case-sensitive to find only a particular key value? #include <iostream> #include ...
The problem is the for loop. You do not need to iterate through the map to print it. Rather you need to do auto it = mp.find("TEST"); if (it != mp.end()) std::cout << it->first << " " << it->second << std::endl; The std::map::find will find an iterator pointing to the key-value pair which has key exactly "TEST", i...
69,228,861
69,229,804
CPP Question - Primes array, how the sqrt while loop finds the prime numbers?
I would like your help to understand how the below code is producing the prime numbers. The code is correct, but I am not sure how the loop ensures that isprime = trial % primes[3] > 0; is not a prime number. P.s. I know that 9 is not a prime number, but I would like to understand how the below code understands that 9 ...
Okay, think about prime numbers. A number is prime if there are no prime numbers that divide into it evenly. maybe_prime % lower_prime == 0 If that's true for any of the prime numbers lower than your number, then your maybe_prime number isn't prime -- because something else divides easily. That's a start of understand...
69,228,881
69,229,045
How to get function template taking invokables to match the types?
I have the following code intended to take a generic function object that takes two arguments and return a function object that does the same with the arguments in the other order. #include <type_traits> #include <functional> template<typename Function, typename FirstIn , typename SecondIn, typename std::enable_if...
Your usage of std::enable_if is wrong. You need template<typename Function, typename FirstIn, typename SecondIn , typename = std::enable_if_t< //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ std::is_invocable_v<Function, FirstIn, SecondIn> > > std::function<std::invoke_result_t<Function,...
69,228,910
69,340,711
How can be shown the placeholder sync icon in a renamed folder using Win32 Cloud Filter API?
I'm using the Microsoft Cloud Filter API to manage placeholders in my local directory, and when I rename a folder its state icon isn't visually updated after I apply the CfSetInSyncState function to this folder. This folder contains a file that was previously copied from another placeholder from this cloned directory. ...
I could show the placeholder sync icon correctly in this case renaming the folder twice using MoveFileW and CfUpdatePlaceholder functions. Here I show you the method that renames the folder twice. bool FolderRenameTrick(const std::wstring& folderPath) { // Gets a nonexistent folder path std::wstring folderPathA...
69,229,696
69,230,032
Need help about iteratively guessing game
I'm new at coding, i made a small game. But program turns it self off after you answer true or false. But i want to make this program iteratively. I mean after you guess it, program should restart. #include <iostream> #include <cmath> using namespace std; int main() { int secretnum; int guess; int...
Your code is getting very convoluted because you are using many unneeded variables. The variables success, success2 and outofguesses are all unnecessary. If you use infinite loops and use an explicit break to break out of an infinite loop when necessary, the code is much cleaner and it is easy to restart the game: #inc...
69,230,222
69,237,275
Maximize this equation E[a1]-E[a2]+E[a3]-E[a4]
Can anyone please help me how todo this problem We have to maximize the value of: E[a1]- E[a2]+ E[a3]- E[a4] where E is an array constraints: 1<=E<=100 (size) N>=4 a1>a2>a3>a4 (index) Input format N (no. of integers in array) N value separated by spaces Output single integer(max value) Test case: I/P 6 3 9 10 1 30 40 O...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> v(n); for(int i=0; i<n; i++) cin>>v[i]; vector<int> a1(n); vector<int> a2(n); vector<int> a3(n); vector<int> a4(n); int max4 = (-1)*v[0]; for(int i=0; i<n; i++) { max4 = max(max4, (-1)*v[i]); a4[i] = max4; } int ...
69,230,577
69,230,670
What is nth_element and what does it do exactly? and how to implement it
I've almost understood many STL algorithms until I've reached the algorithm std::nth_element. I 'm stuck on it; I don't know how it works and it does do exactly. For education and understanding sake can someone explain to me how the algorithm std::nth_element works? std::vector<int> v{ 9, 3, 6, 2, 1, 7, 8, 5, 4, 0 }; s...
So where is nth element here? The n-th element is the 2 at index 2 because thats what you asked for when you passed begin()+2. The element pointed at by nth is changed to whatever element would occur in that position if [first, last) was sorted. This means that, if the vector was sorted, the order of elements would...
69,230,597
69,230,806
How to access user-context data set on epoll when calling epoll_wait
Below I add sockets to epoll and set an application-context index within epoll_event.data.u32. When receiving packets, recv() requires the socket file descriptor. In all the examples events[i].data.fd is used. However, events[i].data.fd and events[i].data.u32 are in a union, so how do I also access my user-context ind...
You tell epoll_ctl() which socket descriptor you want to listen for events for, and provide an epoll_event struct to associate with that listen operation. Whenever epoll_wait() detects a registered event on a socket, it gives you back only the epoll_event struct that you had provided for that event, exactly as you had ...
69,230,824
69,230,898
comparing a string at index i to a value in C++
So im working on a class assignment where I need to take a base 2 binary number and convert it to its base 10 equivalent. I wanted to store the binary as a string, then scan the string and skip the 0s, and at 1s add 2^i. Im not able to compare the string at index i to '0, and im not sure why if(binaryNumber.at(i) == '...
Array indices for C++ and many other languages use zero based index. That means for array of size 5, index ranges from 0 to 4. In your code your are iterating from 1 to array_length. Use: for (int i = 0; i < binaryNumber.length(); i++)
69,230,844
69,235,395
`io_context.stop()` vs `socket.close()`
To close a Tcp client, which one should be used, io_context.stop() or socket.close()? What aspects should be considered when making such a choice? As far as I know, io_context is thread-safe whereas socket is not. So, I can invoke io_context.stop() in any thread which may be different from the one that has called io_co...
To close a Tcp client, which one should be used, io_context.stop() or socket.close()? Obviously socket.cancel() and or socket.shutdown() :) Stopping the entire iexecution context might seem equivalent in the case of only a single IO object (your socket). But as soon as you have multiple sockets open or use timers and...
69,230,926
69,231,037
How to make base class template function visible for derived class instances without casting or duplicating signature?
Is there any way to avoid cast when calling a base class template function from a derived class instance? Suppose the following: class Foo { public: virtual void quux() = 0; template <class T> void quux() { ... } }; class Bar : public Foo { public: void quux() override {} }; Then later on usage of class B...
Just add using Foo::quux;: class Bar : public Foo { public: using Foo::quux; void quux() override {} };
69,231,136
69,231,159
how to make 69.99*100 print 6999 instead of 6998?
I want to have the right 6999 but the code prints 6998, is there any way to implement it in C/C++? #include <iostream> using namespace std; int main() { double x = 69.99; int xi = x*100; cout << xi << endl; return 0; }
Your compiler is probably using the IEEE 754 double precision floating point format for representing the C++ data type double. This format cannot represent the number 69.99 exactly. It is stored as 69.989999999999994884. When you multiply this value with 100, the result is slightly smaller than 6999. When implicitly co...
69,231,219
69,231,266
C++ Simple Login Project
I tried making a simple login authentication program in C++. I wanted help on how to make a dictionary of username and passwords so as to authenticate login info. For the simple project I just assigned a login string with a string and password too and checked the input of user. #include <iostream> #include <string> usi...
You can use map to create your dictionary and use map's find method to check if the key is present in map or not. #include <iostream> #include <map> #include <string> using namespace std; int main() { // create your dictonary map<string, string>dict = { {"john", "123"} }; string username, password; cou...