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
66,346,389
66,347,268
std::chrono::system_clock and C time
I am using the following time point definition universally in my project: using time_point = std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long, std::ratio<1,1000>>> With this definition I get a reasonable tradeoff between precision and range, unfortunately the default with nanosecond resolu...
If you assume that std::chrono::system_clock has the same epoch as time_t (it usually does) then to_time_t and from_time_t are essentially just a std::duration_cast. For example this code should print the same values twice (note that whether to_time_t rounds or truncates is unspecified and duration_cast always truncate...
66,347,219
66,347,248
How do I feed a function containing a vector with different data types with these different data types?
I am still struggling to realize what I want to do. My code shall take user-defined segments (e.g. either a line, a circle, or whatever geometric segment definition I will implement) and chain them together in a vector. However, the order of segment type ("line", "circle",...) is user-defined and may hence vary from ex...
You need to move items in vector, as your items are no copyable: v1.emplace_back(std::move(anotherCircle));
66,347,353
66,347,957
Stack Overflow in rather short (30 lines) program
First of all, I am a beginner, and I don't know what a StackOverflow even is, so please keep your explanations layman-friendly. I read a little about StackOverflow and was surprised that I encountered it even though my program is rather trivial. Anyway, I was practicing in Codewars and then this happened: The challeng...
Here is the function that does what you state: size_t challange(const std::string& s1, const std::string& s2) { auto l1 = s1.size(); auto l2 = s2.size(); for(size_t ind = 0;;++ind) { if(ind>=l1||ind>=l2||s1[l1-1-ind]!=s2[l2-1-ind]) { return l1-ind+l2-ind; } } } P...
66,347,498
66,349,566
Is there a way to optimize the operator+= for different data types
"I'm not a pro, I'm just learning!" I want to support add operator in my class like Buffer. class Buffer : public vector<uint8_t> { public: Buffer() = default; Buffer& operator += (const char* str) { auto pStr = str; while(*pStr) { emplace_back(*pStr); ++pStr...
If you use C++20, then you can use requires to minimize those functions as much as possible. class Buffer : public std::vector<uint8_t> { public: Buffer() = default; template<typename T> Buffer& operator+=(const T& any) // Any container that has iterators or arrays. requires requires {...
66,347,521
66,347,738
Overload resolution works on functions, but not with implicit constructor parameters
This code shows a basic wrapper class for the __int32 and bool type. My intention is to extend basic types with methods and custom operators, etc. Each class has one implicit constructor, allowing to assign an __int32 to an Int32 type implicitly. This works well, until there is a function overload accepting both Int32 ...
The problem is, given AmbiguousFunc(123);, 123 could be converted to bool (standard conversion), then converted to Boolean(user-defined conversion); which has the same ranking with the user-defined conversion from 123 to Int32, then the calling is ambiguous between AmbiguousFunc(const Int32 &) and AmbiguousFunc(const B...
66,347,728
66,347,801
Storing a C++20 function-like object from a forwarding reference?
In C++20, let's suppose I want to std::make_unique a copy (or move as appropriate) and store a function-like object that is passed in a forwarding reference... template<typename F> std::unique_ptr<???> make_copy_of_functor(F&& f) { return std::make_unique<???>(std::forward<F>(f)); } What goes in the ???s ? Is it ...
As forwarding reference, when being passed lvalue F would be deduced as lvalue-reference, you can use std::decay to remove reference part (and add pointer for function type). template<typename F> auto make_copy_of_functor(F&& f) { return std::make_unique<std::decay_t<F>>(std::forward<F>(f)); }
66,348,214
66,348,463
How to do sorting and applying unique on vector of vectors?
I need to keep only the unique arrays in a vector. I am not getting how to do it just using std algorithms. I tried different approaches, but nothing worked. Code: include <iostream> #include <vector> #include <array> #include <algorithm> using vec3 = std::array<int,3>; struct vec3comp{ bool operator()(const vec3...
using a std::set should solve your problem std::set<vec3> s{vec.begin(),vec.end()}; vec.assign(s.begin(),s.end()); you can also add a custom compare class as a template parameter
66,348,227
73,554,807
PATH environment variable is different in the Qt C++ code and process explorer tool
I am trying to update the PATH environment variable inside my C++ program using Qt on Windows 10. There is something wired in this scenario that I cannot understand. The strange point is that the value of PATH environment variable is getting different in the C++ code and in process explorer tool after dynamically loadi...
I could not find any reason behind this problem. It seems that it can be an internal issues comes from Qt/Windows. So, the only workaround that I have found is to add the below line again: qputenv("PATH", qgetenv("PATH")); // this line fixes the issue
66,348,947
66,354,034
How to find prime numbers within a range in C++ without using flag variables or functions?
In my textbook, the algorithms and flowcharts for this problem use flag variables.So I gave it a try without using flag variables and got a solution (given below).But its implementation in C++ is quite puzzling. We haven't officially learnt goto statements yet. So my doubt is whether its implementation in C++ is possi...
Here is my implementation of the above idea only using for loops and if statements with an optimization for j: #include <iostream> #include <algorithm> #include <math.h> using namespace std; int main() { int l, r; bool good; // stores whether a certain i will be prime cin >> l >> r; for(int i = max(l, ...
66,349,024
66,349,124
Stack using linked list. Struct field is of the same type as the struct
While practicing stack using linked list, I ran across the following piece of code: class stack { private: struct node { double value; node* next; }; size_t stack_size; node* head; ... } As you can see, the struct node has a pointer field *node. How can a field be of the same type as th...
How can a field be of the same type as the struct? It can't, this won't compile (note that the node data member is not a pointer in this example): struct node { double value; node next; }; But with node *next being a pointer it works, because the compiler knows that node* will be the size of a pointer on you...
66,349,159
66,349,185
Why is this only returning whole numbers when i used double throughout?
Just wondering why this area calculation code only returns whole numbers, even though I used double throughout. #include <iostream> #define pi 3.14 piCalc(double radi) { double result; result = (radi * radi) * pi; return result; } int main() { double radius; std::cout << "Welcome to the circle area calcula...
Here: piCalc(double radi){ You are missing the return type. This isn't valid C++. In (ancient?) C you could omit the return type and int was assumed. Some compilers still allow this as non-standard extension. Make the return type double: double piCalc(double radi){ In general you need to take care with compiler exten...
66,349,352
66,349,505
Comparison of INT_MAX
I tried comparing two INT_MAX and then comparing result of this with a integer and I'm getting this weird result.Could u please explain why this is happening? #include <iostream> #include <climits> #include <bits/stdc++.h> using namespace std; int main() { // your code goes here int a = 2; int option1 = m...
INT_MAX is the largest positive value you can store in a (signed) int, when you add 1 to that you get undefined behavior. It's not that surprising, though, as (unsigned int) 0x7FFFFFFF + 1 == 0x80000000 which is the value -2147483648 in two's complement. Now you compare a large negative number with 3 and get the larg...
66,349,562
66,349,633
Is it possible to call a method pointer with a void* pointer to the object
I have a struct, that contains a void* pointer to an object and a function pointer to some method of that object's class. I don't (and can't) have information of that objects' class, so I need a void*. I tried to call the method by this: object->*function(args) When I try to compile this with msvc I get two errors: C...
Is it possible to call a method pointer with a void* pointer to the object No, it is not. More generally, you cannot indirect through a pointer to void at all. Pointer to void must be casted to an pointer to object type that is compatible with the pointer to member function. I don't (and can't) have information of t...
66,350,357
66,350,573
Why is alloca returning the same address twice?
I'm trying to implement my own math library, and I'm starting off with vectors. The idea is to give the class a pointer to an array of numbers, then copy the array and store it in the data address given by a private variable pointer. To begin with, I used alloca to try and free up some memory for the private variable v...
You have to be very careful with alloca. It allocates memory on the stack rather than the heap. That memory is freed as soon as the function which called alloca exits. In this case, it will be called in the constructor so when you call operator() that memory has already been freed and you are dealing with undefined beh...
66,350,603
66,350,678
Unique_ptr to array of pointers syntax
I'm trying to have a struct take possession of a pointer to an array of pointers to objects on the heap. In order to not have to worry about deleting these objects I want to use smart pointers. However, I can't seem to find a correct syntax to do so... This is what (I think) I want to achieve: const std::unique_ptr...
A unique_ptr to an array will only clean up the array, but if the elements are pointers to objects stored elsewhere (presumably on the heap) then those objects are not cleaned up automagically. It seems you rather want a std::vector< std::unique_ptr<Position>> or a unqiue_ptr to an array with a custom deleter that a...
66,351,206
66,351,323
template with enum specialization
I have a template which takes as specialization an enum class (note the different initializations of enum), and I would like to be able to compare two different enums enum choiceA {One, Two, Three}; typedef enum {Four, Five, Six} choiceB; template<typename S> void f(S choice, int& x) { if (choice == One || choice == ...
The fact that you have two enum types for the same enumeration is odd. I would fix that design first. Anyway to strictly answer your question you don't need templates here. A simple overload would suffice: void f(choiceA choice, int& x) { if (choice == One) { x = SomeWhateverIntegerValue; } els...
66,351,246
66,361,280
Microsoft Visual Studio doesn't resolve #include <file.h> but it does when used quotes
I am trying to add some .h and .c files to a C++ project. However, the library calls header files by using <> instead of "". And the Microsoft Visual Studio 2015 tells me it can't open the header file. When switched to "" it can open it. I don't want to go through 100 files and change <> to "". Is there any solution to...
When using include to quote header files, the difference between " " and < >: " ": To quote the header file of a non-standard library, the compiler first searches in the directory where the program source file is located. If it is not found, it goes to the system default directory to search, usually used to quote user...
66,351,272
66,351,839
Input validation of opening a text file in C++
I am building an input validation function that takes the input of the user and tries to open that file. and repeats if user is not entering the correct format. the correct format is: test1.txt My function works if I write correct format in the first run, but after the second run it keeps printing the error message a...
I could reproduce and fix. The problem is caused by cin.ignore(). According to cppreference: ... the next available character c in the input sequence is delim So ignore will read the next line, up to the newline, and leave that newline alone. And the following getline can only read an empty string! By the way, using ...
66,351,305
66,351,412
g++ 10.2 shows cpp version 14
I am beginner in cpp. I had a old cpp which version i dont know. I ran the following to check the version. int main() { if (__cplusplus == 201703L) std::cout << "C++17\n"; else if (__cplusplus == 201402L) std::cout << "C++14\n"; else if (__cplusplus == 201103L) std::cout << "C++11\n"...
You can set the C++ standard in gcc with the command line argument -std. Some of the supported standards are -std=c++11, -std=c++14, -std=c++17, -std=c++20.
66,351,663
66,351,813
PrintInfo() Giving Me A Hard Time
So I'm studying with classes and and I'm making a program that prints user entered data, however I can't seem to get past this one compiler error. The gist of the program is to take student user data and output it. #include<iostream> #include<string> using namespace std; class Student { public: Stud...
myStudent does not exist inside Student::PrintInfo(). PrintInfo() is actually a member function, so it should look simply like this. void Student::PrintInfo(void) { cout<<"Name: "<< GetName()<<endl; cout<<"ID #: "<< GetId()<<endl; cout<<"Gender: "<< GetGender()<<endl; cout<<"Ethnicity: "<< GetEthnicity(...
66,351,942
66,354,645
Multiple programs using one or multiple config file
I have a embedded device with a custom linux built with yocto. On this device are multiple programs: reading data from sensors converting the data into a given format response to udp-requests ... many of the programs need some configuration, like: how many samples to read which format to convert which udp-port ... ...
I suggest you arrange for each application to obtain its configuration variables from a named scope within a named file, for example, you might start applications app1, app2 and app3 as follows: app1 -cfg common.cfg -scope app1 app2 -cfg common.cfg -scope app2 app3 -cfg common.cfg -scope app3 The above instructs each ...
66,352,366
66,352,650
Do google protobuf messages have parseable headers with meta information?
I couldn't find a proper guide to send and receive protobuf messages over network. The example from tutorial shows how to read from and write to a file. So a naive approach would be to create a custom header for a network protocol and send protobuf files. Header also contains enumeration value for a type of the message...
No, a vanilla protobuf payload does not contain metadata about the message type (the recipient is expected to know that in advance), nor is it self-framing (if sending multiple messages on the same transport, you are expected to use your own framing protocol).
66,352,372
66,358,382
Invalid conversion from 'int' to 'void (*)(void*)' in MinGW 7.3.0 32bit
I have to integrate the plain C .h file to my C++ project (Qt GUI). For that I have to avoid some function pointers with tricky substitutions. Piece of code you could see below had compiled without any problems in MinGW 5.3.0 C++ before. But when I tried to use more fresh compiler (7.3.0 for C++) I got an error "Invali...
Solution Actually, I've done it! Your comments forced me to think harder and I found out how to make this 'mocking' trick. I have this code compiled now without any warnings. For what purpose does it serve? What I need it's extracting values of some fields from const struct types[]. I'm sure there're another solutions ...
66,352,556
66,353,170
How to get the result of a quadratic equation with negative root in c ++?
I am trying to obtain the result of a quadratic equation with negative root, but the result that I obtain is not the same when I do the operation on paper, also the result is not the same only with negative roots when it is the opposite, it works perfectly. #include<iostream> #include<cmath> using namespace std; int ...
Your first problem is opeartion priority. You should have a parenthesis in the following lines: x1 = (-b + sqRoot)/ (2 * a); x2 = (-b - sqRoot)/ (2 * a); instead of x1 = (-b + sqRoot)/ 2 * a; x2 = (-b - sqRoot)/ 2 * a; The second problem is your division using int variables. The code s...
66,352,964
66,353,896
How to register callback with variadic arguments and pass a value
could you please help in following. I have callback function definition in the 3rd lib header: #ifdef __cplusplus extern "C" { #endif typedef int (*SOCK_CLBK)(int, short, unsigned char*, int, ...); #ifdef __cplusplus } #endif And I define my callback in the following way: header file: template<typename T> int Read...
First, your code with ReadTCP function template is incorrect. SOCK_CLBK is a type of a function pointer that has an ellipsis at the end of its argument list, which is different from int (or any other type) that ReadTCP<int> has. The compiler does not fail to compile because you explicitly convert the pointer to ReadTCP...
66,352,969
66,353,101
Should FreeLibrary be called at the end of the program?
I haven't found this in the documentation: if I need a DLL handler until the end of the program, should I still call FreeLibrary before my caller program ends, or it's not required?
It is best practice to always call FreeLibrary for any corresponding LoadLibrary call. However, skipping that call and just ending your program will likely not cause any serious issues, as terminating the calling process would appear to have the same effect as reducing the 'reference count' for your DLL (as calling Fre...
66,353,304
66,353,354
Why is the array constant?
This question is a follow-up question to Why is alloca returning the same address twice?. I've found a way to get a different memory address to both instances by using an array. vml.h #pragma once #include <iostream> namespace vml { // Vectors template <typename in_type, const int in_length> class vec { ...
You miss the const in return type of your operator()() in_type const & operator()(int index) const { _ASSERT(0 <= index && index < in_length); return data[index]; } When you declare member function with const modifier all class members inside became constant while using inside it If you want non-co...
66,353,692
66,353,762
std::any of std::unique_ptr doesn't work?
Please consider the following C++20 program: #include <any> #include <memory> int main() { std::any a; std::unique_ptr<int> x = std::make_unique<int>(42); a.emplace<std::unique_ptr<int>>(std::move(x)); } I'm getting: test.cc: In function ‘int main()’: test.cc:7:47: error: no matching function for call to ‘std::...
The class std::any is copyable. Despite its name, it cannot wrap "any" and all types. Specifically, it cannot wrap non-copyable types. std::unique_ptr is not copyable. std::unique_ptr cannot be stored in std::any.
66,354,072
66,382,538
C++: Getline ignores "\n" in mqtt message
I use a mqtt message to send messages like this: mosquitto_pub -t "TOPIC1" -m "ARG1\nARG2\n" In my C++ application i write: string payload = reinterpret_cast<char*>(message->payload); std::istringstream iss(payload); std::string arg1; std::getline(iss, arg1); cout << arg1 << endl; This gives me ARG1\nARG2\n. What's wr...
This is not a C++ problem. Your problem is that normally \n is not interpreted as new line in by bash for a command line argument. Also mosquitto_pub will not do any interpretation on the input message. You can force this as follows: mosquitto_pub -t "TOPIC1" -m $'ARG1\nARG2\n'
66,354,497
66,359,161
Boost MSM with constructor parameters on a submachine
I'm trying to share the SyncBox object between a main state-machine and a sub state-machine. The ideal way is to pass it on the constructor (sub state machine will be a initial state of one of the regions in a more complex case). No matter what, I can't make this code compile and execute properly. Any help? #include <i...
As far as I can tell you had everything correctly. The problem, however, is that the substate-list requires all state elements to be default-constructible regardless. (This might not be true for the frontend class, as far as I can tell, but haven't looked all the way into it). This means that storing a reference as mem...
66,354,770
66,355,114
No matching function for call to "MessageDlg"
I am receiving an error indicating that their is no matching function for a call to MessageDlg() in C++ Builder. My header file does include <Vcl.Dialogs.hpp> which is where the function is declared. The function is being called from within a TForm class public function. Below is the offending code: void MBInvalidPosit...
C++ supports overloaded functions — which function you're calling is a product of both its name and the types of the arguments supplied to it. Therefore, given that you have the correct name of a function, a reasonable first guess is that you are supplying the wrong type for one of the arguments. Specifically, it doesn...
66,355,427
66,355,505
how to reset rand() function c++
Good afternoon. I'm working on a quiz which contains four buttons. They contain a randomly selected line of text from a text file. The problem begins when I call 4 integers with the rand() function, which picks numbers from 1-5. Knowing that the rand() function can pick the same numbers, I code this: if (random4 == ran...
It sounds like you want a random selection of items from a list, but without repeats. An easy way to do this is to shuffle a list and then read out the items from the shuffled list. This page describes an approach for doing this: https://www.cplusplus.com/forum/general/207328/ In your case, you can create a list with t...
66,356,313
66,356,810
Converting integers to _LARGE_INTEGERS
I'm trying to call NtDelayExecution but can't seem to figure out how to convert an int to a _LARGE_INTEGER (the format that the NtDelayExecution function requests). (http://www.codewarrior.cn/ntdoc/winnt/ex/NtDelayExecution.htm) My current code is: LARGE_INTEGER DelayTimeConverted = HIBERNATION_TIME; ((NtDelayE...
LARGE_INTEGER is a union containing two 32-bit integers LowPart (DWORD) and HighPart (LONG) laying on top of a 64-bit integer QuadPart (LONGLONG): typedef union _LARGE_INTEGER { struct { DWORD LowPart; LONG HighPart; } DUMMYSTRUCTNAME; struct { DWORD LowPart; LONG HighPart; } u; LONGLONG Qua...
66,356,320
66,357,109
Template argument deduction from inherited type
I want a setup like the following: template <typename T> class a {}; class b : public a<int> {}; template <typename T> void do_foo(std::unique_ptr<a<T>> foo) { // Do something with foo } int main() { do_foo(std::make_unique<b>()); } This fails to compile with a note saying template argument deduction/substi...
Is there a way to get the compiler to deduce the template parameter in this case? No. Not in C++14 (or even C++20). And what would you call this behaviour? Standard compliant. To be specific, this paragraph applies: [temp.deduct.call] 4 In general, the deduction process attempts to find template argument values th...
66,356,416
66,356,486
Compiling variables/data types into executable (Ghidra, C, C++, gcc)
I am currently reverse engineering a software sample in which the original author has pre-defined a series of unicode data types/variables into the .data portion of the sample upon compilation. Thus, since they seem to be compiled into the executable itself, I cannot find where the code where they are written (obviousl...
I am pretty sure that is what (typically) happens to string literals: int main() { std::string s = u"Services"; return 0; } See this.
66,356,998
66,419,419
OpenSceneGraph plugin not included in Conan?
I'm trying to do simple mesh viewer using OpenSceneGraph and I want to use Conan for dependencies. The compilation is working well in both debug and release mode (I'm compiling on Windows for now with msvc toolchain). As soon as I try to load any kind of mesh, the osgDB::readNodeFiles just fail. Looks like the plugin a...
I found the solution. I'm compiling statically the program, the plugins are linked to the final binary but the plugin registry look for a dynamic library (osgdb_obj.dll for example). If you have the same problem, you have to register manually the plugin : USE_OSGPLUGIN(obj) USE_GRAPHICSWINDOW() // and you may want this...
66,357,045
66,357,279
Copy-assigning to a tuple from an iterator range in C++17
I've been hoping to use new C++17 features like fold expressions and std::apply() to simplify some C++11 code I have that uses tools like std::index_sequence and std::initializer_list for some operations on tuples. One task in particular is giving me a bit of trouble: copying a range of values (e.g. from a boost::token...
Version with fold expression may look like: std::tuple<int,int,int,int> t; std::vector<int> v{4,3}; auto beg = v.begin(); auto end = v.end(); std::apply([&](auto&... values){ auto getValue = [&](){ return (beg != end) ? *beg++ : 0; }; // returns 0 if range is too small ((values = getValue()),...); }, t); std::c...
66,357,065
66,358,097
OpenSSL problem with returned SHA256 value - C++
I need help with generating SHA256 value with OpenSSL. I have code: typedef unsigned char byte; int generateSHA256() { unsigned char temp[SHA256_DIGEST_LENGTH]; char buf[SHA256_DIGEST_LENGTH * 2]; const unsigned char *charToGenerate; size_t lenCharToGenerate; memset(buf, 0x0, SHA256_DIGEST_LENGTH...
If the goal of this is to produce an asci hex string of the sha bytes (in either case), your sprintf_s loop (a) is lying, the target buffer is decreasingly smaller as you march up so repeatedly passing sizeof(buf)/2 is a lie, and (b) invokes undefined behavior on the final write, which will produce a three character ou...
66,357,388
66,357,476
Why is cin changing the address of my reference variable?
I am learning C++ and created some experimental cases for myself to learn about references and pointers. I ran into a situation where I would pass in a reference variable to a function, but when I tried to change its value within the function, the value change did not persist outside of the function. It took me a long ...
It looks to me that you've run into a buffer overflow and therefore undefined behaviour. The trouble is that char input[2]; can hold only two characters and no more. Unfortunately, your input of "00" requires three characters to store as a C string - you can't forget the null terminator!
66,357,481
66,368,230
Why I couldn't handle an exception thrown from a destructor outside of it?
I've read in C++ primer 5th edition ch18 on Exception Handling that a destructor usually should not throw an exception like STL containers and if it should, that thrown expression should be wrapped in a try-catch block (a catch must handle that exception). I've tried this for understanding purpose: struct Foo{ ...
I think you misunderstood the recommendation: a destructor usually should not throw an exception like STL containers and if it should, that thrown expression should be wrapped in a try-catch block (a catch must handle that exception). In other words, it says: You should not throw an exception from a destructor. Now t...
66,357,794
66,357,966
Function returns const ref to std::unique_ptr, can it return null?
I have a function that return const ref to a std::unique_ptr. I'm getting this ptr from some container. I want to have a possibility to return nullptr or something when in my container of std::unique_ptr there is no appropriate object to the input values. It seems to be impossible with const ref. There is definitely a...
If you have an interface that returns a reference to an object, then that interface is referring to an object that exists somewhere in the program. If, in the course of trying to generate such a reference, you realize that the user has malformed their inputs or otherwise no such object exists, you have the following ch...
66,357,921
66,358,675
Is memory access slower than shifting?
Which of the following two code snippets would generally run faster (without compiler optimizations)? This code is just an example - I am aware that there are faster ways to do the same calculation. // arr points to the following array: [1,2,4,8,16,32,64] // assume that it has already been created, so that the // array...
I recommend that you take a look at the excellent manuals from Agner Fog, especially the one related to C++ Optimizing for speed is relevant when CPU access and memory access are critical time consumers. In most of modern architectures, shifting (ALU instruction) will be much faster than memory access, quoting the ma...
66,357,998
66,358,980
QThread: Destroyed while thread is still running in QTest
I have written a small multithreaded message queue. Now I am trying to do a test. But I am having a synchronization problem that I am not able to fix. If I remove everything about the queue, the minimum verifiable example looks like this (sorry, it's a bit big): #include <QCoreApplication> #include <QDebug> #include <Q...
You need to always wait() on a thread before deleting it (in non-Qt speak "join"). Calling exit() on a QThread returns immediately and does not wait. And deleteLater() is performed in the caller's thread (not target thread), so you cannot count on it to be called "late enough". Do exit(), then wait(), then deleteLater(...
66,358,126
66,358,938
How can I detach a gdb session from outside?
I start a gdb session in the background with a command like this: gdb --batch --command=/tmp/my_automated_breakpoints.gdb -p pid_of_proces> &> /tmp/gdb-results.log & The & at the end lets it run in the background (and the shell is immediately closed afterwards as this command is issued by a single ssh command). I can ...
If you run the gdb command from terminal #1 in the background, you can always bring gdb back into foreground by running the command fg. Then, you can simply CTRL+C and detach as always to stop the debugging session gracefully. Assuming that terminal #1 is now occupied by something else and you cannot use it, You can se...
66,358,575
66,359,397
C++ VSCode CMake VCPKG: manifests are not enabled
I'm trying to build the Supertux-C++-Project like in this Video. I installed the VS Code extensions for C++ and CMake, and I'm using the GCC compiler. I cloned the VCPKG-Repository and executed the bootstrap-vcpkg.bat. After that, I ran ./vcpkg integrate install and got the message: Applied user-wide integration for t...
Manifests are a relatively new feature of vcpkg. It allows you to specify (via the vcpkg.json file) what your dependencies are. The old way meant there was really no way for vcpkg to automatically know your dependencies from looking at your project folder. You had to essentially install them manually. Manifests mode is...
66,358,665
66,359,167
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition
My system is macOS Big Sur and I have a compilation problem. This is my program: #include <iostream> #include <sys/ioctl.h> #include <unistd.h> class view { virtual void draw() = 0; }; class tui : view { public: void draw(); }; void tui::draw() { struct winsize size; ioctl(STDOUT_FILENO, TIOCGWINSZ, ...
You are trying to compile C++ code with a C compiler. Just use: g++ -Wall main.cpp -o my_program
66,358,737
66,510,127
c++ adaptor via emcc for tensorflow.js
I have a moderately large library of C++ code that uses the tensorflow_cc API. I have just started working with Emscripten/emcc and am excited by the potential to port my application to run in node.js using tensorflow.js. I want to refactor my C++ code so that most of it can be agnostic as to which Tensorflow backend i...
It does not appear that anyone has published an interface like the one I was hoping for, but it is clearly possible to use the emscripten/embind APIs to invoke TensorFlow.js functions from C++. My first working implementation to do this is available in this gist.
66,358,824
66,362,310
How to rename the program-name menu-label in a MacOS/X program?
I have a Qt-based GUI program that runs under MacOS/X, and I'd like to be able to change the label of that program's first menu-header, i.e. the label circled in red in this screenshot: Is there a programmatic way to do that? An objective-C/"native" solution would be sufficient, assuming no Qt-based solution exists. ...
The following code (Swift, should be trivial to port to ObjC) changes the menu's name: NSApp.mainMenu?.item(at: 0)?.submenu?.title = "child-program-name" However, with this approach the menu is no longer displayed in bold once the name is changed since it doesn't match the app's name. In fact, even when changed back t...
66,358,935
66,359,458
Problem with relative paths on mingw and vscode on windows
I have a problem with working with files in vscode opened folder. I can't specify the relative path of the file, because it is a relative path for the compiler, but not for my project folder. For example: //I want to write in this way std::ofstream out("out.txt"); //*compiler's folder*\out.txt //But have to write in t...
Ok, I found the fix by myself. g++ bin folder wasn't added to my PATH, so I added it and changed "command": "*path to g++.exe*/g++.exe" to "command": "g++" and deleted "options": { "cwd": "*path to g++ bin folder*" }, in tasks.json. Now workspace I compile from is "main" and relative paths work correctly. Thanks dresch...
66,358,945
66,359,290
Reverse a string taken from a file and then input it in to another file
It might be because I don't pass the values correctly.Although the code is running. #include <iostream> #include <fstream> #include <stream> using namespace std; int main() { //Files ifstream Myfile; Myfile.open("Myfile.dat"); ofstream ReverseEx; ReverseEx.open("ReverseEx.txt"); string s...
You need to read line by line (using std::getline) instead of word by word to get the result you expect. Your current loop also reads two words and just throws one of them away. while(std::getline(Myfile, str)) { reverse(str.begin(), str.end()); ReverseEx << str << '\n'; }
66,358,968
66,360,417
How do I read in a specified number of characters from a file while still iterating through it?
I have a file of data like this: Judy Henn 2 Oaklyn Road Saturday 2001 Norman Malnark 15 Manor Drive Saturday 2500 Rita Fish 210 Sunbury Road Friday 750 I need to assign the first 20 characters as the name, next 20 as address, next 10 as day, and the number as yardSize, using the ...
First off, the character counts you mentioned don't match the data file you have shown. There are only 19 characters available for the name, not 20. And only 9 characters available for the day, not 10. After fixing that, your code is still broken, as it is reading only into the Customer::name field. So it will try to...
66,359,779
66,367,558
Try to connect Mysql but FAILED
I tried to connect MySQL. But it seems like something goes wrong and I cannot get it. I'm basically sending a simple SELECT statement to the database and checking if the operation was successful or not. Unfortunately, this always outputs "Failed!" #include <iostream> #include <string> #include <mysql/mysql.h> using na...
Adapted from https://dev.mysql.com/doc/c-api/8.0/en/mysql-real-connect.html MYSQL mysql; mysql_init(&mysql); if (!mysql_real_connect(&mysql,"localhost","root","111222","test",0,NULL,0)) { fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(&mysql)); } else { cout << "Successfull...
66,360,003
66,360,075
How to make string variables more than one word c++?
When I am trying to store more than one word in a string variable, it only outputs one word when I tell the program to print it. This is an example: #include <iostream> using namespace std; string i; int main() { cout << "Input more than one word." << endl; //in this case the user will input whats up// cin...
Instead of using cin >> i, use getline(cin, i). The difference is that, with getline() you get all the words in a line, whereas with operator>> you get only one word at a time.
66,360,124
66,360,286
How to Count a Type of Character that Appears in a String Using a Function in C++?
The goal of my assignment is to write a C++ program that takes in two variables, a character value and a string value. The program is then, with the use of a user-defined function called int CountCharacters() the program is supposed to count the number of times that the user inputted character value is in the user inpu...
The reason you got different numbers is that you output casesFound without assigning a value to it. Reading uninitialized variables makes your program have undefined behavior - so anything could happen. If your function returned 1 it wouldn't have mattered because you do not assign that value to casesFound. You can ass...
66,360,345
66,360,535
How to convert from string to char*
I have this code, in which I need to input some data, and then the program needs to put the data in alphabetical order. The problem is that I can't convert string name to the char* variables s1 and s2. Data to input: 1 Cheile_Dobrogei 45 25 200 2 Vulcanii_Noroiosi 46 25 50 3 Cetatea_Istra 45 25 100 4 Barajul_Siriu 51 3...
It's not necessary to even use C-strings in your code. Change 3 lines char* s1 = ...; char* s2 = ...; to const std::string &s1 = ...; const std::string &s2 = ...; and if (strcmp(s1,s2) > 0) to if (s1 > s2) { and you can keep std::string: #include <array> #include <iostream> #include <string> struct obiectiv { ...
66,360,348
66,360,573
CMake BUILD undefined reference (findpng)
I'm still very new to CMake so feedback is definitely welcome. So, I'm trying to build a simple application that should eventually create a pdf using the library libharu. I think i figured it out how to link the library. But I still receive build errors for the findpng module (I suppose libharu depends on it) CMakeLis...
I've never worked with that particular library before, but skimming their CMakeLists.txt on GitHub it seems like libharu has optional dependencies on libpdf and zlib. Without knowing how you built your version of libharu I'm going to assume that both are needed. Luckily, CMake comes with find-modules for both libpng an...
66,360,534
66,360,591
C++ class as list length specifier?
I was just shown this code on cppreference.com's page about the friend keyword, and I was a little thrown off by the last declaration: class Y {}; class A { int data; // private data member class B { }; // private nested type enum { a = 100 }; // private enumerator friend class X; // friend class forwar...
A::a names the enumerator value defined at a = 100. int v[A::a]; declares a class member named v which is an array of that many int values. So it does the same thing as int v[100];. (Except for the first dimension in a new-expression, the array bound in specifying any array type needs to be a "constant expression", ess...
66,361,077
66,361,278
How can I swap a parent pointer and a child pointer in c++?
Weapon inherits from Item. weapon is a member of class Hero. I want to swap it with the item passed in the function, which is also a Weapon for this example (I'll add more cases). void Hero::equip(Item* item){ if(instanceof<Weapon>(item)){std::swap (item, static_cast<Item>(weapon));} } Basically, when somethi...
std::swap() takes non-const lvalue references as input, which is why you are getting a "no matching function" error when you try to swap with static_cast<Item*>(weapon), which is not returning an lvalue that you can swap with. In order to assign the new item to the weapon member, you need the Weapon* pointer that dynam...
66,361,430
66,362,016
about return (count), count = 0;
so after #include <stdio.h> int main(int argc , char *argv[]) { int n; n = _strlen_recursion("Corbin Coleman"); printf("%d\n", n); } int _strlen_recursion(char *s) { static int count = 0; count++; return (count), count = 0; } where the comma operator is in action 0 can be seen on screen. Wh...
return is not similar to sizeof. The operand of sizeof is either a type in parentheses or an expression. A return statement has only an expression (or nothing). Parentheses are not part of the grammar of a return statement. Parentheses may be present only because they are part of the expression. In return (count), coun...
66,361,929
66,362,234
How do I dereference multidimensional vector pointer?
I'm stuck trying to get the value of what A[i][j] is pointing to. double a = A[i][j];. How do I correctly do it? Could someone please explain? // g++ jacobi.cpp -O0 -o jacobi && ./jacobi #include <iostream> #include <iomanip> #include <vector> #include <climits> using namespace std; void print_matrix(vector<vector<do...
I tried your code and it gave me error on this line: double a = A[i][j]; Change that line into this: double a = (*A)[i][j]; and it will work. Explanation: It's basically the same trick as in line B[i][j] = avg_temp_at(*A, i, j);. A is a pointer, which is pointing to a vector. To accessing to pointers "real data" you...
66,362,482
66,362,521
How to represent (x ^ y) & 1 in another form?
I am trying to find Hamming distance between two integers, and I got it to work with: int count = 0; for(int i = 0; i < 32; i++) { if((x ^ y) & 1) count++; x >>= 1; y >>= 1; } However, it does not work with: if(x & 1 != y & 1) When x = 1 and y = 4, the correct result is 2. However, the second version...
The != operator has a higher precedence than the & operator, so the condition as written is evaluated as x & (1 != y) & 1, but you probably want (x & 1) != (y & 1) instead.
66,362,496
66,362,550
How to print byte array in hexadecimal - c++
I have a piece of code here: #include <iostream> #include <iomanip> using namespace std; int main(void) { unsigned char bytes[] = {0x43,0x4d,0x30,0x30,0x0f,0x0D}; std::cout << std::hex << bytes[0] <<std::endl; } The above program is printing C to command line. How can I make the program to print 43 t...
Use printf function: #include<cstdio> ... printf("%x", bytes[0]); See here if you want to know more about printf function.
66,362,937
66,363,206
How to Convert Big/Little-Endian bytes to Integer and vice versa in C++
I'm going to receive length delimited frame from server with QTcpSocket in this format:- +----------+--------------------------------+ | len: u32 | frame payload | +----------+--------------------------------+ where u32 is in 32 bit unsigned integer encoded in Big-Endian format. depending on config, I...
the way to do is: bytearray -> stream ->setorder -> serialize to variable QByteArray newData = ....; QDataStream stream(newData); stream.setByteOrder(QDataStream::LittleEndian); // or BigEndian stream >> variable;
66,363,234
66,363,440
How to repeat a program when user prompted y/n
This program is supposed to encrypt and decrypt the string "myWord". Once received, it passes through the two methods to encrypt and decrypt and then returns to main. I have been trying to make it prompt the user if they want to continue or not. If they enter "n" then the loops stops and the program ends. if they enter...
Your issue is switching between whitespace-delimited input and line-oriented input. Since std::cin leaves the '\n' in the stream, the next call to std::getline sees that and skips ahead too. You need to skip to the end of the stream: See https://en.cppreference.com/w/cpp/string/basic_string/getline for more information...
66,363,456
66,363,528
Will this completely clean up the result of dynamic allocation of a class object?
So I dynamically allocated a class object with this code: void Inventory::createNewInventoryItem(std::string itemName, unsigned int maxQuantity, unsigned int orderThreshold, double price) { InventoryItems* newItem = new InventoryItems; newItem->createInventoryItem(itemName, maxQuantity, orderThreshold, price); ...
Will this deleteInventoryItem function successfully free up the memory used by the dynamic allocation in createNewInventoryItem? No, your code does leak memory. What you do here, m_inventory.at(posInVector)->~InventoryItems(); is explicitly calling the destructor of the container element. This does clean up any reso...
66,363,478
66,363,636
Why is there an ambiguous call for templatized function?
I have a problem with creating a template in c++. I am using xcode for mac. When passing an int to a swap function I get the error code "ambiguous call". However, passing strings works fine. Why is that? This is my code #include <iostream> #include <cmath> using namespace std; template <typename T> void swap(T& c, T&...
You have using namespace std; which brings std::swap into scope. This means the template swap that you have written conflicts with std::swap, and you get an ambiguous call when you pass it 2 ints. Takeaway: Never do using namespace std; The interesting part is that calling swap with 2 std::strings works. That's because...
66,363,972
66,364,023
How to cause static error in constexpr if-else chain?
In the following C++20 function template: template<int i> void f() { if constexpr (i == 1) g(); else if constexpr (i == 2) h(); else ??? // <--error } Is there something we can write in ??? such that a call of f<3>() will fail at compile-time?
The problem is that the discarded statement of constexpr if can't be ill-formed for every possible specialization. [temp.res.general]/6 (emphasis mine) The validity of a template may be checked prior to any instantiation. The program is ill-formed, no diagnostic required, if: no valid specialization can be generated ...
66,364,381
66,366,495
how return different types from function in c++?
I have a homework in c++ to make a Vector for multi data types in the same vector, I stuck where I need to return different data types and I can't change the main. The homework ask to make the main valid: int main() { Vector v; v.add(5); v.add(5.5f); v.add("this"); for (int i = 0; i != v.size(); ++i...
You might return wrapper with conversion operator, something like: struct data { int int_ = 0; float float_ = 0; string string_; operator int () const { return int_; } operator float () const { return float_; } operator std::string () const { return string_; } }; const Node* get_node(int n) c...
66,364,507
66,365,057
Valgrind false memory leak for a pointer stored in a static std::list
Valgrind shows a memory leak for a pointer stored in static std::list variable. below is the sample code. Leak shown for "auto t = new Abc;" ( definitely lost: 4 bytes in 1 blocks) Is this a BUG in Valgrind ? Is there a solution/workaround (other than clearing the Pool::queue manually) ? #include <list> struct Abc { ...
The std::list destructs (the compiler takes care of that for a static object), the objects in it don't as that's the job of ~Pool, which the code doesn't invoke anywhere. The Abc instance survives and is indeed not reachable, the leak report is correct.
66,364,540
66,454,771
How to use thread in c++ win 32
I want to use thread in C ++ like c # then what to do, I tried to do it but failed, hope the helping (Why can't I post, someone edit the content for me) Here is my c # code Thread[] threadsArray = new Thread[100]; public class Users { public ListView listView1; public string sName; public string sName2; ...
You define the object of the constructor in the constructor of the cMain class, which will call the constructor repeatedly. When creating the thread run, you passed a NULL parameter. I didn't see the declaration of this parameter in the run function. If you don't need it, please delete it. I removed some irrelevant c...
66,364,629
66,364,731
Capturing a reference to object causes segmentation fault
When capturing a reference by reference or by copy the call to name() causes segmentation fault. With std::bind there is no problem. Why? struct with_name { template<typename T> explicit with_name(T& t) : // name([&]{return t.name();}) name(std::bind(&T::name, &t)) {} std::functi...
The problem is not capturing a reference, but the return type of the lambda doesn't match the signature of std::function. Given [&]{return t.name();}, the return type would be std::string, but name expects returning const std::string&. Change the lambda to template<typename T> explicit with_name(T& t) : name([...
66,364,919
66,365,187
reduce the time complexity of below given code .The code working fine the problem is time complexity
/*The first line will consist of one integer T denoting the number of test cases. For each test case: The first line consists of two integers n and r, n being the number of elements in the array and r denotes the number of steps of rotation. The next line consists of N space-separated integers, denoting the elements o...
There is one non standard usage in your code: int a[n]; Despite being accepted as extensions by gcc, VLA are not part of C++ Now for your question: instead of moving all the elements of the array, one step at a time, just note that you should move all only once by r%n steps. This would greatly reduce the time comp...
66,365,316
66,365,417
Put Value to Empty Location in std::vector
I have this method public: void reserveMemory(int start, i32 space) { for (int index = start; index < start + space; index++) { this->memory.at(index) = (i32)0; } } and when this->memory.at(index) is empty it throws an error. How am I going to put a value to that location when the index is empty? N...
You don't need the loop, all you need is to resize the vector: void reserveMemory(int start, i32 space) { memory.resize(start + space); } The new elements that are created will be zero-initialized. Note that this kind of makes the name of the function (reserveMemory) wrong since you don't actually reserve memory, ...
66,365,531
66,419,367
What should I feed to real FFT functions in vDSP?
The function signature of vDSP_fft_zrop (actually most of FFT functions in vDSP) accepts two DSPSplitComplex structures as input and output. However, for real FFT calculations, forward FFT accepts an input of only real values, while backward FFT produces an output of only real values. So how should I fill the input/out...
You can represent real values as even-odd configuration that uses both the real and imaginary parts of the complex values. See Apple's Data Packing for Fourier Transforms article for a full discussion.
66,365,602
66,366,322
How to build a one command compile project by cmake which have submodules?
I have a project like this: (base) [tp]➜ ~ tree cmake_test cmake_test ├── CMakeLists.txt ├── src │   ├── CMakeLists.txt │   └── mycode.cpp ├── sub1 │   ├── CMakeLists.txt │   └── src │   ├── CMakeLists.txt │   └── somecode.cpp └── sub2 ├── CMakeLists.txt └── src ├── CMakeLists.txt └── s...
link_directories(${CMAKE_INSTALL_PREFIX}) You shouldn't need to do this. You should be able to just do: target_link_libraries(mycode somecode) and cmake knows that the mycode program requires the somecode library and it will automatically build somecode before it links mycode. If this doesn't automatically happen, ...
66,366,005
66,366,273
Problem with std::index_sequence_for as default argument?
The following C++20 program: #include <utility> #include <cstddef> template<typename... Args> class C { template<size_t... I> static void call( std::index_sequence<I...> = std::index_sequence_for<Args...>{} ) {} }; int main() { C<long int>::call(); } fails to compile with error message: test.cc...
In general template argument deduction + default function arguments cause a lot of trouble. To simply fix it you can go with this: #include <utility> #include <cstddef> template<typename... Args> class C { public: static void call() { call_impl(std::index_sequence_for<Args...>{}); } private: templ...
66,366,268
66,423,349
Openvino Loading up binary file into a blob
Hi I am working on an audio classification model. I have implemented in python, now I need to port it to c++. I do feature extraction in python as it is easier. I save these features, into a file. The feature is represented as a 2D array in numpy.(feature is not an image but one can think of it as as an image) I would ...
For the inference of non-image data, you can create the blob using the InferenceEngine::Blob classes. Here is the video on the example implementation of the Inference Engine main function call. https://www.youtube.com/watch?v=JwgPgKClU3w There is no specific example for an array as an input. Check out the following dem...
66,366,410
66,366,517
optional parameter based off boolean template parameter
I'm trying to declare a template function that... has 3 parameters if template boolean is true has only 2 parameters if template boolean is false Is this possible? The code below compiles, however both versions require 3 parameters. I need it to only need 2 parameters when the template boolean is false and the result...
Sure, you can do that through SFINAE; #include <type_traits> template <const bool EnableThird, std::enable_if_t<EnableThird, int> = 0> void dynamic_parameter_count(int one, int two, int three) { std::cout << "EnableThird was true\n"; } template <const bool EnableThird, std::enable_if_t<!EnableThird, int> = 0> voi...
66,366,900
66,367,201
In C++20, is a macro considered "active" if it's #undef'd, then #define'd again?
Consider #define VER 1 #undef VER #define VER 2 #if defined(VER) // #1 #error VER is defined #endif [cpp.import]/6: A macro directive is active at a source location if it has a point of definition in that translation unit preceding the location, and does not have a point of undefinition in that translation unit pre...
Let's see if I can lawyer that. The paragraphs above where the link points say: Each #define directive encountered when preprocessing each translation unit in a program results in a distinct macro definition. So, #define VER 1 is a definition, and #define VER 2 is a distinct one. 5.1 The point of definition of a m...
66,367,654
66,368,549
Runtime error when trying to display array of objects
So, I'm trying to create a card game in C++ and while trying to make sure that my arrays are working I'm getting a runtime error which says: Exception thrown at 0x7AD940D9 (vcruntime140d.dll) in Sabacc.exe: 0xC0000005: Access violation writing location 0x0BFE1052. I have no idea what this error actually means, but here...
the cards structure allocates indexes 0-59. In the first iteration the loop is okay but i modified a little for understanding better. You can understand which indexes are being allocated. In the print statement if you do not want to show the '0' you can start the loop from 1. Mainly the error was in line number 25 for ...
66,367,987
66,368,145
How to pass an abstract class as function parameter, which will then be used after the original goes out of scope?
I have the following abstract class struct Interface { virtual ~Interface() = default; virtual void Do() = 0; }; And I have one or more concrete class which implements Interface struct ImplA final: Interface{ virtual void Do() override {printf("DO IN ImplA\n");} }; struct ImplB final: Interface{ virtu...
Store a smart pointer within Container so that it controls the lifetime of the referred object: struct Container { std::unique_ptr<Interface> pointerToInterface; // What to do with the ctor, how to pass it Pass a smart pointer: Container(std::unique_ptr<Interface> i) : pointerToInterface(std::move(i)) {} ...
66,368,046
66,368,111
How should i solve this task?
I got the homework,i try to solve it,but i dont know why its bad. One of part of this code was a default: #include <iostream> using namespace std; /*##SOLUTION##*/ /*##SOLUTION##*/ int main() { Valami var; int i=var.ujszam(); cout<<i<<endl; cin>>i; var.tarol(i); var.print(); return 0; } ...
tarol is used as name of both a variable and a function. You have to give another name to one of them. example: class Valami { public:int tarol_var; // rename the variable public:int ujszam() { int i; cin>>i; return i; } public:void tarol(int ertek) { ...
66,368,061
66,368,509
error clearing an object of non-trivial type with memset
Well, the thing is simple, im getting warning: ‘void* memset(void*, int, size_t)’ clearing an object of non-trivial type ‘struct FormatHashBuffers(CBlock*, char*, char*, char*)::<unnamed>’; use assignment or value-initialization instead [-Wclass-memaccess] memset(&tmp, 0, sizeof(tmp)); on this function and idk why, whe...
You could default-initialize your member variables: struct { struct unnamed2 { int nVersion{}; uint256 hashPrevBlock{}; uint256 hashMerkleRoot{}; unsigned int nTime{}; unsigned int nBits{}; unsigned int nNonce{}; } block; unsigned char pchPadding0[64]{}; ...
66,368,156
66,429,213
Compile OpenCV + Gstreamer for others
I created a project which uses OpenCV and Gstreamer (receiving udp stream), It's working perfectly fine if open with Visual Studio (Run button). But after compiling Release x64 MT and trying I not only need to throw a whole lot of GStreamer .dll files to open my app but even after it opens successfully when It comes t...
Ok I found out, for some reason you need o move .dll files from GStreamer /bin folder to your application main directory, and in the previous folder copy GStreamer /lib folder /MyFolder /my app /*.dll /myapp.exe /lib *.dll-s from " \gstreamer\1.0\x86_64\bin " /lib from " \gstreamer\1.0\x86_64 " A w...
66,368,343
66,368,596
Upcasting/Downcasting to handle mutliple derived classes by base class
Let's say I have a base class and multiple derived classes and I want to avoid having multiple variables/functions for every derived class type. The only way I found to realize this is using up-/downcasting. But especially downcasting is often considered bad practice - so whats the way to go? Example: #include <stdio.h...
I feel like the best way to achieve this would be having a virtual method petted() in base class and override it in every subclass to suit the needs of that subclass. class Animal { // ... virtual void petted() { std::cout << "Petted general animal"; } } class Dog: public Animal { // ... void petted() { std::cout << ...
66,368,469
66,368,548
RAM leaks on stl containers?
I have a RAM limit on my project, as it contains a lot of data manipulation . The problem is, I noticed that calling std::set<std::pair<int64_t, int64_t>>::clear() does not actually free any memory. The code for reproducing the problem: std::set<std::pair<int64_t, int64_t>> stltest; for (size_t i=1; i<=250000; i++) { ...
Probably clear() just sets size() to zero, but does nothing with contents No. It destroys the elements and deallocates their memory. Can I get the memory back Sure, if you implement your own malloc and replace the standard one. In practice no, that's not a useful goal. I really need it. What do you think you need...
66,368,483
66,368,696
What determines which system calls a program makes?
So i have a C/C++ program which does not run a certain computer system simulator because it makes a system call that is not implemented in that simulator. Now I am wondering what determines what system calls a program makes. Is it only the compiler? or do things such as OS and hardware play a role as well. The simulato...
What determines which system calls a program makes? The source code of the program. The entire program including all the compiled sources that have been linked together. Including those that you didn't specify explicitly, most notably the the C system library where most system calls will directly originate. In case o...
66,368,590
66,383,803
Missing ws2def.h, from which package can I download?
I'm trying to compile a C++ project on Win10 Pro with Eclipse, MinGW and the POCO library. A POCO header include ws2def.h that is missing on my Laptop. From which package/library/website can I find this missing file ? MinGW seems not to install it...
That is not a POCO header. It is a Win32 API header. MinGW seems to have its own version of it.
66,368,940
66,370,347
Demonstrating a class that prints the combination of a string
I am dealing with a 'homework' problem however the professor isn't explaining anything so I can't offer a lot more. Direct quote of the question: "Create a class that prints the combination of strings. The program should use two constructors, the first constructor should be an empty constructor that will allow the dec...
Ok, so you could not understand all the requirements. I am not your teacher, so I can only tell you what I understand from your post. the first constructor should be an empty constructor that will allow the declaration of an array of string It is common to create an empty (also said default) constructor, because it i...
66,369,032
66,560,325
Send a kill signal to self
I have a C++ code that runs a linux command, I want to simulate segfault i.e. SIGSEGV while executing that linux command from by C++ code. So my code looks like this int main(){ string cmd = "some linux command that should throw seg fault"; execute_linux_comand(cmd); // Want to simulate segfault coming while ex...
Sending kill signal to self can by done by putting this command kill -9 $$
66,369,477
66,369,727
How to implement method chaining with inheritance?
My problem is that I can't chain methods from Derived class when I already used Base class methods. I tried to mix topmost answers from Returning a reference to the derived class from a base class method and CRTP and multilevel inheritance, but the problem is one of them is always returning the same object, the other i...
Not sure if it is what you want, but with C++17 and if constexpr, you might do: template <typename T = void> class Base { public: auto& a() { std::cout << "a\n"; if constexpr (std::is_same_v<T, void>) { return *this; } else { return static_cast<T&>(*this); ...
66,369,849
66,373,712
Run jar file use Qt (QProcess)
How can i exec jar app from qt (use Windows)? I know about QProcess, and i use that: QProcess myProcess; myProcess.setWorkingDirectory("D:\Programs\Qt\Units\MyJavaProjects\StackExp\target"); myProcess.start("StackExp-1.0-SNAPSHOT.jar"); myProcess.waitForFinished(); i show this message: D:\Programs\...
When you "run example.jar" you actually run java.exe -jar example.jar QProcess process; process.setWorkingDirectory("D:\\Programs\\Qt\\Units\\MyJavaProjects\\StackExp\\target"); process.setProgram("java.exe"); process.setArguments({"-jar","StackExp-1.0-SNAPSHOT.jar"}); process.start();
66,370,264
67,284,551
Complex matrix exponential with Armadillo library
I'm doing some physics simulation in C++ using Armadillo. I need to calculate a product looking like: Q = R * exp(neg_i*Lambda*t) * R.t() * Q Where Q,R are cx_mat class of the same size, Lambda is a mat class of the same size as Q,R and is diagonal, neg_i is -i the complex number and t is a double. I should get a uni...
You need to use the expmat() function for a matrix exponential, exp() calculates an element-wise exponential. For example, some code I'm currently using for a physics simulation: arma::cx_mat f; // A hermitian matrix double delta_t ; // A time step std::complex<double> i_imag(0.0,1.0) ; // i, the imaginary number s...
66,370,380
66,371,133
Does C++ have a data structure like a Python dictionary?
I am new to C++. I use a Python dictionary to store the data previously, now I am working on C++. Does C++ also have a data structure like Python's dictionary? My scenario is as follows, We have 4 flows in the network and assign a route to each flow. Thus, in python we can: dictFlowRoute = {"flow1":(1,2,3,4), #flow1...
Python's Dictionary data type is an associative array. In C++, we have two options to choose from, std::map and std::unordered_map. The main difference is that std::map uses a Self Balancing Red-Black Tree and std::unordered_map uses a Hash Table implementation. And because of this, std::unordered_map is generally fast...
66,370,757
66,370,822
Default struct construct with another constructor
The following code doesn't compile because the instance parameters don't match the constructor parameters. If I remove the constructor it compiles and runs. I would like to be able to use it in either way - constructing with string or direct member variable initialisation. (This is a minimal version of what I'm really...
What you want is not possible. Your options are: Don't define constructors and use aggregate initialisation. Define constructor for each set of arguments you want and implement them to behave exactly as you want to. The options are mutually exclusive. Do I need another constructor with an initialiser list or similar...
66,370,969
66,371,274
How can I stop C++ program?
I made a program that prompts the user to guess numbers (which I have programmed to produce a random number)ranging from 1-10, if the user guesses the number successfully which is the same as the random number generated it prints "congratulation", else it prompts the user to try again. but I want to stop the user from ...
You could count the number of times the user answers and stop when it has executed for the number of times you want. //prompt the user for numbers ranging from 1 - 10 cout << "type in a number from (1 - 10)\n"; cin >> b; int answer_count = 1; // variable to count answers (there is already 1 answer here) const int max_a...
66,371,134
66,372,520
Boost::units with non SI units
This is driving me nuts. I'm trying to do something simple: Convert between si::meter and US foot. I can do do: quantity<si::length> l = 1 * si::meters; but there doesn't seem to be a US based system, e.g. I cannot find quantity<si::length> l = 1 * us::foot; Is that correct? What is the intended use of the US base un...
After a lot of staring at the radar_beam_height.cpp example, I came up with the following solution: #include <boost/units/base_units/us/foot.hpp> #include <boost/units/io.hpp> #include <boost/units/quantity.hpp> #include <boost/units/systems/si/length.hpp> #include <iostream> namespace us { typedef boost::units::make_...
66,371,842
66,372,731
Custom object's vector attribute median c++
I am trying to find the median value from the third attribute of my objects. My objects are in a vector. std::vector<Object> obj = { Object {V , H , 5}, Object {C , B , 2}, Object {D , F , 6}, Object {B , H , 4}, Object {B , H , 4} }; answer: 4 I tried to use the nth_element method but it ...
By default, std::nth_element() applies the operator< to the dereferenced iterators provided as arguments. In C++, there is no operator< defined for custom classes but the author is free to define (overload) one. Alternatively, std::nth_element() can be called with a custom less predicate to force a specific order. Cou...
66,371,922
66,382,714
How to include "<>" cascading headers
I'm trying to use SWIG to be able to use C++ code as a Go module. My folders are organized as this: MyLib/ -go-integration -basic_host -basic_host.i -basic_host_wrap.cxx // gen by SWIG -basic_host_wrap.h // gen by SWIG -basic_host.go // gen by SWIG -MyLib/ -...
This is what I was suspecting, SWIG uses gcc and cgo to produce the files and you can add as an environment variable CGO_CPPFLAGS that is the path to your include files. $env:CGO_CPPFLAGS="-I D:/Repos/MyLib/MyLib/include" I also tried with the command -I of SWIG like this : swig -go -cgo -c++ -I"D:/Repos/MyLib/MyLib/i...
66,372,303
66,372,431
How do I determine if a type is memcpy-save?
I work with colleagues who like memcpy (too) much. I am porting code which generally deals with simple types (doubles mostly), which can be safely copied using memcpy, extending it to non-trivial types. I wanted to write a simple copy function which does the right thing depending on the type in question: #include <stri...
The correct type trait to use for this is std::is_trivially_copyable, not std::is_trivially_copy_assignable. To fix the warning, use if constexpr instead of if in order to perform the check at compile time and only generate one of the two branches as unconditional logic for a given type T. Even if an ill-formed call is...