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
63,689,965
63,698,311
Bellman ford single source shortest path for adjacency matrix not detecting negative cycle
I have tried implementing Bellman ford Single Source Shortest Path for adjacency matrix, but it is not detecting one of the vertices in the negative cycles the same algorithm works for edge list, but gives error in adjacency matrix This is what the graph looks like: My code: #include <iostream> #include <climits> #inc...
In the second loop, dist[i] + matrix[i][j] may exhibit unspecified behavior by way of integer overflow if dist[i] is already set to INT_MIN and matrix[i][j] is negative. In practice, the sum wraps around to a large positive number, and then the condition dist[j] > (dist[i] + matrix[i][j]) doesn't hold, and dist[j] is n...
63,690,501
63,691,808
Openssl EVP "EVP_CTRL_GCM_GET_TAG" fails
I am using Openssl EVP in C++. Somehow getting the tag failes. My Code: int do_crypt(FILE *in, FILE *out){ unsigned char inbuf[1024], aadbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH]; int inlen, lenbuf, unused, outlen; EVP_CIPHER_CTX *ctx; unsigned char key[] = "0123456789abcdeF"; unsigned char iv...
There are two bugs in the code: Since sizeof is used to determine the length of the IV, the 0-terminator is counted as well and the wrong length 13 is determined. Instead of sizeof, strlen must be applied, which returns the correct value 12. The context is released before the tag is determined, i.e. EVP_CIPHER_CTX_fre...
63,690,513
63,692,050
Using boost c++ to read a serial port, how should I decode the data?
I am trying to create a simple app that reads data from a serial port. I have the structure of the data, it is as follows: Byte Function Format Example Hex 0 Header ASCII Char I 49 1 Header ASCII Char W 57 2 Header ASCII Char A 41 3 Header ASCII Char P ...
You can use the structure provided in order to parse the data. The blank spaces that you're seeing are most likely due to ASCII interpretation of binary data. The clue that this is binary data is that the writer is specify byte position. Here's how I would approach parsing this data. First, create a structure that m...
63,690,731
63,691,917
Use default template parameter of one template declaration in another
Let's assume I have a class template cls1 with some default template arguments and another class template cls2 that uses cls1: template<typename T1, typename T2 = int, typename U = std::vector<T1>> class cls1 {}; template<typename T1, typename T2 = int, typename U = std::vector<T1>> class cls2 : public cls1<T1, T2, U>...
I dont think there is a way to avoid verbosity completely. Similar to function default arguments, you can't really get your hands on templates default arguments without some added effort. This is the best I can come up with: template<typename T1, typename T2 = int, typename U = std::vector<T1>> class cls1 { using v...
63,690,927
63,691,132
Implementation of Queue using Arrays in C++
I have written this code and am confused about why is it showing segmentation fault. I think my dynamic memory allocation is causing problems for me here. Can anyone tell me what is causing the segmentation fault in here and how to improve the code. Also, please tell me if I can create the object with the ClassName obj...
Your code have at least 3 problems: Firstly, Queue* queue=new Queue(); will lead to compilation error because no default constructor is defined and another constructor is defined in the class Queue. To fix this, you should do one of: Change this line to match the defined constructor like Queue* queue=new Queue(1024);...
63,691,187
63,694,505
Cygwin - Blocking on opening a named fifo causes another thread to block on opening a regular file
A blocked open of a named pipe in Cygwin causes another thread to hang when it tries to open any file, including a simple text file. The below code reproduces the issue on cygwin 3.1.6(0.340/5/3), and works fine (does not hang) on RHEL 7. #include <unistd.h> #include <limits.h> #include <stdio.h> #include <thread> #inc...
On Cygwin the open syscall locks the file descriptor table for the entire duration of the syscall. Which means all open syscalls are essentially sequentialized. See syscalls.cc/open(): extern "C" int open (const char *unix_path, int flags, ...) { . . . cygheap_fdnew fd; // <-- here And cygheap.h: class cy...
63,691,234
63,693,293
What is a Eigen::array (not Eigen::Array)
I'm using eigen tensor library and it seems to me that shuffle() method wants as input an object Eigen::array<type,int>. In my implementation I have a std::list of int I need to pass to shuffle (of course I know the second int param (the rank) only at runtime!)
Not long ago Eigen's Tensor module was C++03 compatible. That implies that std::array is not available. For that reason the Tensor module defined its own Eigen::array class that is in fact a typedef for std::array if C++11 is available. The file unsupported/Eigen/CXX11/src/util/EmulateArray.h contains something that bo...
63,692,267
63,692,464
C++ Classes for High Performance Computing
According to this Quora forum, One of the simplest rules of thumb is to remember that hardware loves arrays, and is highly optimized for iteration over arrays. A simple optimization for many problems is just to stop using fancy data structures and just use plain arrays (or std::vectors in C++). This can take some gett...
If your class looks like this: struct Person { double age; double income; size_t location; }; then you might benefit from rearranging to std::vector<double> ages; std::vector<double> incomes; std::vector<size_t> locations; But it depends on your access patterns. If you frequently access multiple elements of a p...
63,692,572
63,692,632
std::mt19937 gives the same random float for identical first float numbers ex(1.2, 1.5)
I have this random-float function that looks like so: float randomFloat(float input) { std::mt19937 mt; mt.seed(input); std::uniform_real_distribution<float> dt(-1,1); return dt(mt); } as you can see the function takes an input and return an output between -1 and 1 but my problem is that when I give a...
The seed value expected is an unsigned integral type; passing a float is really just passing the truncated integer value of said float. You can derive this from the signature of seed, which returns result_type, and from the documentation of result_type: result_type - The integral type generated by the engine. Results ...
63,692,761
63,692,814
Allocator-related error when passing lvalue to a universal reference parameter that is used as template parameter to a temporary std container
I have stripped down my use case to a minimal meaningless example: #include <vector> template<typename Container> void f(Container&) { // using && gives compilation error... (*) std::vector<Container>{}; }; int main() { std::vector<int> v; f(v); // (*) ... which is "solved" by std::move-ing v here. Why? }...
When you have template<typename Container> void f(Container&) { // using && gives compilation error... (*) std::vector<Container>{}; }; Constainer is deduced as a std::vector and all is well. When you use template<typename Container> void f(Container&&) { // using && gives compilation error... (*) std::vector...
63,693,003
64,441,323
Cannot get hyperlink from winword document: TYPE MISMATCH
I have the following code in my COM Add-In for MS Office to go through all hyperlinks in winword document and then parse them: ... HRESULT hr; ULONG nRet; CComQIPtr<MSWORD::Hyperlinks> hylinks = doc->Hyperlinks; // CComQIPtr<_Document> doc ATLASSERT(hylinks); IEnumVARIANTPtr pEnum = hylinks->Get_NewEnum(); for (int...
Finally, found out. How many collections have office application, so many ways to iterate them. Here we can do it like following, assign index of type VARIANT manually, not with enumerator: CComQIPtr<MSWORD::Hyperlinks> hylinks = doc->Hyperlinks; // CComQIPtr<_Document> doc ATLASSERT(hylinks); for (int i = 1; i <= hy...
63,693,185
63,693,801
How to get TableView with exapanding columns
I'm trying to get TableView (the new one from pure qml introdudced in qt5.12) with column which resize them dynamically to fill extra available space but It's not working here is my minimal reproducible example:- main.qml:- import QtQuick 2.15 import QtQuick.Controls 2.15 import QtQuick.Window 2.15 Window { id: wi...
Restating my comment as an answer: For performance reasons, TableView does not re-calculate its row height or column width unless absolutely necessary. But you can force it by calling forceLayout() whenever the width changes. onWidthChanged: forceLayout()
63,693,871
63,694,106
If I create a vector on the heap, does that mean I could access it from any other function? How?
This statement creates a vector on the heap: std::vector<int>* pVector = new std::vector<int>(); So, if I declare it in main() or somewhere, how can I access it in another function? For example: #include <iostream> #include <vector> void insert(int value); int main (){ int n = 1; std::vector<int>* pVecto...
This has nothing to do with heap usage. pVector is simply a local variable to main(), so only main() can use it. The only way to access the std::vector object from any other function is to explicitly pass in a pointer/reference to it. You could pass it in using an input parameter, eg: #include <iostream> #include <vec...
63,694,092
63,694,245
C++ CreateDirectory() not working with APPDATA
I want to create a directory inside the %APPDATA% folder. I am using CreateDirectory() for this and it doesn't work. I debugged the code and it seems like the path is correct, but I can't see a new directory in my the APPDATA. My code for creating dit in appdata: void setAppDataDir(std::string name) { char* path; ...
CreateDirectory() is a macro that expands to CreateDirectoryW() in your case, which requires strings in UTF-16LE encoding (wchar_t*). You are casting the const char* path param to PCWSTR (const wchar_t*): CreateDirectory((PCWSTR)path, NULL) ... But you are not converting that string into a UTF-16LE string. So, you nee...
63,694,643
63,694,841
should pragma once be on top of every header as default
I'm learning C++ and I have encountered (and fix) what seems to be a very classic problem : g++ main.cpp A.cpp B.cpp -o out In file included from B.h:1, from main.cpp:3: A.h:1:7: error: redefinition of ‘class A’ 1 | class A { | ^ In file included from main.cpp:2: Which from a quick res...
To me this suggest that I should start every header with #pragma once !!! Wich can't be right is it? It can be right. Although it may in theory be a slight exaggeration. Is it common practice? Yes, it is. It is fairly universal if we include the other option of using a macro header guard into same practice. If so,...
63,695,032
63,695,216
C (avr-gcc is C with classes and new/delete) - Best way to not allocate memory for non-instatiated classes on microcontroller
I've got a variety of different PCBs each with an AtMega2560 microcontroller using a avr-gcc/ C compiler (using Arduino 1.8.12 compiler, which has classes, new, delete but not vector and such). My firmware is the same for all of the PCBs, which is really nice because a single EEPROM byte allows the PCB to select it's ...
I would consider a union. Something like: struct PcbCommon { char pcbName[32]; unsigned version; char sn[200]; uint8_t some_big_common_array[100]; ... }; struct PcbA { uint8_t some_big_array_specific_to_PCB_A[1000]; ... } struct PcbB { uint8_t some_big_array_specific_to_PCB_B[500]; ...
63,695,080
63,695,779
LPCWSTR ERROR C++ argument of type is incompatible with parameter of type
#include <iostream> #include <WS2tcpip.h> #include "sharedmemory.h" #pragma comment (lib, "ws2_32.lib") using namespace std; #define MAP_OBJECT_NAME "$pcars2$" void main(int argc, char* argv[]) { HANDLE fileHandle = OpenFileMapping(PAGE_READONLY, FALSE, MAP_OBJECT_NAME); I am relatively new to C++, and I happe...
TCHAR is defined as either wchar_t or char, depending on whether UNICODE has been defined or not in your project setup, respectively. OpenFileMapping() is a TCHAR-based preprocessor macro. It is defined as taking a const TCHAR* pointer to a null-terminated string in its 3rd parameter. In reality, what happens is that ...
63,695,820
63,695,932
Setting icon in Win32 dialog to a default icon
I have an icon in a custom dialog box which I would like to be one of the icons which can simply be accessed via macros, such as MB_ICONERROR or MB_ICONINFORMATION. I know these are of course C(++) macros, so they can't just be writen into the .rc file, but I would like to display the file which they correspond to in m...
The LoadIcon function is able to load those standard icons. E.g. LoadIcon(nullptr, IDI_ERROR) returns the same icon that MB_ICONERROR gives you in the standard message box. To display them in your own dialog box, use a static control with the SS_ICON style set, and then use the STM_SETICON message to assign the icon to...
63,696,400
63,696,476
Why am I getting "warning: returning reference to local temporary object"?
I'm getting warning: returning reference to local temporary object from clang compiler on code bellow and I'm not sure why. (code on gdbolt) <source>: In member function 'const int& Full_Coord::r() const': <source>:29:41: warning: returning reference to temporary [-Wreturn-local-addr] 29 | int const& r() const...
That is because the SpecialId and OtherId are uint32_t, and since your function returns int it must be implicitly cast so a temporary is created. Either change the return types of Full_Coord::r and Full_Coord::ls to SpecialId and OtherId respectively, or use auto as a return type. auto const& r() const { return xy_r.r(...
63,696,489
63,697,392
map::const_iterator mapped type is not const
I'm trying to write an iterator adaptor for a class built on top of a map. I'm having issue when trying to get the mapped type from the iterator type. Basically I'd like to get: map<Key,Val>::iterator --> Val map<Key,Val>::const_iterator --> Val const Here is a minimal repro. #include <map> #include <type_traits> ...
For almost all practical purposes, types you might want to deduce is tied to some expression, in which case decltype is always the answer template<typename T> using mapped_type = std::remove_reference_t<decltype((std::declval<T>()->second))>; using m = std::map<char, int>; using i = mapped_type<m::iterator> // int us...
63,696,934
63,698,889
Stencil Test doesn't seem to do anything
It seems that no matter what I do the stencil buffer has no effect on what I'm drawing. I'm drawing two rectangles, one is drawn over top of the other and slightly off of it. The part where they intersect is the only thing I want to be displayed. This would achieve what I want for my scrollable areas for my UI. Here...
Your window (default framebuffer) doesn't have a stencil buffer at all. You have to setup a OpenGL window with a stencil buffer by using the sf::ContextSettings class. See Using OpenGL in a SFML window: sf::ContextSettings settings; settings.depthBits = 24; settings.stencilBits = 8; settings.antialiasingLevel = 4; sett...
63,697,228
63,697,320
Why do you split the definition and declaration of functions in c++?
I usually code in Java, but I have started to learn c++ as I'm trying to get into some competitive programming. What is confusing for me right now is that in java you can declare a method within a class, make it public and thats that. For example, in Java: public class Main{ public int javamethod(int myNum){ ...
There are 3 reasons: Function must be declared before it can be called. So if you have fun1() calling fun2() and vice versa you cannot write implementation for each upon declaration. To hide dependencies. If implementation is dependent on some include and you don't want to require every user of the function to includ...
63,697,624
63,702,849
Problem downloading an image with Poco C++
I am trying to download an image from a url link via Poco in C++ but has encountered a problem with it. It always catches a NoMessageException whenever the code below is ran (the receiveResponse part). The 2 code blocks below is referred from: https://www.codeproject.com/articles/252566/learning-poco-get-with-http and ...
Your problem is that you are using HTTPS URI. Your code works with modified HTTP URI: http://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png If you want to use HTTPS, use code below, linked with PocoNetSSL library. #include <Poco/MD5Engine.h> #include <Poco/DigestStream.h> #include <Poco/Net/...
63,697,777
63,697,830
C++ delete pointer when referencing to a variable
I do not quite understand about using the pointer in C++. My example code and question are below: int main() { int *ptr1, *ptr2; int val1, val2; ptr1 = new int; val1 = 45; ptr1 = &val1; ptr2 = ptr1; cout << *ptr2; delete ptr1; //Crashed } The reason why it got runtime error because I t...
You may only pass to delete something you got from new. You didn't save the value you got from new since you modified ptr1 to contain &val1. So you cannot delete it and thus your code has a memory leak. You can fix it like this: int main() { int *ptr1, *ptr2, *ptr3; int val1, val2; ptr1 = new int; ptr3 ...
63,697,959
63,699,376
Azure DevOps YAML self hosted agent pipeline build is stuck at locating self-agent
Action: I tried to configure and run a simple c++ azure pipeline on a self-hosted windows computer. I'm pretty new to all this. I ran the script below. Expected: to see build task, display task and clean task. to see hello word. Result: Error, script can't find my build agent. ##[warning]An image label with the label W...
Since you are using the self-hosted agent, you could use the following format: pool: name: Default demands: - agent.name -equals Weltgeist Then it should work as expected. You could refer to the doc about POOL Definition in Yaml.
63,698,129
63,698,793
Characters after a space is not being printed out
I was using character arrays to get inputs from the user then display the output afterwards. However, every time I enter values with spaces in between, only the first word before the space is printed. For instance, this is what I typed: Customer No.: 7877 323 2332 This will be the output: Customer No.: 7877 I alrea...
Another option is to use std::basic_istream::getline to read the entire string into the buffer and then remove the spaces with a simple for loop. But when using plain-old character arrays don't skimp on buffer size. It is far better to be 1000-characters too long than one-character too short. With your input, your abso...
63,698,208
63,698,524
Successful dereference seems to cause a latent segfault
As mentioned in the title, I'm successfully dereferencing the data coming to and from the modMYSTRUCT and showMeThis functions. The proper output before "Fourth check" displays but a segfault occurs: First check Second check 0 Third check Segmentation fault (core dumped) This doesn't happen, however, when I comment fr...
Replace your MYSTRUCT with this: struct MYSTRUCT { int * num; MYSTRUCT() {num = new int;} // allocate memory for an integer ~MYSTRUCT() {delete num;} // free memory (will be called when struct_inst goes out of scope) }; But honestly, just because you can do this, doesn't mean you should...
63,698,322
63,699,639
Copy only row indices of Mat from findNonZero function in C++ OpenCV
I am trying to convert MATLAB code to C++. In MATLAB, I use the find function to get the indices of a vector and then copy these to other variables. For example: idx = find(A>s); B = idx; % A, idx, and B are vectors; s is a scalar In C++ OpenCV (C++14 / OpenCV 3.4.10) I know I can use the findNonZero function, but it ...
MATLAB's find determines the column-major indices of where values are nonzero in the input matrix. This is true if you specify the single output version of it. If you provide two output variables, that generates both the row and column locations of the nonzero values in the input. In your example you have provided th...
63,698,324
63,699,554
How to check the count of function template instantiations
How to check the count of function template instantiations? template <typename T> void foo(T f) {} struct Bar { void operator()(bool x) {} }; void f1(bool x) {} void f2(bool x) {} int main() { foo(f1); foo(Bar()); foo(f2); foo([](bool x){}); foo([](bool x){}); }
I took this as (a kind of) puzzle assuming that OP is asking out of curiosity. To achieve this, I intend to add something to template foo() that is called for each template instance exactly once. The construction of a static instance is an option for this. The second part of the solution is to let each of these static ...
63,698,433
63,698,459
How to enforce contract on template parameter
How can I specify template parameter to be of a certain type i-e it must have implemented an interface (the template parameter must be a derived class of a specific base class) Heres the interface (abstract base class) class baseActionCounter{ public: virtual int eat()=0; virtual int drink()=0; }; Now I want my templa...
Yes, you can use std::is_base_of to check the type, e.g. template <class counterType, std::enable_if_t<std::is_base_of_v<baseActionCounter, counterType>>* = nullptr> class bigBoss { Or template <class counterType> class bigBoss { static_assert(std::is_base_of_v<baseActionCounter, counterType>, "counterType must de...
63,698,567
63,698,989
How to add argument to stream buffer c++
I just want a way to have a function ( or anything else ) which have one standard argument and another one coming from the operator <<. my_comp(argument) << "HelloWorld" ; The goal is to purpose a Logger class that any other class can easily extends and call its unique functionality with a single line of code. The Log...
#include <iostream> struct foo { int bar; foo(int bar) : bar{ bar } {}; foo& operator<<(std::string baz) { std::cout << bar << ' ' << baz; return *this; } }; int main() { foo(42) << "Hells in the World!\n"; } Makes sense? No? Question answered?
63,698,653
63,699,387
Forward declaration not working in c++. It says initialization of incomplete type
I am learning design patterns and I am trying to implement builder pattern. For this purpose I am compiling below code with "clang++ -std=c++17" but I am getting error "error: initialization of incomplete type 'HtmlBuilder'" where I am returning in static function HtmlElement::build. How to solve this issue? class Html...
As the first comment points out you need to separate the declaration from the definition, otherwise the compiler is forced to tackle both at once, as they're given. In your original code: class HtmlBuilder; class HtmlElement { friend class HtmlBuilder; public: static HtmlBuilder build(const string& root_name)...
63,699,045
63,699,138
for a static member initialization outside its class declaration, is it necessary to provide its type?
I have a class in Game.h: class Game { public: ~Game (){} bool init(const char* title,int xpos, int ypos, int width, int height,bool fullscreen ); void render(); void update() ; void handleEvents(); void clean(); void draw(); static Game* Instance(); // a function to acces the p...
I have a static variable initialization like the following Game* Game::s_pInstance = 0; This description is incomplete. More accurate: you have a static variable definition, and an initialization is part of this definition. The initialization does not need to mention the type, but the definition does. Syntactically,...
63,699,318
63,699,504
how to compile dlib and its examples in debug mode (in ubuntu)?
I'm trying to use ddd (a kind of graphic debugger, using gdb inside) to analyze the dlib , a c++ machine learning library running the dnn_face_recognition_ex example program. Under the example directory, I did # mkdir build # cd build # cmake .. # cmake --build . --config Debug but when I run ddd --args dnn_fa...
I found http://devdoc.net/c/dlib-19.7/compile.html and tried (under examples/build) g++ -std=c++11 -O2 -g -I../.. ../../dlib/all/source.cpp -lpthread -lX11 ../dnn_face_recognition_ex.cpp -o dnn_face_recognition_ex and now I can run it in debug mode by ddd --args dnn_face_recognition_ex ../faces/bald_guys.jpg
63,699,529
63,712,243
Any recommendation in using smart pointers for COM-lite objects in C++/WinRT component?
C++/WinRT provides 3 flavors of smart pointers to use for COM objects - Microsoft::WRL::ComPtr, com_ptr, and ATL-based CComPtr. In my case, it is a COM-lite object, meaning it is NOT an in-proc or out-of-proc COM object, it is created as a C++ object. In that case, which smart pointer should I use in a C++/WinRT compon...
Whether using "true COM" or "COM lite" (a.k.a. "nano-COM"), you track the lifetime the same way using the IUnknown methods AddRef and Release. The various COM smart-pointers all rely on the IUnknown methods, so you can you whichever one you want. For C++/WinRT applications, the recommendation is to use winrt::com_ptr. ...
63,699,663
63,700,017
In c++ does greater_equal<double> have a type of function<bool (double, double)>
my understanding is that greater_equal<double> is a functor that has a signature of function<bool (double, double)>, so I have tried to perform the following, #include <functional> #include <memory> using namespace std; int main() { std::shared_ptr<std::function<bool (double, double)>> f; auto f1 =make_shared...
What you wrote would work if std::greater_equal<double> and std::less_equal<double> inherited from std::function<bool(double, double)>, which they don't do. But since std::function<bool(double, double) is constructible from an instance of std::greater_equal<double> (and less_equal), you can do this instead: auto f1 = s...
63,699,980
63,700,755
Copy constructor on C# struct, that works like a C++ copy constructor
Is it possible to have a copy constructor on a C# struct, that works like a C++ copy constructor? Because mine isn't working. Specifically, it's not being called automatically during an assignment, as would happen with a C++ copy constructor. struct TestStruct { public TestStruct(TestStruct other) { // ...
Since others have already answered the question about how to call the "copy constructor" (which would be to pass the other instance to the constructor: TestStruct B = new TestStruct(A);), I'll try to answer the other questions. "Can you have a copy constructor for a C# struct, that works like a C++ copy constructor?" ...
63,700,581
63,700,644
Is this legal template lambda syntax?
While refactoring some legacy code, I came across this traditional implementation of a predicate to be used in STL algorithms: template<bool b> struct StructPred { bool operator()(S const & s) { return s.b == b; } }; I was tired and hitting the Ballmer Peak, so I accidentally rewrote it into a lambda like this, wh...
template<bool b> auto lambda_pred = [] (S const & s) { return s.b == b; }; This is not really a template-lambda, it is rather a variable template which is assigned to a lambda. It is not equivalent to adding template parameters to the implicitly declared Closure struct which has this lambda as a call operator (the tra...
63,700,658
63,700,737
Why Overflow is not in circular fashion
why incase of boolean, overflow doesn't occur in circular fashion. eg say a=126 when you reach 128 and you increment it, a goes to -127 if range is -127 to 128. similarly for boolean it is 0 to 1 so it should move around 0101010101 and so on. please clarify using namespace std; int main() { bool a; for (a = 1; a...
From cppreference If the operand of the pre-increment operator is of type bool, it is set to true If the operand of the post-increment operator is of type bool, it is set to true Note that this behaviour was removed in C++17 and your code won't compile with newer standards (probably because it was confusing).
63,700,713
63,700,980
Two processes handling their own lines of code in one main function (c++)
So my task goes like this: The program needs 2 processes in one main function First process creates or opens a file "log.txt" which is in the same directory where the program is located. Then it adds user input to this file. Second process is a "monitor" of this file. It checks if the file exists, shows its size and s...
Assuming you have a separate helper.exe, you can do: CreateProcess(nullptr, "helper logger-mode", ...) and CreateProcess(nullptr, "helper monitor-mode", ...) This will create two processes that see either logger-mode or monitor-mode in their second argument (argv[1]).
63,701,056
63,701,370
Why reserve memory in the structure?
I often see structures in the code, at the end of which there is a memory reserve. struct STAT_10K4 { int32_t npos; // position number ... float Plts; Pxts; float Plto [NUM]; uint32_t reserv [(NUM * 3)% 2 + 1]; }; Why do they do this? Why are some of the reserve values dependent...
This would typically be to support variable-length records. A couple of ways this could be used will be: 1 If the maximum number of records is known then a simple structure definition can accomodate all cases. 2 In many protocols there is a "header-data" idiom. The header will be a fixed size but the data variable. ...
63,701,498
63,701,988
When is a floating point operation 'invalid'?
Consider (both msvc15 and 16 i.e. Visual Studio 2017 & 2019) on a Xeon 15something: int main() { unsigned int x; uint8_t val; float f; x = _status87(); // x = 0 here, OK f = -1.00e+9; x = _status87(); // x = 0 here, OK val = uint8_t(f); // val = 0 here, I can live with that x = ...
In the generated assembly, we can see that for the conversion is used the instruction cvttss2si. The documentation for this instruction reads: Converts a single-precision floating-point value in the source operand (the second operand) to a signed double-word integer (or signed quadword integer if operand size is 64 bi...
63,701,741
63,701,999
Sorting a Linked List in ascending order and printing sorted List
I am trying to sort a linked list in ascending order and stuck at this point here. THe rest of the code is working fine (appending, prepending functions). I was trying to use the bubble sort algorithm here. However, the output shows segmentation fault. What am I doing wrong over here? void sortLinkedList(Node** head_re...
You have Node* temp=NULL; and then you temp->data=fast_node->data; and it goes BOOM because temp is a null pointer. If you're going to swap the nodes' data, you don't need a whole node, just one of whatever type data is: if(fast_node->data>fast_node->next->data) { whatever_data_is temp = fast_node->data; ...
63,701,851
63,702,598
std::set::erase unexpectedly erases 3 elements
Before the last erase, the elements in the s1 and s2 are the same. The last erase to the s1 erases 1 element in the set s1. It is correct. The last erase to the s2 erases 3 elements in the set s2. It is unexpected. #include <iostream> #include <cstdlib> #include <cassert> #include <set> #include <functional> using nam...
lr_cmp is not a strict weak order. Amongst other failings, it isn't transitive. Requirements if lr_cmp(a,b)==true and lr_cmp(b,c)==true then lr_cmp(a,c)==true This is not the case, e.g. Ev a {1, 1, 3, true}; Ev b {1, 3, 4, true}; Ev c {0, 4, 5, true}; std::cout << std::boolalpha << lr_cmp(a,b) << lr_cmp(b,c) << lr_c...
63,701,911
63,702,034
How can i instantiate a static member method template of a class?
I want to instantiate My::name() method for different types passed to it: #include <string> #include <iostream> namespace prw { class My { public: template <typename TYPE> static std::string name(TYPE v); }; } std::string prw::My::name(int v) { return "Ok"; } int main() { std...
You are trying to specialize the template, not instantiate it. The syntax for specialization would be: template<> std::string prw::My::name(int v) { return "foo"; } // And if you want to further specialize for other types: template<> std::string prw::My::name(bool v) { return "bar"; } Specialization defines ho...
63,702,046
63,707,936
How to debug and step into custom language sources transpiled to C++?
I would like to use a custom preprocessor language along with C++. My sources would be first transpiled to valid C++ with my custom transpiler, then compiled with a regular C++ compiler. Example: my_transpiler -o source_gen.cpp source.mycpp g++ -o myapp source_gen.cpp In that scenario, the debug information generated ...
As was hinted in a comment to the question, the usual approach to this issue is the #line directive. In particular, # line digit-sequence " s-char-sequenceopt " new-line Your transpiler should put this directive for each source line in the original file into the generated file: #line 3 "source.mycpp" If your C++ comp...
63,702,224
63,702,506
C++ Vector become empty in instance class after pushing some data
class Bank { private: string bankName; vector<Account> accounts; public: Bank(string name){ bankName = name; } Account registerAccount(string name){ Account account(name, rand()); accounts.push_back(account); return account; } void checkMyAccount(Account account){ cout << a...
So the problem is that you have two different bank objects Bank bank("BCA"); Account customerAccount = cust.requestAccount(bank); Account requestAccount(Bank bank){ return bank.registerAccount(name); } The bank object in requestAccount is a copy of the bank object in main. So you add an account to the copy but not ...
63,702,594
63,712,944
combining C\C++ translation units state?
I have a main.c file which includes a guarded (#ifndef...) c header, called mydefinitions.h. In the header i declare an extern function, lets call it CppMain, to which i then call from the main.c file. The CppMain function is defined in cppmain.cpp file which includes the (guarded) mydefinitions.h file as an extern "C"...
What's happening is that every object file compiled from source contains both the integer GLOBAL_STATE as well as a runtime initialiser for it. You only need it defined once. In the header file, declare the variable extern: extern unsigned int GLOBAL_STATE; In your main C file, define it: unsigned int GLOBAL_STATE = ...
63,702,648
63,704,989
QProcess doesn't run with spaces in path
I've run into a problem with starting a QProcess where the path contains spaces. The general goal is to run other program (at the moment on Windows, but macOS would be great, too). I tested multiple different paths and it seems that only paths without spaces work. This works: QProcess *process = new QProcess(); process...
If you set program and arguments separately Qt will figure out the correct quoting for you. Note the list of arguments, each will be exactly one argument in the target process: QProcess *process = new QProcess(); process->setProgram("C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe"); process->setArguments(QStr...
63,702,922
63,703,169
Doubts about classes and polymorphism
I'm trying to build a hash table class in C++ using the chaining method, a minimal example class is: template <class V> class HashTable { ...
TL;DR - the answer to all questions is "use templates, not polymorphism". A natural choice for me would be to use polymorphism for the hash function in the following way (mind that I have limited experience with classes and polymorphism): But this won't work because the operator()(string name) in StringHashFunc has di...
63,703,117
63,703,520
VSCode "variant is not a template", how to make vscode detect it?
I am writing a simple structure in using vscode in c++ #include <variant> using namespace std; struct Entry { string name; variant<double,int> v; }; I am using the C/C++ extension by Microsoft. Despite the fact that it's compiling just fine, somehow the extension is unable to detect the variant class. How do I fix...
Found it! Go to Extensions > C/C++ > Gear Icon > Extension Settings In upper search bar add "standard" Look for the "C_Cpp > Default: Cpp Standard" entry. Click on drop-down list and select the highest c++ standard that you need. Reload and the error goes away. The Same goes for this kind of problems in C. It seems l...
63,703,637
63,705,291
How to efficiently permute an array in-place (using std::swap)
How can I apply a permutation in-place? My permutations are effectively size_t[] where perm[i] represents the target index for an input index i. I know how to apply a permutation if I have an input and output array: struct Permutation { std::vector<size_t> perm; template <typename T> void apply(const T in[...
The hint to find the cycles and permute each cycle worked for me. To sum up my approach, I find the start indices of all cycles in the constructor. Then, in apply(), I permute each cycle by just repeatedly using std::swap. struct Permutation { private: /// The single vector which stores both the permutation ///...
63,703,925
63,704,125
How to assign a value to std::variant?
I am trying to assign a value to a simple std::variant #include <variant> using namespace std; int main() { variant<int, double> v; v = 12; //error v = 12.0; //error } I expect this to compile, with g++ main.cpp but I get this error: no operator "=" matches these operands -- operand types are: std::va...
You have to pass the C++ standard to the compiler with g++ -std=c++17 main.cpp The default standard of gcc 9.3.0 is C++14 which doesn't support variant.
63,704,046
63,705,197
Map of template functions
I want to make a std::map with std::string keys that contains functions. These functions should be templates in order to work with different numeric values: template <typename T> T (*pfunc)(T,T); The map declarations looks like this: std::map<std::string, pfunc> funcMap; I know I need a template argument list for pfu...
I think the best you will get is template <typename T> T myMax(T x, T y) { return (x > y)? x: y; } template <typename T> T myMin(T x, T y) { return (x < y)? x: y; } template <typename T> using pfunc = T(*)(T, T); template <typename T> std::map<std::string, pfunc<T>> funcMap = { { "myMax", myMax ...
63,704,567
63,704,675
C++ is that possible to initialize base class' base class?
I am trying out the below snippet, #include <string> class A { protected: std::string name; public: A(std::string name):name(){} }; class B: public A { public: B() : A("B") {} }; class C: public B { public: C(): A("C"){} //<-- this is not allowed, but I want to make C has its own name }; Obviously, ...
Rewriting B's constructor B(const std::string& name = "B") : A(name) {} is one way. Here I'm equipping it with a default value, so it still acts as the default constructor.
63,705,007
63,705,143
C++ how to remove puncuation from a string array?
In the following program showed below I attempted to remove all puncuation from a string array using ispunct std::string fileName; std::fstream readFile; const int arraySize = 50000; std::string storeFile[arraySize]; int main(int argc, char *argv[]){ for (int i = 0, len = storeFile[i].size(); i < len; i++) { if (...
ispunct takes 1 character as input, not an entire string. But you don't need to check the string before removing the punctuation. Something simple like this will work: for (auto& s : storeFile) { s.erase(std::remove_if(s.begin(), s.end(), ::ispunct), s.end()); } Live demo ==EDIT== You have a fixed arra...
63,705,018
63,705,214
boost::thread vs std::thread vs pthread
What are the tradeoffs b/w boost::thread, std::thread (C++11), and pthread for high CPU throughput (read: lots of floating point operations) Linux based applications? When should one implementation be used over the others? The use case here is to call a routine on a buffer (or pointer to a buffer) of contiguous memory,...
std::thread Pro: Is standard; guaranteed to be on all conforming platforms. Con: Requires C++11, so it cannot be used with ancient compilers. Only basic, lowest common denominator features. However, platform specific features can still be used through std::thread::native_handle. boost::thread Pro: Is cross platfor...
63,705,115
63,705,851
Is it ok to keep simple C++ method definitions inside of a header file?
I've put all of my classes into separate header files. So I have a file named snake for the Snake class and a fruit file for a Fruit class etc. I'm familiar with the concept of using a header file for declaring a class and its methods and then defining the methods in a separate .cpp file with the same name. All of that...
@ReinstateMonica left a really good, succinct answer which I wholeheartedly agree with -- however I wanted to expand a little on it. There is nothing inherently "good" or "bad" about defining functions inline in a header. There can be some cases where it is better to not define in a header since it may cause code-bloat...
63,705,374
63,710,002
Segmentation Fault (SIGSEGV) in Geeks for Geeks problem
Hi there I was trying to solve a problem on Geeks for Geeks using brute for approach, so the problem statement was, Given an array of positive integers. Your task is to find the leaders in the array. Note: An element of array is leader if it is greater than or equal to all the elements to its right side. Also, the righ...
In your updated code it looks like you have a typo at long *A = new long(N); I believe you want long *A = new long[N]; Regardless, you are over complicating things. First, use std::vector to eliminate all the memory allocation stuff. Second, process each test case fully - that is, don't save the printing until all th...
63,705,435
63,707,261
C++, “error: 'void*' is not a pointer-to-object type”
I need to create an array of pointers of different types. Some variables are defined at the beginning and their vectors are assigned to different spaces in the array. Later, from another process, the values of these variables can be changed using the pointers stored in the array. Variables are accessed directly from th...
You are converting an integer value to pointer. Maybe you wanted to do this: *((uint8_t *) values[0]) = (*((uint8_t *) values[0])+x); *((uint16_t *) values[2]) = (*((uint16_t *) values[2])+x); also see these questions: this question and this question
63,705,552
63,735,593
SWIG convert vector of maps to python list of dictionaries
Hi I am working on wrapping C++ with SWIG for use in python. Inorder to wrap C++ classes I am using SWIG. I have no good idea about typemaps and hence I am stuck. I have a vector consisiting of multiple maps ie. std::vector<std::map<std::string, int>> and I want to return it from C++ function and convert it to list of ...
You do need typemaps if you want the return value to be an actual Python list of Python dicts, but the included pre-defined templates might work for you. Here's an example: test.i: %module test %{ #include <vector> #include <map> #include <string> std::vector<std::map<std::string, int>> func() { std::vector<std:...
63,705,820
63,705,858
Why is my program skipping my switch statement, going straight to default?
I am relatively new to programming and am trying to write a simple ATM type program. I have a function that takes the option input by the user and a function that manages the input given called 'operate till' which uses a switch statement to filter through the given input. For some reason its skipping straight to defau...
In your code switch (command) { case 1: if (command == 'b') { void displayBalance(float &currentbalance); displayBalance(currentbalance); } break; case 2: if (command == 'w') { float Withdraw(float &accountbal); float Withdraw(); } ...
63,706,075
63,708,422
Serial WriteFile returns before completion
I've been working on a program which dialog with an external device via a serial RS422 bus. The goal is to send commands to the device, which send an answer back. So far, the code for sending a message look like this: OVERLAPPED osWrite = {0}; void init() { // Create this write operation's OVERLAPPED structure's h...
Since Windows is not a real-time OS and is a multi-process & multi-thread OS, time accuracy should not be guaranteed. If the system is lightly loaded, most of it will work as intended, but not always. Conversely, the completion of WriteFile() may be notified earlier than it actually is, depending on the hardware and de...
63,706,447
63,706,477
How to change class attribute values permanently with a function in c++?
I wrote a program in c++ with 2 classes. Basically "HeroList" just is a vector of "Hero" elements. Now I want to change the values each hero has given (in function "change"). But it doesn't work. It only works if I call the function with the "Hero" Objects directly as parameter(try 1). But when I use the "heroList"-el...
You can update getHeroes() to return a reference to the Heroes vector to get the behavior you want: vector<Hero>& getHeroes() { return Heroes; }
63,706,623
63,707,065
Why are clang and GCC not using xchg to implement std::swap?
I have the following code: char swap(char reg, char* mem) { std::swap(reg, *mem); return reg; } I expected this to compile down to: swap(char, char*): xchg dil, byte ptr [rsi] mov al, dil ret But what it actually compiles to is (at -O3 -march=haswell -std=c++20): swap(char, char*): mov ...
TL:DR: because compilers optimize for speed, not for names that sound similar. There are lots of other terrible ways they also could have implemented it, but chose not to. xchg with mem has an implicit lock prefix (on 386 and later) so it's horribly slow. You always want to avoid it unless you need an atomic exchange...
63,706,687
63,706,950
is there any difference between two methods that re-initializing vector?
I use two methods when I re-initialize vector vector<int> vec(1000, 1); //first vec.assign(1000, 2); //second vec = vector<int>(1000, 3); I think these two methods are produce same result, but I found that the second method takes up less memory. Is there something difference between these two method??
The difference is how the internal memory of the std::vector is handled. With std::vector<int> vec(1000, 1); You created a new std::vector called vec. It allocates memory to hold 1000 ints and initializes their values to 1. In the first method: vec.assign(1000, 2); You then tell vec to reuse that allocated memory, wh...
63,706,740
63,707,846
Show an Icon inside Modal Dialog Box
I'm completely new to MFC and have been working on this issue for a couple of days now and can't find any solution that works. Problem: I have a dialog class (Modal Dialog Box) with a style defined in an .rc file (Code below) and get the resource id of the icon (int m_icon is the same as IDR_MAINFRAME) from another cla...
You shouldn't have to do any thing like SetIcon or SendMessage to get an icon to show. What's wrong is your RC file is wrong. It should look like this: ABOUTBOX DIALOGEX 0, 0, 285, 77 STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "<<Aboutbox>>" FONT 8, "MS Shell Dlg", 0, 0,...
63,706,820
63,724,692
Visual Studio 2019 x64 app using mongocxx driver
I'm trying to get a windows x64 C++ project working with the latest mongocxx driver using Visual Studio 2019. I installed the driver libraries using vcpkg: vcpkg install mongo-cxx-driver[boost] In VS 2019 I created a new console app and inserted the example code from the mongo driver page into main(). I built the app a...
As I suspected, it was something I just didn't know to do. From Neumann-A on the vcpkg github site: vcpkg install mongo-cxx-driver[boost]:x64-windows or vcpkg install mongo-cxx-driver[boost] --triplet x64-windows or set VCPKG_DEFAULT_TRIPLET=x64-windows vcpkg install mongo-cxx-driver[boost]
63,706,937
63,707,496
connecting a checkbox signal to a method in qt widget
For example I have a three files the generalsetting.ui, generalsetting.h, generalsetting.cpp . I want to trigger the enableNotification method when the Notifycheckbox in the UI file is clicked. by passing the return value of the checkbox to the function I tried using connect(ui->notifyCheckBox, &QCheckBox::toggled, th...
you can connect to a lambda: connect(ui->yyy, &QCheckBox::toggled, [this]() { qDebug() << "sd.." << ui->yyy->isChecked(); enableNotification(ui->yyy->isChecked()); }); or directly, same way as the signal connect(ui->yyy, &QCheckBox::toggled,this, &Foo::enableNotification);
63,707,608
63,720,287
How to programmatically differentiate between dvd or mini dvd disk inserted?
I need to get a capacity of inserted DVD disk. DeviceIoControl function call with IOCTL_DISK_GET_DRIVE_GEOMETRY_EX parameter writes 4128768 bytes as a size of DVD what, obviously, is wrong result. Code was taken from https://learn.microsoft.com/en-us/windows/win32/devio/calling-deviceiocontrol. Another solution was to ...
There is a field DiskSize in DVD_LAYER_DESCRIPTOR, which I was looking for. Firstly, we should open drive with correct permissions. HANDLE drive = CreateFileW(devicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); Be careful with devicePath, it should be...
63,708,530
63,708,632
Why can two std::vector iterators not be summed?
This is more of a curiosity question about C++ that came up after learning how to find the index referenced by an iterator. Given two vector iterators, why can they be subtracted from each other but not added together? For instance, why does this compile and run: std::vector<int> vect; vect.begin() - vect.end(); While...
Iterators are modelled after pointers. Given pointers P1 and P2, the expression P2 - P1 gives you the offset/distance between the pointers. There is nothing sensible you can expect from the expression P1 + P2. Extend that idea to iterators and you will understand why subtraction between two iterators makes sense but ad...
63,709,153
63,721,143
Addr2line 64bit tool
Am looking for errors in the il2cpp build of Unity for android, according to this guide https://support.unity3d.com/hc/en-us/articles/115000292166-Symbolicate-Android-crash It specifies the 32 bit short address 0043a05c, which after executing the following command > ./arm-linux-androideabi-addr2line -f -C -e /Applicati...
Found the required utility for 64 bits. The 32-bit utility was located here C: \ Program Files \ Unity \ Hub \ Editor \ 2019.2.19f1 \ Editor \ Data \ PlaybackEngines \ AndroidPlayer \ NDK \ toolchains \ arm-linux-androideabi-4.9 \ prebuilt \ windows-x86_64 \ bin \ arm-linux-androideabi- addr2line.exe And 64 bits are h...
63,709,218
63,710,063
How do I pass arguments by reference when calling Rust from C++?
I am trying to do a very simple test to see how I can call Rust functions from C/C++. My C++ code: #include <iostream> #include <cstdint> extern "C" { int32_t add_one(int32_t x); } // extern "C" using namespace std; int main() { int32_t x = 14; cout << x << endl; cout << add_one(x) << endl; cout <<...
#[no_mangle] // See note below pub extern "C" fn add_one(x: &mut i32) { *x += 1; } #include <iostream> #include <cstdint> extern "C" { void add_one(int32_t *x); } // extern "C" using namespace std; int main() { int32_t x = 14; cout << x << endl; add_one(&x); cout << x << endl; cout << x <<...
63,709,841
63,710,080
Is casting a C++ reference from unsigned char to double& safe?
I am trying to implement a "table" of references for setting various code elements by an index lookup. Most of the underlying variables are double, but a few are different types like unsigned char. Here is a simplified example: static unsigned char foo = 0; // Variable to set static unsigned double bar = 0.0; // Va...
Reading an individual char as a double is undefined behavior as it breaks type aliasing rules, which is what you are doing. Converting from a char value to a double value using static_cast<double> is perfectly normal and defined though. It is generally possible to reinterpret double as char, but only in specific scenar...
63,710,289
63,710,699
include .cpp with #ifndef instead of .h considered bad practice?
There are lots of similar answers to this question such as this one: Include .cpp instead of header(.h) https://stackoverflow.com/a/1001723/637142 (this answer really says it is bad) Stack overflow will prbably say I have a duplicate question but I still do not understand after looking into all the similar questions ...
You should never #include a .cpp file, because the .cpp extension tells people that a file is a separately compiled translation unit. There is nothing technically wrong with it, but it is misleading to other programmers and will make your code confusing and difficult to maintain. If you change the file extension of th...
63,710,336
63,710,565
Compression of binary arrays to overcome GPU memory limitations
I'm working on physical simulations on the GPU (CUDA) and struggling with the limited amount of available memory on standard graphic cards. The problem is as follow: I have a huge binary mask (> 30 GByte) which serves as a lookup table. To evaluate the validity of a specific variable I generate an index from the variab...
Run-Length Encoding I don't know of any library that does this for you, but I can provide you with an idea of how to do this. Since your mask contains many repetitions of the same bit, a suitable approach would be Run-Length Encoding (RLE). The idea is that instead of encoding individual bytes, you encode the byte and ...
63,711,963
63,712,281
unable to resolve the error in bfs implementation
I've written bfs for finding the shortest paths to every other node: queue<int> q; dist[s] = 0; // maintains the distance of vertices from s(source). q.push(s); while(!q.empty()){ int src = q.front(); q.pop(); vis[src] = 1; // visited array to keep track of nodes which have been visited fo...
I assume when you name the array vis, it stands for is_node_visited, and you would like to have is_node_visited[n] to be true if and only if node n is visited. This is the problem. The right notion for BFS is is_node_enqueued. We would like to have is_node_enqueued[n] to be true if and only if the node n was ever enque...
63,712,046
63,862,769
C++ std:: string starts_with/ends_with case insensitive versions?
C++20 added starts_with, ends_with to std::string. Is there a nice way to get it to be case insensitive? Note that perf matters so I do not want to lowercase/uppercase both strings(or std::min(len1, len2) parts of them). Unlike regular <algorithm> algorithms starts_with has no overload with comparator so I see no nice ...
std::mismatch(s1.begin(), s1.end(), s2.begin(), s2.end(), <comparator>) will do what you want. You have to write the case-insensitve comparator, but I'm sure you can figure that out.
63,712,105
63,712,146
c++ adding random(i think) numbers in the end of string output
I started using HackerRank and my code is outputting the correct outputs, but it is adding random numbers at the end of the string outputs. I have solved a couple more problems on CodeBlocks and tried it there. It is the same as the one on HackerRank. #include <iostream> #include <cstdio> using namespace std; int mai...
Looking at the printf man page, the function will return an int: Return value Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings). [...] If an output error is encountered, a negative value is returned. So if you do cout << printf("one...
63,712,369
63,712,670
Trying to dynamically allocate an array inside an element of a vector of structs
I have a vector of point type( point is a structure which contains 2 ints and a pointer to int, s) and I m trying to dynamically allocate memory for the s array( malloc / new) and add two values to it but it gives me seg fault. I don t know if I m allowed to do this inside a vector element. Thank you in advance. struct...
You don't resize() the vector to n. You have a fixed value of 2. This will make the program have undefined behavior as soon as someone enters something larger than 2 in std::cin >> n. The second loop for(i = 0; i <= v.size(); i++) will make the program access v[v.size()] which is out-of-bounds so your program has unde...
63,712,849
63,713,924
c++ More efficient data structure and algorithm for making a Counter. i used look up tables
My problem is : i gave a series of queries, and a series of references, and i want to count the number of occurance of said keys between them, but only if they have matching keys. I choose to have an LUT because i think it will help me efficiently, but im not sure if there are better ways, or the way im using LUT is no...
Considering my comment above, here is what I got. Adjusted to keep original data, but this feels like an extra credit :) unordered_map<int,int> MakeCounter(const unordered_map <int, set<int>>& qs, const vector<unordered_map <int, set<int>>>& refs) { unordered_map<int, int> counters; for (size_t i = 0; i < refs....
63,713,050
63,713,312
Multiple double colon (::) in call stack of VS 2010 C++
I am from java/C# background and I am trying to understand some C++ code. I learned that a code like following is defining a function out of the class file Some_Class::someFunction ( void ){ //SOME LINE //OF CODE //FOR THIS FUNCTION } I am using Visual Studio 2010 to build the project. However, when I debug it to unde...
:: is the scope resolution operator. I suppose this wont help you much, so I will try to put it in simple terms. abc::def::ghk::The_Class::The_Function() This is the full name (*) of The_Function(). Suppose it is a method of The_Class as in your snippet. Then this class might be nested inside another class called ghk:...
63,713,146
63,714,131
How can i stop QT Widget from closing?
I have a class (Window) that inherits from QWidget (Not QMainWindow). This is the important part of my main function. QApplication app (argc, argv); QMainWindow *window = new QMainWindow; QMenuBar *tool_bar = new QMenuBar (window); Window *graph_area = new Window (arguments); window->setMenuBar (tool_bar); wi...
You can either: Subclass QMainWindow, instead of QWidget Override QMainWindow::closeEvent, instead of QWidget::closeEvent Allocate your QMainWindow subclass on the stack, instead of on the heap, i.e.: MyMainWindowSubclass window; or: Change your code to: QApplication app(argc, argv); Window w; window->show(); ...
63,713,573
63,713,718
I cannot create a file in C++ using fstream
This is my first question here on stack overflow, so have mercy if I screw up with anything (lol) Coding language: C++ IDE: Code::blocks Compiler: GNU GCC OS: Windows Let me clarify: Here is my code: #include <iostream> #include <fstream> int main() { std::fstream fileObject; std::string line; fileObject.open(...
You need to read the documentation, you can't program C++ by guess work. These options allow you to open a file for simultaneous reading and writing, but with the following caveats // error if the file does not exist std::fstream fileObject("randomFile.txt"); or (same thing) // error if the file does not exist std::fs...
63,714,317
63,729,485
C++ program adding ^M characters
I'm editing a python file and my program iterates through every line and if the string "if" exists, it appends a comment to it. The program does work but it adds ^M and I can no longer see the code on GitHub as it appears as a raw file. Looking at this post here https://unix.stackexchange.com/questions/32001/what-is-m-...
So as it turns out, the solution to use unix2dos worked. What ended up happening was all the comments being appended added another .6MB to the file which in turn made it over 1MB. That's why even though the code could be easily read locally, you could not view it on GitHub. Thank you to those who commented, I appreciat...
63,714,675
63,714,810
Interfacing with a custom PCI from windows
I'm trying to write a program that can read from a bunch of sensors, make decisions on a windows computer, then write to some actuators (e.g. valves). This is all already done on an existing system and program but we want to do something different and so are starting with a new program on the windows computer from scra...
You need to access the hardware via a driver provided by the manufacturer. Many manufacturers don't document how to access their drivers directly by the end user code. Instead, they provide an API library (in an SDK) that the users call into to operate the PCI device. It'd help if you'd post a link to the device you're...
63,714,696
63,715,237
How to translate python byte array append to C++
I am very very very new to ROS and embedded C++ programming. I hate Python and I wish to convert a node written originally in Python to C++. I won't get into detail on this conversion I am happy with OOP approach I took (put subscriber callback into a class, put publisher as class member), the main issue however is a p...
Most direct solution: std::vector<signed char> make_byte_array(std::vector<signed char> array) const { array.push_back('\n'); array.push_back('\r'); return array; } What's happening: array is passed by value so it's automatically copied. We take advantage of this copy to eliminate the need to manually copy...
63,715,105
63,716,846
How is C++20's std::vector assign constexpr?
Given that the current contents and size of a vector can be randomly determined at runtime, and all contents will have to be destroyed upon calling assign, how can C++20's assign member function be constexpr ie. compile-time?
Found my answer here. To quote, Being a constexpr function does not mean that the function is executed at compile time. It says, that the function has the potential to run at compile time. A constexpr function can also run a runtime. It's often a question of the compiler and the optimisation level if a constexpr funct...
63,715,108
63,732,819
How to get `cin` to read a raw mode terminal
Why is it a standard stream can receive input from a terminal in canonical mode, but you put it in raw mode and suddenly this method is no longer valid? I'm well aware of POSIX serial programming, and typically you use read. I'm trying to understand standard streams better. #include <termios.h> #include <unistd.h> #inc...
After much discussion and a bit of investigation, I've discovered this is a limitation to the implementation of the given standard streams. Basically, I've deduced that standard streams work fine when your terminal is in cooked mode, but unreliable if in raw mode. The code can be reduced to using std::cin.rdbuf()->sbum...
63,715,295
63,715,864
C++ template for specific type
So I have this little template class: template <typename T, typename std::enable_if<std::is_arithmetic<T>{} || std::is_same<T, std::chrono::duration<int64_t, std::nano>>{}, int>::type = 0> class Accumulator { public: void Sample(const T value) { value_ = Convert(value); } private: float value_; ...
template <typename T, typename std::enable_if<std::is_arithmetic<T>{} || std::is_same<T, std::chrono::duration<int64_t, std::nano>>{}, int>::type = 0> class Accumulator { public: void Sample(const T value) { value_ = Convert(value); } private: float value_; }; template <class U> float Convert(U ...
63,715,908
63,715,963
question on c++ object construction and scope
this is a little bit difficult to put into words, here is the snippet, int main() { int i = 5; { int i(i); i = i+5; // int i = i; // i = i + 5; cout << "inner scope" << endl; cout << i << endl; } cout << "outer scope" << endl; cout << i << endl; } this...
When you shadow a variable you remove all trace of it within that scope, so: int i = i; This declares i to equal its (uninitialized) self. This variable is completely independent from the parent scope's i. This is effectively undefined behaviour. Curiously the int i(i) approach uses the parent scope's i to initialize,...
63,716,204
63,716,324
Why does the std::unique_ptr constructor accept an external pointer?
I'm relatively new to cpp, and am learning about smart points. I'm wondering the following: Why is constructing an std::unique_ptr with an lvalue allowed? Wouldn't it be safer to only allow the construction of an std::unique_ptr with rvalues to avoid evil things? std::unique_ptr<int> createInt() { int* a = new int(...
This is a classic example of what a dangling pointer is! In contrast to what smart pointers may seem, they are simply wrappers over normal (raw) pointers, which can manage memory on their own and give you some added functionalities. Consider the following example: int* someFunc() { int* ptr; int* ptr2 = ptr; ...
63,716,425
63,716,706
does pointer "this" in c++ support virtual mechanism?
Consider that: class B { void f() { vf(); }; virtual void vf(); }; class D: public B{ virtual void vf(); }; I thought that in C++ the implementation of B::f() is something like that: f(B *this) { *(this->vptr[index])(this); } Is D::vf() called through the virtual mechanism in the following example? B...
Answer is yes for the given example, but not for calls from a constructor of the base class, which executes before the derived class gets constructed. With a slightly modifed example: #include <iostream> class B { public: B() { f(); } void f() { vf(); }; virtual void vf() { std::cout << "B::vf" << std::e...
63,716,489
63,717,201
Concurrent request processing with Boost Beast
I'm referring to this sample program from the Beast repository: https://www.boost.org/doc/libs/1_67_0/libs/beast/example/http/server/fast/http_server_fast.cpp I've made some changes to the code to check the ability to process multiple requests simultaneously. boost::asio::io_context ioc{1}; tcp::acceptor acceptor{ioc...
io_context does not create threads internally to execute the tasks, but rather uses the threads that call io_context::run explicitly. In the example the io_context::run is called just from one thread (main thread). So you have just one thread for task executions, which (thread) gets blocked in sleep and there is no oth...
63,716,507
63,716,539
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:25:17
I am solving the problem--> Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. and the error I get is Line 16: Char 17: runtime error: index ...
This would fix your bug, however there is a problem with your algorithm, does not pass all the test cases: class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { int n = nums.size(); int indice[n][n]; int total[n][n]; ...
63,716,806
63,717,368
Can an SSBO binding point index be any value?
When you specify "location = x" in a shader to specify a shader storage or uniform buffer binding point, can that number be any value? Is this binding point independent of which shader is currently bound? Would it be possible to bind all my ubos and ssbos before I bind my shaders, so long as the number of each type of ...
Every indexed buffer binding point (and pretty much every kind of binding in OpenGL) has an implementation-defined maximum number of available binding indices. This represents the maximum number of buffers that the hardware can use in that fashion during any one rendering operation. Furthermore, for buffer-backed inter...
63,716,974
63,716,987
Multiply two numbers through recurssion
#include<iostream> using namespace std; int multiply (int num1, int num2){ if (num1 > 0) return num2 + multiply(num1-1,num2); } int main(){ int mult = multiply(5,6); cout<<mult; } I am trying to multiply two numbers through recurssion, but i am not getting the desired result, i want to print 30 but it is give...
You are invoking undefined behavior by letting the execution reach at end of function definition without executing return statement in function whose return type is not void. #include<iostream> using namespace std; int multiply (int num1, int num2){ if (num1 > 0) return num2 + multiply(num1-1,num2); return 0; // ...
63,717,041
63,717,107
Is it safe to assume that changing a global bool variable in threads without lock is crash safe?
I know it is undefined behaviour. Hence the possibility of data race or crash. One can use atomicbool to avoid such possibilities. What I am interested to know about the crash safety. AFAIU, crash may happen when one thread reads the partially written or torn value by another thread. On the other hand the size of the ...
No, it is not safe. Undefined behavior is undefined. There is no rule that says that it can't crash unless you can think of a way that it can crash. I can think of ways it can crash. For example, suppose you have a function that creates a thread that reads from the same bool that the function writes to without synchron...
63,717,396
65,233,372
How to limit drawing area in Allegro 5?
I want to make a scrollable window in Allegro 5. The problem is, in order to make everything work, I'd need to limit drawing area, so the parts of window that, due to scrolling, are above this window are not visible. Is there any way to do this? I am asking about something like love.graphics.setScissor.
Got the solution. The functions I was looking for are al_set_clipping_rectangle() and al_get_clipping_rectangle().
63,717,924
63,719,221
Redirecting I / O from cmd.exe using CreateProcess () and CreatePipe()
My problem is that I can't get output from the command line using pipes. My task: "Redirect the command input stream to cmd.exe | output the result of the cmd.exe command to the main process." #include <iostream> #include <windows.h> using namespace std; #define deffBuffSize 1024 int funSC() { HANDLE writ...
First, the error of ERROR_BROKEN_PIPE(109) caused by the cmd.exe exit unexpectedly. According to the sample Creating a Child Process with Redirected Input and Output: The parent process uses the opposite ends of these two pipes to write to the child process's input and read from the child process's output. As specifie...