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
67,651,954
67,652,280
How to return 2d array C++
I have a function that needs to return a 2d array, I'm new in c++ but I searched a lot and the best I got is that, which gives "error: cannot convert 'int** (*)[3]' to 'int**' in return". int** initial_state() { int arr[3][3] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}} ;...
You can do something like this using the auto keyword, like in this example: auto make_array() { int arr[3][3]; return arr; } It will actually be an array of pointers to ints, but it works.
67,651,983
67,652,043
Global variables not allowed in headers?
I am trying to use separate files for my PlatformIO Arduino project, but I get this error: .pio/build/uno/src/test.cpp.o (symbol from plugin): In function `value': (.text+0x0): multiple definition of `value' .pio/build/uno/src/main.cpp.o (symbol from plugin):(.text+0x0): first defined here collect2: error: ld returned ...
You appear to have two source files in your project: main.cpp and test.cpp. Both are probably including test.hpp. So now each source file has independently picked up a value variable. So the linker gets confused because it doesn't know which value each module should use. And you probably do not want multiple instan...
67,652,174
67,767,412
Bash script detect memory leaks of C++ programs
I'm writing a bash script that times some C++ programs compiled using g++ with -fsanitize=address. Is there any way to detect whether any memory leaks occurred (from the script)? Basically I want the aggregate times of those executions that did not leak and disregard those that did.
Is there any way to detect whether any memory leaks occurred (from the script)? You can look at the process exit code. Address Sanitizer will force the program to exit with error code if leaks are detected. This assumes that the program itself correctly exits with error code 0. Basically I want the aggregate times o...
67,652,544
67,652,955
How do i run an executable every time i run my code in Visual Studio?
I've seen it done on mac in xcode where you can edit the scheme to configure an external executable to run whenever you run your code. How can this be achieved in Visual Studio? Can't seem to find out online.
In the Solution Explorer, right click on the project you want to debug and select Properties. Select Debugging group at right of panel, then modify Command item at the right. The default is $(TargetPath) which works for normal executable targets, but needs to be set to debug DLL for example. You might want to set also ...
67,652,826
67,831,523
How to Use The CD4067BE Library for Multiple Buttons
I just have a small problem with this Arduino library: CD74HC4067. I am not sure how to use multiple buttons with this multiplexer library. I have an Arduino Mega 2560 and the CD4067BE [multiplexer]. The connections are fairly simple: just like this, but with the signal pins going to 2, 3, 4, 5, and 6: https://electron...
This is the answer to my problem: I needed to scan the individual channels to determine which one was being pressed. Here is the code, in case anyone is interested: /* Controlling and looping through a CD74HC4067's channel outputs Connect the four control pins to any unused digital or analog pins. This examp...
67,652,884
67,664,217
CMake generator expression with duplicated compile flags
I'm trying to make a compiler-dependent configuration using CMake generator expressions. One part of this configuration is to set compiler flags with use of list of include directories, similar to what CMake has in their documentation. However for some reason the JOIN expression does not work properly for me in this ca...
After playing around with it for some time it turned out that the problem comes down to both spaces and arguments deduplication. Partially it can be handled by removing space between option (e.g. -systemi) and its argument (path). However some flags just cannot avoid duplication (like -Xclang option). In order to suppr...
67,652,929
67,654,159
OpenCV multiplying matrices (cv::Mat) of different types
Error: what(): OpenCV(4.2.0) ../modules/core/src/arithm.cpp:691: error: (-5:Bad argument) When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified in function 'arithm_op' Code: // cx is a cv::Mat containing a 1280x720x1 matrix of floats ...
The main issue is that the type of (cx > 0.5) is CV_8U and not CV_32F. Take a look at the following code sample: //Initialize 3x3 matrix for example cv::Mat cx = (cv::Mat_<float>(3, 3) << 5.0f, 0, 0, 0, 5.0f, 0, 0, 0, 5.0f); //The type of "logical matrix" result of (cx > 0.5f) is UINT8 (255 where true). cv::Mat cx_abo...
67,653,021
67,653,118
MPI_Comm_split not working with MPI_Bcast
With following code I am splitting 4 processes in column groups, then broadcasting in same column from diagonal (0,3). Process 0 broadcasts to 2. And 3 should broadcast to 1. But it is not working as expected. Can some one see whats wrong ? 0 1 2 3 #include <stdio.h> #include <stdlib.h> #include <iostream>...
MPI_Bcast Broadcasts a message from the process with rank "root" to all other processes of the communicator is a collective communication routine, hence it should be called by all the processes in a given communicator. Therefore, you need to remove the following condition if(myrank%3==0) and then you need to adapt th...
67,653,149
67,653,208
pushing a char into the stack does not work
I'm trying to make a stack of chars with linked list so I made two classes for stack and node but when I'm trying to push a char into the stack: stack->push('x') it does not work and give these two errors : expected an identifier , expected a type specifier class stack { private: node* top; ...
'stack' is seemingly the name of your class. You need to instantiate it. Like stack someStackInstance; someStackInstance.push('x'); You might want to show your complete code where you have stack->push('x') (not you're using a pointer).
67,653,456
67,653,511
Two "const" in c++ variable declaration
I came across this code in win32 API programming tutorial and I am struggling to understand it. if (msg == WM_NCCREATE) { const CREATESTRUCTW* const pCreate = reinterpret_cast<CREATESTRUCTW*>(lParam); } What does const CREATESTRUCTW* const pCreate mean? I did find this answer while doing my research. The example ...
Let's rewrite this const CREATESTRUCTW* const pCreate into this: CREATESTRUCTW const * const pCreate // <------- a -------> <- b -> which means the same thing. const refers to the thing to the left, so you have an immutable pointer (b) that is pointing to an immutable object of type CREATESTRUCTW (a).
67,653,516
67,654,154
CMake building files twice when using `target_sources` on common library
My project has a main executable and a test executable. All files from the main executable except the one with the int main() definition are used in the test executable too. So I put these files in a library which is linked to main and test executable. Minimal reproducible example: Also on GitHub: https://github.com/bb...
How can I use target_sources to add files to the library without building them twice? Normally, target_sources command is used only with PRIVATE keyword: target_sources(Lib PRIVATE fibonacci.cpp fibonacci.h) With that keyword sources will be used only when compile the library itself, and won't be used when compile a...
67,653,592
67,653,765
C++ variadic templates with type and non-type argument mixing for recursive inheritance
I would like to achieve this: Foo<int, 5, double, 7> foo_1; Foo<char, 7> foo_2; foo_1.Foo<int>::value[4] = 1; foo_2.Foo<char>::value[1] = 'x'; (This is an oversimplified example, Foo would do much more than this.) How can I do that with variadic templates? TLDR; I know that variadic templates can be used in this way ...
It's not possible. You'll have to settle for one of the following: Foo<Bar<int, 5>, Bar<double, 7>> foo_1; Foo<int, Bar<5>, double, Bar<7>> foo_1; // ...? If the values are always integral, you could also try this: Foo<int[5], double[7]> foo_1; And then extract elemenet types & extents from each argument.
67,653,658
67,653,705
Why does my static std::vector erases when used from a class?
I have a static std::vector in one header to save the report of some behavior, but for some reason the vector erases when i want to consult it. NOTE: to make this bug work, this have to be separated in 4 files: Reports.hpp #ifndef REPORTS_HPP_INCLUDED #define REPORTS_HPP_INCLUDED #include <vector> static std::vector<i...
Because that's how a static object that declared in global scope works. Each .cpp that includes it has its own, private object that's not accessible from other .cpp files. If you want to declare a single object that's accessible from all .cpp files, you must declare it as extern, and not static, in the header file and ...
67,653,665
67,653,690
C++: Function can't access variable defined in main() function
Why can't the print() function access the msg variable? #include <iostream> void print() { std::cout << msg << std::endl; } int main() { std::string msg{"Hello"}; print(); } Error: 'msg' was not declared in this scope
This is because the msg variable that you have declared in the main function is a local variable and can be accessed only within the main function. You can either define a global variable so that you can access it from any function, or you can pass msg as a parameter to the print function.
67,654,474
67,655,313
How do I import C++ 20 <format> module?
I am using Visual Studio 2019 (Community edition) running on a Windows 10 machine. I have created a simple console application and I want to import the format module so that I can use something like std::format(). I get an error that 'cannot find header 'format' to import. My code is based on a book by Horton and van W...
While waiting for MSVS support of std::format, you can use the fmt library that is the basis for the std::format. This can be found at https://github.com/fmtlib/fmt. It is compatible with the C++20 standard but does include additional features. Add the library to your source and use fmt::format instead of std::format. ...
67,654,540
67,654,583
Passing values as reference to a constructor/function
In my example I declared a class Player1. The constructor expects a read-only input and handles it as reference. Thats okay. class Player1 { private: std::string m_Name; public: Player1(const std::string &name) : m_Name(name) {} std::string GetName() { return m_Name; } }; For instanciation either way (A) is p...
Your tentative explanation is actually pretty close, but it differs in a couple of details from what actually happens. It's not the constructor that does any work here, the constructor still takes a const std::string & as a parameter. That part doesn't change, and nothing exceptional happens in the constructor, in this...
67,654,798
67,664,907
How do you add external libraries to 'self-made' libraries using CMake?
I'm not able to link external libraries with the libraries I wrote using CMake. I'm wondering if there's something that is needed to be added to my CMakeLists.txt? Or if I need to add another CMakeLists.txt in a lower level (inside src) and what would that need to contain? I have the following project structure: Projec...
There are several errors in the CMakeLists.txt with the following changes the project loads appropriate libraries and builds properly. Another note is that before, to include helper.h I needed to write: #include "../include/helper.h". Now it works as expected with #include "helper.h". Here is the modified CMakeLists.tx...
67,654,817
67,654,996
how do i split up fltk code and definitions
This is my first ever C++ project. I have 1600 lines of code mostly in include files using FLTK widgets and I would like to split the class definitions and the code the way I always see recommended. I have tried numerous times to figure out what goes where and I always get compiler errors. I've been trying with some ex...
You put the definition of your constructor in two places so you need to remove it from here: class mybox : public Fl_Box { public: mybox(int x, int y, int w, int h, const char *lbl); // removed };
67,654,892
67,654,984
Why class destructor called if I delete linked list element?
I want to free memory by deleting all nodes in the end of programm, but I also have function(overloaded operator) to delete specific node. If I'm deleting specific node class destructor is called. Can someone explain why, and how to fix it. Class declaration class StudentList { private: typedef struct stude...
You've declared your operator- like this: StudentList operator-(student_nodePtr selectedSt); Note that it is returning a StudentList object by-value. That means that the calling code is receiving a temporary StudentList object, which then gets destroyed when it goes out of scope; hence the call to the StudentList...
67,655,378
67,655,417
what is the proper case of constant class member fields according to the google c++ style guide?
according to https://google.github.io/styleguide/cppguide.html#Variable_Names, Data members of classes, both static and non-static, are named like ordinary nonmember variables, but with a trailing underscore. according to https://google.github.io/styleguide/cppguide.html#Constant_Names, "Variables declared constexpr o...
In your example: class A { const int size_; This member variable is not a "constant" for the purposes of the style guide. Its value cannot be changed after construction, but is different per instance. A "constant" inside a class would be constexpr or static const or enum. As it stands, it is not a constant so d...
67,655,485
67,762,687
Webassembly: possible to have shared objects?
I am wondering if, using C (or C++ or Rust) and javascript, I am able to do CRUD operations to a shared data object. Using the most basic example, here would be an example or each of the operations: #include <stdio.h> typedef struct Person { int age; char* name; } Person; int main(void) { // init Pers...
Creating the object Let's create the object in C and return it: typedef struct Person { int age; char* name; } Person; Person *get_persons(void) { Person* sharedPersons[100]; return sharedPersons; } You could also create the object in JS, but it's harder. I'll come back to this later. In order for JS ...
67,655,647
68,349,657
How do I make VS Code parse Qt object names from .ui file?
I'm looking for a way to make Visual Studio Code recognize object names from QtCreator's form (.ui) file. I really don't like to use QtCreator as a code editor, and I want to use it only for designing windows, which requires the .ui file. The problem is that QtCreator parses the object names from the .ui XML file to gi...
I found the answer after a bit of researching. There is a VS Code extension called Qt Tools that parses object names from the .ui file and shows code suggestions for those objects for seamless Qt development.
67,655,667
67,655,670
error: no viable conversion from '(lambda at A.cpp:21:22)' to 'int'
What am I missing? Lambda declaration error. Marked in comment. void solve() { int charCount, time; cin>> charCount >> time; // Generating error: no viable conversion from // '(lambda at A.cpp:21:22)' to 'int' int rightDistance = [&](int i) { return charCount - i -1; }; rightDis...
You're trying to initialize rightDistance from the lambda itself. You should call the lambda as int rightDistance = [&](int i) { return charCount - i -1; } (42); //^^^^ If you want to declare the lambda variable, then declare the type of rightDistance with auto instead of int. auto rightDistance = [&](int i) ...
67,655,974
67,657,626
Vector iterator incompatible ? Same vector
I have the following code vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { vector<Interval> res; vector<Interval>::iterator it; for (it = intervals.begin(); it != intervals.end(); it++) { if (newInterval.start < (*it).start) { ...
The iterator is invalidated with insert(For vector, an insertion may cause the memory reallocation, all elements are moved to a new address. The iterator is just a pointer, so it can't be used to compare with the new end of a vector, it's meaningless), as the comment mentioned, you need to reassign the return value to ...
67,656,851
67,658,209
preorder successor in binary tree
I want to find a preorder successor in Binary search tree using value. I have a Code But it works using Node. Node* preorderSuccessor(Node* root, Node* n) { // If left child exists, then it is preorder // successor. if (n->left) return n->left; // If a left child does not exist, then // tr...
You can implement a simple depth first search in advance: Node* depthFirstSearch(Node* node, int value) { if(!node) { return nullptr; } if(node->value == value) { return node; } auto n = depthFirstSearch(node->left, value); if(n) { return n; } return d...
67,656,926
67,657,098
How could I comunicate with the terminal using an external device connected through usb port?
I want to program an arduino in such a way so that when I connect the arduino to any computer via usb port, the arduino will communicate with the computer's terminal and execute hardcoded commands. How could I make this system?
There are basically just 2 options for you: You have to install additional software/driver on the computer first that executes the commands and communicate with your arduino via normal serial commands. Your arduino has to emulate something that is allready allowed to send the computer commands like the keyboard or mou...
67,657,440
67,657,633
How the values of array got affected in the following c++ code?
When the following program is compiled, the output is if break float while break. #include<iostream> using namespace std; string s[5]={"if","int","float","while","break"}; string & blast(int i){ return s[i];} int main() { for (int i = 0; i < 5; i++ ) if( i % 3 == 1 ) blast( i ) = s[ 5-i ]; ...
As you wrote yourself you have when i is equal to 1 blast[1]= s[4] = "break" so, s[1] = "break" Thus s[1] contains the string "break". After that the array does not contain the string "int". Then this string "break" is copied now from s[1] to s[4] when i is equal to 4 blast[4]= s[4] = s[1] = "break"
67,657,674
67,657,713
Defining simple struct object
Having such a simple code: struct OurVertex { float x, y, z; // pozycja float rhw; // komponent rhw int color; // kolor }; OurVertex verts[] = { { 20.0f, 20.0f, 0.5f, 1.0f, 0xffff0000, }, { 40.0f, 20.0f, 0.5f, 1.0f, 0xff00ff00, }, { 20.0f, 40.0f, 0.5f, 1.0f, 0xff00ff55, }...
the most disturbing for me is the }; It is only the hint, that the compiler detects the error exact at this place. Sometimes this looks wrong, but in this case, it is perfect at the end of the definitions which is the right place. struct OurVertex { float x, y, z; // pozycja float rhw; // kompon...
67,657,777
67,658,687
pass parameter with pointer or with reference when the origin data is pointer?
I need to read some data from binary file, which i save the data pointer in a vector. I want to handle them with best performance. I have two design, please see this: struct A { int a, b,c; } void Handle(const A & a) { // do something } void Handle(A * a) { } std::vector<A* > av; // this is read from file for (int ...
Pointer and reference are mostly the same when regarding performance: their implementation in the runnable code is the same (or course, there are exceptions to this rule, but I cannot think of any). The difference between reference and pointer is mostly for the programmer - reference has cleaner syntax (that is, you do...
67,657,860
67,657,939
Why does std::set::find not provide a hint iterator?
#include <set> #include <vector> using Value = std::vector<int>; int main() { auto coll = std::set<Value>{}; // ...... // Insert many values here. // ...... auto new_value = Value{1, 2, 3}; auto const pos = coll.find(new_value); if (pos != coll.end()) { // Good coll....
The result of std::set::lower_bound() is usable as a hint for emplace_hint(). So just use lower_bound() instead of find(), and check if the key returned by lower_bound() matches what you were looking for, instead of checking if the iterator returned by find() is end().
67,657,974
67,658,244
C/C++: When and why do we need to call SSL_do_handshake() in a TLS client-server application?
I have created a client-server application that uses TLS for communicating with each other. I have used non-blocking sockets and using the generic OpenSSL library functions for establishing TLS channel and for IO iperations, i.e. not using BIO explicitly anywhere in my application. The application is working normally w...
SSL_do_handshake need to be invoked when the TLS handshake should be done. When using SSL_accept (server) or SSL_connect (client) one does not need to call SSL_do_handshake explicitly, since it is already done internally. Similar if SSL_do_handshake should used there is no need to use SSL_accept or SSL_connect, just se...
67,658,177
67,658,196
Constructor Overloading Issue in C++
// Create a function which takes 2 point objects and computes the distance between those points #include<iostream> #include<cmath> using namespace std; class dist{ int x, y; public: dist(int a , int b) { x = a; y = b; } dist(); void caldistance(dist c1, dist c2) { // c1 ...
Define the constructor as dist():x(0),y(0) {} dist() is just a declaration, but you have not defined the construtor.
67,658,343
67,658,424
Why does C++20's requires expression not behave as expected?
#include <type_traits> template<typename T> struct IsComplete final : std::bool_constant<requires{sizeof(T);}> {}; int main() { struct A; static_assert(!IsComplete<A>::value); // ok struct A{}; static_assert(IsComplete<A>::value); // error } I expected that the second static_assert should be tr...
It's a wrong expectation. To start with, a class template has only one point of instantiation in a translation unit: [temp.point] 7 ... A specialization for a class template has at most one point of instantiation within a translation unit. A specialization for any template may have points of instantiation in multiple ...
67,659,850
67,659,851
Selecting an overloaded function between two functions that both have a parameter of the type reference to an array
Here is a demonstrative program where there are declared two functions that both accept a reference to an array. #include <iostream> void f( const int ( &a )[5] ) { std::cout << "void f( const int ( &a )[5] )\n"; } void f( const int ( &a )[6] ) { std::cout << "void f( const int ( &a )[6] )\n"; } int main() ...
The program is correct. It is a bug of the compiler. According to the C++ 14 Standard (13.3.3.2 Ranking implicit conversion sequences) 3 Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies: (3.1) β€” List-initialization sequence L1 is a ...
67,660,464
67,660,618
When I use XM_CALLCONV of DirectMath, Do I have to write that both declarations and definitions?
// declaration in header file void XM_CALLCONV F(FXMVECTOR vec); // definition in source file void XM_CALLCONV F(FXMVECTOR vec) { ... } Do I have to writh XM_CALLCONV both of them? or just write it once at declareation?
https://learn.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160 I got it. In MScompiler, Just write it once at declareation is ok.
67,660,976
67,661,033
why does std::thread throws an error when it's asked to run an overloaded function?
below is the code i am running , it throws an error in the lines where i am passing overloaded function 'myfunc' in thread object t1 and t2 (also identified with a comment) #include<iostream> #include<thread> using namespace std; void myfunc(int x) { cout << x << endl; } void myf...
When you have overloaded functions that you pass as arguments, you need to help the compiler. Possible solution: using f1 = void(*)(int); using f2 = void(*)(int, int); thread t1(static_cast<f1>(myfunc), 1); thread t2(static_cast<f2>(myfunc), 1, 2);
67,661,365
67,661,430
Error: Data initializer is not allowed here?
code: struct example { int a = 0; // line 3 example() {} }; I am gettting data initializer is not allowed here error at Line 3 How to solve this?
In C++ prior to C++11 standard, you cannot initialize value where you declare it, you have to do it with constructor: struct example { // int a = 0; NOT ALLOWED int a; example() : a (0) {} // preferred way /* NOT PREFERRED WAY example() { a = 0; } */ } EDIT: Thank to @user4581301 for the co...
67,661,634
67,661,787
using operator '*' on a 4 byte value and then casting the result to a 8 byte value
I have to write a program that takes a Student's marks in the following format from a .dat file COS1511 30 66 70 49 COS1512 25 76 75 67 COS1521 10 58 90 62 COS1501 50 62 50 57 INF1501 40 82 60 78 INF1511 20 24 80 55 The fields are: Subject ID, Weight of assignment 1 in %, Assignment 1 in %, Weight of assignment 2 in %...
stoi convert String to Integer. try to convert result to double. Return Value: On success, the function returns the converted integral number as an int value.
67,662,025
71,150,871
How can I intercept the pressing of multiply (*) key in my C++ Qt calculator app?
I'm new in Qt and now working on calculator application that has opportunity of keyboard input (1,2,3,4,5,6,7,8,9,0,-,+,/,*,.,(,),). Firstly, I tried just to determine "keyPressEvent" method like this: void MainWindow::keyPressEvent(QKeyEvent* ev) { QString CurrentLabel_disp = ui->label->text(); QString KeyPres...
try using this case (Qt::Key_Asterisk):
67,662,035
67,662,412
Lambda capture-by-value while transfering ownership
I have a RAII style class which manages the ownership certain resources. Therefore, copy constructor and assignment operator are explicitly deleted, only move variants exist and they move the resource and invalidate the source (reference). So far it has worked fine, but now I would like to move an object of that kind i...
A lambda is not a std::function. You are right that c++14 allows moving something into a lambda, and even move said lambda afterwards. A std::function on the other hand requires the callable to be Copy Constructable and Copy Assignable. From cppreference Class template std::function is a general-purpose polymorphic fu...
67,662,073
67,662,307
Copying text from a Memo by line/index
I was wondering if there is a way to copy text from a specific line of memo. For example, I want to store the content from the 3rd line of my memo to a string, then do some operation on that string and copy it to another memo/edit. I've tried a few variations of this, but none work: str_temp = Memo1->Lines[2].Text; Mem...
The Lines property is a pointer to a TStrings object. So Memo1->Lines[2].Text is the same as doing (*(Memo1->Lines+2)).Text per pointer arithmetic, which is syntaxically valid but logically wrong as it will end up accessing invalid memory. Whereas Memo1->Lines[0].Text is the same as doing (*(Memo1->Lines)).Text (aka Me...
67,662,707
67,663,570
Template default argument
How do I specify a template class as a default value for a template typename? e.g. the following doesn't work. template <typename A, typename B> class X {}; template <typename T=template <typename, typename> class X> class Y {}; int main() { Y<> y; return 0; } tmp.cc:4:22: error: expected type-specifier bef...
The problem of your code is that for Y you ask a type template parameter and you want to use a template template parameter. template <typename A, typename B> class X {}; // type template template //........VVVVVVVVVV VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV template <typename T=template <typename...
67,663,298
67,663,565
What's the correct in templated class forward function declaration, operator> overloading
I'm trying to overload an operator in a class and don't know the correct syntax for in class forward declarative functions, like operator. operators template <typename S, typename T, typename R> class TRIPLE { public: TRIPLE(S, T, R); const TRIPLE &operator...
You have to distinguish between member and non-member operators. Member operator > takes one argument (operands are *this and right): bool TRIPLE::operator>(const TRIPLE& right) const; Non-member operator > takes two arguments (operands are left and right): bool operator>(const TRIPLE& left, const TRIPLE& right); By ...
67,663,299
67,670,670
Calculating the Cosine/Sine/Tangent of an angle using Bernoulli Series Expansion in C++ without using outside libraries
I can't seem to find the error. I need a fresh pair of eyes. I am trying to calculate the values of Cos/Sin/Tan of an angle in C++ without using built-in functions or libraries. These are the only requirements. This is what I have gotten so far: I have written a function to calculate the exponential values, factorials ...
A lot of parameters and variables are int when they only make sense as doubles. #include <iostream> #include <cmath> using namespace std; double bernoulli_numbers[] = { 1, -1/2, 1/6, -1/30, 5/66, -691/2730, 7/6, -3617/510, 43867/798, -174611/330, 854513/138}; double angleToRadian(int angle) { double rad_angle = a...
67,663,358
67,663,741
spliting string in C++
I wonder how to split a string, right before integer. Is it possible? I have written a converter that downloads data from an old txt file, edits it, and saves it in a new form in a new txt file. For example old file look like: Every data in new row. New file after convert should look like: Means that all data after i...
You can try to parse the current string as an int with std::stoi; if it succeeds, you can add a newline to buf. This doesn't exactly split the string, but has the effect you're looking for when you send it to your file, and can be easily adapted to actually cut the string up and send it to a vector. for(int i=0; i<frie...
67,663,427
67,663,776
CUDA optimization for a vector tensor product using a custom kernel or CUBLAS
I have two vectors a and b. Each vector contains the coordinates of a 3d points x, y, z vector3f. struct Vector3f { float x; float y; float z; } vector a has a size of n = 5000 points and vector b has a size of m = 4000. I need to do a tensor vector product between them like on the right side of the pict...
You can make the kernel move through both a and b simultaneously, like this: __global__ void tensor3dProdcutClassic(const int n, const int m, const Vector3f *a, const Vector3f *b, float *c) { int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdy.y * blockDim.y + threadIdx.y; if (i < n && j < m) ...
67,663,952
67,664,028
c++ mutexes that not blocks code from inside, but allow to block it from outside
I'm trying to solve the next problem: There are two types of functions. The first type can execute from different threads simultaneously (for example - read data from container). The second one must block all threads inside first-type-function until some operation done (for example - change container). I am sure this i...
This is a common pattern best solved using reader/writer locks. In C++ you want to use std::shared_lock and imagine that f is a reader and g is a writer. Declare variable: std::shared_mutex mutex; In f: // Multiple threads can enter the shared lock (readers). std::shared_lock lock(mutex); In g: // Only one thread can...
67,663,976
67,664,020
Why does my QIntValidator allow inputs not in my specified range?
I am trying to set up a QIntValidator to validate input on a QLineEdit. This is what I did: userInput = new QLineEdit("1"); userInput->setValidator(new QIntValidator ( 1, 20, this ) ); This appears to work: it does not allow any letters in. However, I can type in 0, which is out of range, and I can also type in number...
The 0 is accepted as QValidator::Intermediate state, because the user may intend to type e.g. 05, which would be valid. You won't be able to actually input the undesired value. After you press Return or move focus from the widget, having 0 in the input field, the value should return to the original (well, at least spin...
67,664,330
67,666,206
Are .lib and .dll files in C++ comparable to .jar files in Java?
So I have a background in Java and is starting to learn C++ using Visual Studio. From what I’ve seen, you can put C++ classes and function into .lib and .dll so the linker can use them for other programs. In Java, you can also archive stuffs into jars. So is this comparison correct?
It's a good comparison although not perfect. Jar files are just archives of .class files, and .class files contain all the information that the Java compiler needs so that you can use class A from class B. It's self-contained. C++ libraries (.a, .dll, .dylib, etc) are not fully self-contained. They are archives of the ...
67,664,357
67,664,395
Why cout is not giving output for string?
My code is not giving st in output. There is no compilation error but there's no output either. #include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; string st; int j=0; transform(s.begin(),s.end(),s.begin(),::tolower); for(int i=0;i<s.size();i++) { if(s[i]!='...
st[j++]=... writes beyond the end of the allocated space for the string and is undefined behaviour. It also overwrites the string's terminating nul character. Instead, you want: st.push_back (...); or: st += ...;
67,664,399
67,666,736
trim_left implementation using string_view disallowing temporary parameters
I'd like to implement a non-copy data trim_left function, but would like to not allow it to accept temporary parameters to make the returned string_view is valid (the data is still alive). I started accepting string_view as parameter, but I cannot get the way how to guarantee the data is valid. So I make this: template...
I find out this second implementation: template<typename T, std::enable_if_t< std::is_same<T, std::string_view>::value || !std::is_rvalue_reference_v<T&&>, int > = 0 > std::string_view trim_left( T&& data, std::string_view trimChars ) { std::string_view sv{std::forward<T>(data)}; sv.remove_prefix( std::min(sv.f...
67,664,515
67,664,637
Objects beyond the far clipping plane are rendered in perspective view
I see objects beyond the far clipping plane in perspective projection and I don't think this is how it's suppose to work, so can someone give me an explanation why do I see objects beyond the far clipping plane such as a grid in this example. The orthogonal projections works fine btw I cleared all shapes from this dem...
I think you're thinking of the maximum view distance as being consistently 900 units away from the camera/eye position. If that was the case, it wouldn't be a clipping plane at all, it would be a curve - a sector of a sphere. In reality the view frustum is a truncated pyramid made up of 6 planes. When the far plane is ...
67,665,218
67,665,237
What is the equivalent of TiXmlAttribute for tinyxml2 and how to use it?
I've encountered a problem that I'm not being able to solve using tinyxml2. I have a function that receives as a parameter a XMLElement and I need to iterate over its attributes. With tinyxml, this worked: void xmlreadLight(TiXmlElement* light){ for (TiXmlAttribute* a = light->FirstAttribute(); a ; a = a->Next()) {...
Going by the error message, it looks like you need to do: for (const XMLAttribute* a = light->FirstAttribute(); a ; a = a->Next()) { ... ^^^^^ Presumbably, the return type of FirstAttribute has been made const in tinyxml2. If you check the Github repository for the tinyxml2.h file on line 1513 you will see this:...
67,665,414
67,665,997
How to write a program that displays numeric limits of a data type in a table
I'm currently learning how to program in C++ and one of the practical examples is to write a program showing the data types numeric limit in a table. Currently writing in repl.it before pasting to .txt and compiling using makefile. There are no resources or similar examples I could find explaining how to do this, nor h...
There're quite a lot of errors/typos within your code. void main() will return a '::main' must return 'int' error, the correct syntax is int main(). number = (IMO is Pythonic syntax) should be int number = , as in C++, the correct format for declaring variables is type variable_name = value;. More info here. Variab...
67,666,764
67,671,804
Lares - Them divide c people into t groups
There is m men, and n women.The boss chooses k people. Them divide m+n-k remain people into t groups, each group exactly 2 men and 1 woman. Find max(t) For example: Input 264936043 821529140 438045170 Ouput 132468021 #include <iostream> using namespace std; int n, m, k, res, t; int main(){ cin >> n >> m...
Thank you @dratenik, I used derivative to analyze the function (n-x)/(m-k-x). And this is my accepted code. #include <iostream> using namespace std; int n, m, k; int main(){ cin >> n >> m >> k; if (k >= m+n) cout << 0; else if (n/2 <= m-k) cout << n/2; else if ((n-k)/2 >= m) cout << m; else { ...
67,666,847
67,854,996
btHeightfieldTerrainShape constructor arguments not clear
I am having a hard time understanding the consturctor parameters of btHeightfieldTerrainShape and how the height field data is supposed to be set up. The first two arguments heightStickField and widthStickField. What do they represent? Is it the width and height of the entire terrain so that the height field is scaled ...
Figured it out. For those wondering the ordering is -x to +x and z+ to z- . So a for loop such as the following will get you the right ordering. width and height here are in terms of the number of tiles/height values per row/column for (int i = 0; i < mHeight; i++) { for (int j = 0; j < mWidth; j++)...
67,667,039
67,667,271
How do I create 3 types of objects(movie, book & journal) from this text file and then display it?
So far I can only create one type of object - books, can someone explain how can I create movie and journal objects? This is what I have done so far: #include <iostream> #include <fstream> #include <sstream> #include <vector> using namespace std; struct Item { string type; string i...
Your "readBooks" function opens the input file and parses each line with the assumption that it contains book data. It needs to instead grab each line, then (based on your file format) examine the substring from the beginning of the line till the first comma and compare it to values (MOVIE, BOOK, JOURNAL). Once you...
67,667,209
67,668,153
Do I need to perfect forward arguments in these cases where the arguments are used directly in the function?
I thought to myself that I don't need std::forward<T>(arg); in my function because I wasn't passing the argument on to another function, I was using it directly. However then I thought even if I use it directly, by for example assigning it, or using it as a constructor argument then those each are function calls, respe...
An expression that is a name of a variable is always an lvalue. For example, in 1 template <typename T> 2 void push_back(T&& copy) { 3 *_end = copy; 4 } copy in line 3 has the lvalue value category no matter what type is deduced for T. Depending on how operator= in line 3 is defined/overloaded, this might resu...
67,667,215
67,667,303
Perfect forwarding in std::make_unique<SomeWrapper<T>> not quite perfect
Given the following types: struct Point { int x; int y; Point(int x, int y) : x{ x }, y{ y } { } }; class Widget { public: std::string name; Widget(std::string name) : name{ name } { } }; template <typename T> struct DataHolder { T value; DataHolder(T value) : value {value} { } }; Why d...
Why does this code compile: auto compiles = std::make_unique<DataHolder<int>>(42); auto alsoCompiles = std::make_unique<DataHolder<std::string>>("Hi"); DataHolder<int> has a constructor taking int, and 42 is passed as the constructor argument to construct DataHolder<int>, which works fine (similarly as DataHolder<in...
67,667,318
67,667,447
Why must a std::ranges::filter_view object be non-const for querying its elements?
#include <ranges> #include <iostream> #include <string_view> using namespace std::literals; int main() { auto fn_is_l = [](auto const c) { return c == 'l'; }; { auto v = "hello"sv | std::views::filter(fn_is_l); std::cout << *v.begin() << std::endl; // ok } { auto const v = "h...
In order to provide the amortized constant time complexity required by range, filter_view::begin caches the result in *this. This modifies the internal state of *this and thus cannot be done in a const member function.
67,667,847
67,669,713
Can't pass the lcm solution task in the Yandex Contest competition
This is my source code, which I try to pass to the least common multiplier task: #include <iostream> #include "algorithm" using namespace std; using ll = long long; using ld = long double; long long gcd(int a, int b) { while (b > 0) { a %= b; swap(a, b); } return a; } long long lcm(int a,...
what about negative numbers? Try calculating the GCD(abs(x), abs(y)), it's the same as GCD(x, y)
67,668,046
67,668,107
How to bind a GL_TEXTURE_2D_ARRAY to a framebuffer on GL_COLOR_ATTACHMENT1?
Edit : see @Rabbid76 answer, question was not truly related to GL_TEXTURE_2D_ARRAY, only to framebuffer color attachment activation! I'm having trouble updating a shader that use to ouput into a single texture to multiple textures. Here's the simplified code, I'll put all I find relevant, feel free to ask for other par...
You need to specify the buffers to be drawn into with glDrawBuffers: GLenum drawBuffers[]{ GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glDrawBuffers(2, drawBuffers);
67,669,230
67,735,282
How can I mesh a 2D domain with cannot-be-split line segments by using CGAL?
I want to use CGAL lib in C++ to mesh a polygonal domain as follows, The red line segments should not be split but the black can be split. What kind of function should I use ? Can you raise a C++ example?
There is a tradeoff. If the inside line segments are small enough, just add them as constraints without disallowing the splitting. Then, let the min element edge length larger than the length of small segments, before meshing. Generally, the small constraints will not be split.
67,669,269
67,701,902
OpenCL-HPP setDefault crash
Here is a piece of code that I'm trying to run and understand. but it has a awkward error in the setDefault function. cmake_minimum_required(VERSION 3.19) project(OpenCL_HPP) set(CMAKE_CXX_STANDARD 14) # find OpenCL find_package(OpenCL REQUIRED) find_package(Threads REQUIRED) include_directories(SYSTEM ${OpenCL_INC...
After some debuging and reading about OpenCL-HPP I found the problem. The main issue is that the OpenCL-HPP uses pthreads and if they are not included / linked one gets problems like described above. Articles that helped: cmake fails to configure with a pthread error Cmake error undefined reference to `pthread_create' ...
67,669,723
67,670,055
how to get typeid of incomplete type c++
I need to store pointers in such a way that later I'll be able to restore it's original type and do some stuff. vector<pair<void*, type_info>> pointers; and later for(auto p : pointers){ switch(p.second) case typeid(sometype): DoStuff((sometype*)p.first); break; //and so on... } When I add poi...
Use std::any. Some examples for your case: #include <vector> #include <any> std::vector<std::any> pointers; SomeType *pointer; pointers.emplace_back(std::make_any<SomeType*>(pointer)); /* later on */ for (auto p : pointers) { if (SomeType *t = std::any_cast<SomeType*>(p)) /* p is of type SomeType* */ ...
67,670,028
67,670,393
dynamic memory allocation segfault
Why does my code segfault when using the dynamic memory allocation in the code below ?Any pointers on what maybe happening? , im using valgrind and it points to the second loop being the issue . #include <iostream> using namespace std; int main() { int x , y; scanf("%d",&x); scanf("%d",&y); int** b...
Syntax? b[y][x] = 0 and not b[i][j] = 0 ? b[y][x] is out of range. while b[y-1][x-1] is the last matrix index.
67,670,323
67,670,422
Code before first case in switch statement
Please note that this is a question about C++ language, not about how real or useful is the example I'm giving to illustrate it. Imagine we have an enum in a namespace (or namespaces): namespace SomeVeryLargeNamespaceExample { enum class E { One, Two, }; } Now, we want to use it in the expressi...
Any valid C++ statement is possible: int a; void foo(int x) { switch (x) { a=4; case 0: a=1; break; case 1: a=2; break; } } This is syntactically valid C++, and gcc has no issues compiling it and producing an executable. However the initial statement can never b...
67,672,215
67,672,409
MSVC's instrinsics __emulu and _umul128 in GCC/CLang
In MSVC there exist instrinsics __emulu() and _umul128(). First does u32*u32->u64 multiplication and second u64*u64->u128 multiplication. Do same intrinsics exist for CLang/GCC? Closest I found are _mulx_u32() and _mulx_u64() mentioned in Intel's Guide. But they produce mulx instruction which needs BMI2 support. While ...
You already have the answer. Use uint64_t and __uint128_t. No intrinsics needed. This is available with modern GCC and Clang for all 64-bit targets. See Is there a 128 bit integer in gcc? #include <stdint.h> typedef __uint128_t uint128_t; // 32*32=64 multiplication f(uint32_t a, uint32_t b) { uint64_t ab = (uint64_...
67,672,463
67,672,864
identifier "NULL" is undefined and identifier "strncpy" is undefined in vscode on wsl
I am trying to program on vscode on wsl-2 ubuntu distro. I think I did setup the system correctly, but I keep getting red squiggles on identifiers that are in libraries I included in the code. The code looks like this: #include <iostream> #include <stddef.h> #include <cstring> #include "string.h" String::String () { ...
I wouldn't have a header named "string.h"; since the C-header for NULL, strncpy etc is also in "string.h". It might be that #include <cstring> includes your string.h instead of the system string.h, leading to your error. Note that the cstring-header normally contain code like: ... #include <string.h> ... You might als...
67,672,597
67,673,189
How to get a particular part of string in c++?
I have the below string i need take out the id (68890) similar date (01/14/2005) CString strsample = "This is demo to capture the details of date (01/14/2005) parent id (68890) read (0)" CString strsample = This is demo (Sample,Application) to capture the details of date (01/14/2005) parent id (68890) read (0) To...
The simplest way using standard library is to use std::sscanf: #include <iostream> #include <string> #include <cstdio> #include <ctime> #include <iomanip> int main() { std::string s; while (std::getline(std::cin, s)) { std::tm t{}; int id, read; auto c = std::sscanf(s.c_str(), ...
67,673,236
67,673,302
Why is the location returned by GL function call -1 if there's no error?
In the following program the last print function prints -1 which is the location of the uniform named num. I gave right arguments to the function glGetUniformLocation(), yet got -1 as a result , can't figure out why? P.S. The shader compiles successfully. GLuint program = glCreateProgram(); GLuint compu...
The uniform variable num is not an active program resource, because it is not used in the shader program. The compiler and linker optimize the code and determine that the variable is not required. Therefore, you will not get a valid uniform location.
67,673,554
67,675,183
Lifetime of object pointed to by shared pointer
Take the following example struct A { int x = 0; }; struct B { std::shared_ptr<A> mA; void setA(std::shared_ptr<A> a) { mA = a; } }; struct C { B initB() { A a; A *aPtr = &a; B b; b.setA(std::make_shared<A>(aPtr)); return b; } }; Now in main() method C c; B b = c.in...
Firstly, this doesn't compile. B initB() { A a; A* aPtr = &a; B b; b.setA(std::make_shared<A>(/*aPtr*/a);); return b; } You have to pass the actual object being made shared, not a pointer to it. Now, to find out the answer to this problem, we can write notifiers for eac...
67,673,828
67,674,015
Can in C++ override a virtual method by calling a method from a private instantiated class without reimplementing it?
sorry updated I have a class A that overrides many methods from another class B and beside it has an instance of the class B from which I want the methods to be called. B is an interface with virtual methods so it has an implementation passed to me via pointer i.e. class B class B{ public: virtual int f1(int x); vi...
If you want to call f1() and f2() on the member variable, then no. There is no automatic mechanism to tell the compiler that calls to A::f1() should be forwarded to b->f1().
67,674,393
67,674,503
How to Pass a Function to Structure in C++?
My Struct Code : struct MouseHandler { void OnHover(); void* OnLeftClick(); // void (*OnLeftClick)(); void OnRightClick(); void OnDrag(); void OnDrop(); }; Calling of Struct : MouseHandler ms; I am trying to pass SampleScrollDownClickHandler to ms.OnRightClick(), Is it is possible, How can I d...
So the commented out line is actually closer to the solution you want. In order to pass the function pointer you need to not call the function itself, which you did by invoking it with the trailing (). So the following code is closer to what you want (limiting it just to the most basic parts of your code): struct Mou...
67,675,155
67,921,699
Undefined references while building LLVM with MinGW-w64
I am trying to build LLVM using MinGW-w64 (GCC 8.1.0). After cmake .. -G"Mingw Makefiles" and mingw32-make it started building, but after a while this error hapenned: <...> [ 5%] Building CXX object utils/TableGen/CMakeFiles/obj.llvm-tblgen.dir/CTagsEmitter.cpp.obj [ 5%] Built target obj.llvm-tblgen [ 5%] Linking CX...
-DCMAKE_CXX_FLAGS= is for compiler flags, not linker flags. Try something like this: -DCMAKE_EXE_LINKER_FLAGS="-Wl,--as-needed -lkernel32".
67,675,166
67,675,348
Best way to read an array from a file
I wrote an array in a file and now I am trying to read it from the same file. However when I print it, it gives very strange numbers. I would like to know what those numbers come from(is it the address?) and how can I solve it. I want to know if is possible to write something so you dont have to write the same cycle ev...
Try this: #include <iostream> #include <iomanip> #include <fstream> #include <time.h> using namespace std; int main() { int n, m; cout << "Enter number of rows: " << endl; cin >> n; cout << "Enter number of columns: " << endl; cin >> m; int** b = new int* [n]; for (int i = 0; i < n; ++i...
67,675,296
67,807,546
C++ int promotion motivation for restrictions
Integer promotion works by promoting everything of an inferior rank to either int or uint. But why is this so? It makes sense to make a difference between "upgrading" and "downgrading" a type. When you are converting a short to a char you may lose data. However when going up in ranks (bool -> char -> short -> int -> lo...
In the C standard, Section 6.3.1.8 describes "Usual arithmetic conversions." (Added in C99, link is to C11 draft) Many operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to determine a common real type for the operands and result. The C99 Ration...
67,675,510
67,708,798
Linking to std++fs - what syntax to choose
Context I initially developed a C++17 code with gcc 9.2, but had to compile it on a system that has only gcc 8.2 available. I had the linking error: CMakeFiles/qegg1.dir/qegg1.cpp.o: In function `std::filesystem::exists(std::filesystem::__cxx11::path const&)': qegg1.cpp:(.text._ZNSt10filesystem6existsERKNS_7__cxx114pat...
Previously, the filesystem part of the standard library wasn't included in libstdc++ but was only available by explicitly linking with libstdc++fs. g++ is still shipped with libstdc++fs so explicitly linking with it isn't a problem even for newer g++ versions. I was hoping to find a clean cmake way of doing find_packa...
67,675,721
67,675,768
C++ Giving wrong output for a simple math calculation
So my code looks like this: unsigned long i=(27984 * 619246) + (1402 * 615589); cout<<" i= "<<i; I don't use the variable i anywhere else etc Output looks like this i= 1012166658 The correct answer is 18192035842 . WHY is this happening?
Try this: #include<iostream> #include <string> using namespace std; int main() { unsigned long long i = (27984ULL * 619246ULL) + (1402ULL * 615589ULL); cout << " i= " << i; } using the long long literal suffix LL, and upgrading the type to a bigger type solves the problem. I use the U (unsigned) literal suffi...
67,676,058
67,676,587
Run tcp server in another thread
I'm struggling with running tcp server in different thread. So I have sth like that: #include <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); ...
There's some confusion about using io_context; You seem to think operations run on the context, but they won't unless you use async_ versions. Other side notes: write_some doesn't (need to) send the whole buffer. Use boost::asio::write instead. Here's a simpler example that clarifies the confusion: Live On Coliru #in...
67,676,133
67,676,841
What are some options for copying textures from one OpenGL library to another?
Context I'm developing a plugin based architecture that is designed to allow each plugin to utilize its own graphics API so long as it can pass a standard texture format that the engine can ingest and render utilizing a master OpenGL graphics context and shaders. Ideally, each plugin will not be aware nor have access t...
There is no such thing as a free lunch. The price you pay for API-agnosticism is that you give up any efficiencies that knowledge of the API would allow for. OpenGL has mechanisms to allow one context to share objects with another. But if you have decided that you don't know/care if a plugin is using OpenGL, you have t...
67,676,190
67,677,879
Error: (E107) bind interface to port failed: type mismatch on port 4 of module `simple_instance.data_in_reg'
i want to read bus in register_out and write to bus in register_in but i get type mismatch error on port4 of register_in Register.hpp file #pragma once #include<systemc.h> #include"bus.hpp" class Register:public sc_module{ private: sc_port<sc_signal_in_if<sc_logic>> clk,rst,lden; sc_port<sc_signal_in_if<sc_lv<8>>> ...
i replace sc_port<sc_signal_in_if> to sc_in and sc_port<sc_signal_write_if> to sc_out and make bus to sc_inout and it's work. but i have question why this way work but by using sc_port and interface i got mismatch error
67,676,689
67,677,783
cmake of minimal_build under Centos7
I'm trying to compile the examples under cpp starting with minimal_build. I don't have much cmake experience. Must this be run under docker, or can it just be compiled in a Linux shell? I'm running Centos7 on a AWS EC2 instance, and I've installed cmake 3.20.2. Executing sudo ./run.sh, errors immediately with "cd: /io:...
Yes, it is possible. I recently built Arrow on CentOS 7. With any C++ project there are going to be challenges switching amongst Linux distributions. The docker image is a way to provide a single example that the Arrow project can verify. You will need to adapt your Linux environment based on the issues you encount...
67,676,691
67,742,670
Streaming images with ZMQ, message_t allocation takes too much time
I've been trying to find out how to stream images with zeromq (i'm using the cppzmq wrapper, but raw API answers are fine). Naively, I set up zmq::context_t ctx(4); zmq::socket_t pub_image_socket(ctx, zmq::socket_type::pub); pub_image_socket.bind("tcp://127.0.0.1:8001"); ... while(true){ //render to image... ...
Use zmq_msg_init_data http://api.zeromq.org/master:zmq-msg-init-data You can provide the memory pointer/size of your already allocated memory and zeromq will take ownership (skipping the extra allocation). Once its been processed and is no longer needed it will call the associated free function where your own code can...
67,676,818
67,677,057
Why does a template argument of type T& resolves to T?
Here for example, b is of type int& but f(b) resolves to f(int): #include <type_traits> template <typename T> void f(T arg) { static_assert(std::is_reference<T>::value); // fails } void g() { int a = 5; int& b = a; f(b); } I know the standard dictates it - I'm asking, why? What goes wrong (or - becomes ...
There are two things at play here. What if you, as the author of f, wants to write a template function where the user is required to copy/move a parameter into the function? In non-template code, that prototype would look like this: void f(SomeType st);. Any caller of f has no choice but to copy/move into the parameter...
67,677,337
67,677,580
OpenMP clause shared vs critical
I have a loop executed on multiple threads. Each loop will store a value into a global vector. The vector index variable is used by all threads and each thread increments the index after vector update. The access to the index must be protected. How the protection is done in OpenMP? 1/ If I specify #pragma omp parallel...
1/ If I specify #pragma omp parallel shared(k) Will this protect (synchronize access to) k-index access across threads? If you use a shared k you will have two race conditions: during the updates of the variable k, namely in the operation k++. during the access to the array my_vec during the operation my_vec[k++] = ...
67,678,091
67,678,309
C++ Windows compiled program different behaviour to Linux
I wrote some code for a Linux system to read/write bitmap files. I transfered this code to Windows, and attempted to compile it with Visual Studio 2019. I tested my program by opening a bitmap file and saving a copy of it. I found that only the first few lines of the bitmap image were written to file and the rest of th...
Make sure you open your file in binary mode.
67,678,639
67,681,541
QProcess How to deal with too much input?
I'm using 3 command line tools via QProcesses to play music on my Linux (Mint) desktop via the Jack server. It's all working very well, but the input from one of the tools 'jack_showtime' arrives at about 12,000 lines per second. I only need to see one line every 0.1 seconds, but the only way I've found to get a full r...
I suggest something like this, such that no matter how fast or how slow you get input from the child process, you always use the only most recent value, every 100mS: // at startup or in your class constructor or wherever connect(j_s, SIGNAL(readyRead()), this, SLOT(ReadDataFromJack())); connect(&_myQTimer, SIGNAL(timeo...
67,678,668
67,678,697
rearrange an input that result must have alternating sequence of odd and even numbers
I am looking for an stable algorithm for rearranging the array to alternate even and odd numbers example: Input: {2, 8, 9 ,10 ,14 ,17 ,21, 13, 97}; Output: 9 2 17 8 21 10 13 14 97 because odd number are more than even numbers so sequencing started from first odd number 9; also print some error message if altern...
Your problem is modified version of this Below is the solution; this might work: #include <vector> #include <iostream> int main() { std::vector<int> ip = {2, 8, 9 ,10 ,14 ,17 ,21, 13, 97}; std::vector<int> even, odd; for(const auto& num: ip) num%2 == 0 ? even.emplace_back(num) : odd.emplace_back(nu...
67,678,977
67,685,222
MacAddress for topic name - Arduino IDE MQTT
I want to use the mac address of my system as a topic name. I want something like : project/00:1B:44:11:3A:B7/temperature/status I tried in this way: #define TEMP_STATUS_TOPIC "project/" + WiFi.macAddress() + "temperature/status" #define TEMP_CONTROL_TOPIC "project/temperature/control" But I get this error: no matc...
First you shouldn't use a #define in that way, like pointed out in another answer. You could instead declare TEMP_STATUS_TOPIC as a const String: const String TEMP_STATUS_TOPIC = "project/" + WiFi.macAddress() + "temperature/status"; The problem with MQTTClient::publish() is that the first argument requires a C string...
67,679,133
67,679,193
Can't understand how does this return works
can someone tell me how this return works or where I should search, I think it return's 2 values, but when i search i can't find nothing. BOOL __stdcall VirtualProtect() { char v1[4]; // [esp+4h] [ebp-4h] BYREF String = 0; lstrcatA(&String, "VertualBritect"); // No ragrets byte_442581 = 'i'; byte_442587 = 'P'; byte_442...
pVirtualProtect is a function-pointer. GetProcAddress is returning the address of a function, and that address is stored in the pVirtualProtect variable. The return statement is calling (whatever function pVirtualProtect is pointing to) with the specified arguments (Shellcode, uBytes, 64, v1), and returning whatever ...
67,679,227
67,898,735
Socket programming: What is causing select() system call not return on current thread execution?
I am having problem with select() call on an multi-socket app. Here is how it is supposed to work. Writer writes: [0010]HelloWorld on a socket, where the the first 4 character are always digits representing the payload size. Reader should do the following: call select() to verify if a given socket is readable, then re...
I found the problem with the infinite select blockage. I was not closeing the socket after processing.
67,679,236
67,680,088
C++ vector initialization produces unexpected output
I have the following code: #include <bits/stdc++.h> using namespace std; int main() { vector<int> nums = {2, 3, 4, 5}; sort(nums.begin(), nums.end()); int target = 20; int N = nums.size(); int clo = 1e9; vector<int> res(3); for (int i = 0; i < N; i ++) { for (int j = i + 1; j < N; j...
Try this. Should give leftmost of the target number present. #include <bits/stdc++.h> using namespace std; int main() { vector<int> nums = {2, 3, 4, 5}; sort(nums.begin(), nums.end()); int target = 20; int N = nums.size(); int clo = 1e9; vector<int> res(3); for (int i = 0; i < N; i ++) { ...
67,679,312
67,728,963
Creating a function for displaying status updates with printf style string formatting on an MFC control
I needed to display status updates on a dialog box, and wanted to be able to send printf style formatted strings to it. In addition I would like that function to call a similar function which will add the formatted data to a log file. Assuming my Static control is called IDC_MYSTATUSBAR, the function looks like this: v...
When the first parameter passed to the function is 0 or "", *ptr (which is in fact *ptr[0] or *(ptr + 0), hence the first block in memory) will hold null, thus the function printed the string literally, without formatting it with FormatV(). You need to replace the following block if (*ptr == 0) sMsg = lpText; else ...
67,679,586
67,679,709
Why does the recursion happens again after the base call?
So i'm trying to learn c++ and I have reached the topic of recursion and i have reached a problem. void myfun(int n) { if(n>0) { myfun(n-1); cout<<n<<endl; } else { cout<<"Stop"<<endl; } } int main() { int n = 5; myfun(n); }` The output of the program is like t...
The control flow of your main myfun(5) function call breaks down as (in pseudocode): call myfun(5) = [call myfun(4), print "5"] = [[call myfun(3), print "4"], print "5"] = [[[call myfun(2), print "3"], print "4"], print "5"] = [[[[call myfun(1), print "2"] print "3"], print "4"], print "5"] = [[[[[call myfun(0), print ...
67,679,600
67,679,965
How to have a class modify the pointer to itself so I can return to it easily
Can you help me with the nomenclature I'm missing to achieving the following scenario? In my program, I set the following classes: "Patient" has an integer for his "id", and a string for "sickness". "Doctor" has an integer for his "id", and a vector of integers "listOfPatients". Later I push the iD of a patient int...
The problem is that you have designed your program in such a way that you cannot easily find a patient with a specific ID. By using the lines Docteur doc1(9999); Patient pat1(123, "vertigo"); you have specified that every doctor and every patient will have its own unique identifier (name of variable or object). This i...
67,679,698
67,679,837
If I capture a return value in an auto&, will that be destroyed from under me?
Take the following code: const std::string GetString() { return std::string(); } auto& thisIsANewString = GetString(); What happens in this scenario? It compiles successfully, but does the auto reference keep the string around? Or does it get destroyed and I'm left with an orphaned reference? The reason I'm giv...
What happens in this scenario? The reference is bound to a temporary object, and the lifetime of the temporary object is extended to match the lifetime of the reference. This is useful in templates where you will be able to treat references, and objects that are reference wrappers equally. It's only confusing to use ...
67,680,089
67,680,106
pass more than single param to functor
I did overload the operator() for my functor that now it receives two params. I know it possible, but how I invoke it? as far as I see, functions as std::transform or std::for_each iterate over single param each time. minimal example: struct Functor { Functor(double epsilon, double delta): ... float operato...
You don't need a standard algorithm to call a functor. You can use the function call operator and pass as many arguments as the functor expects: Functor{.1, .2}(1, 2); You've simply chosen two standard algorithms that use a unary functor as your examples. There are other standard algorithms that use functors of differ...
67,680,273
69,666,676
Which origin does FLTK draw function use ? Widget or Window?
I'm trying to create a custom rpm gauge widget. everything looks fine when i test it by itself. But when i try to draw it at a different position in the parent window it seems to always draw using the origin of the window and not that of the widget no matter what x or y value i am passing to the constructor. a printf()...
Yep, that's correct. All coordinates in FLTK 1.x are relative to the window. Subwindows create their own coordinate space, i.e. coordinates in subwindows are relative to the subwindow, not the main window.
67,680,673
67,680,706
Efficient way of checking the length of a double in C++
Say I have a number, 100000, I can use some simple maths to check its size, i.e. log(100000) -> 5 (base 10 logarithm). Theres also another way of doing this, which is quite slow. std::string num = std::to_string(100000), num.size(). Is there an way to mathematically determine the length of a number? (not just 100000, ...
Why not use ceil? It rounds up to the nearest whole number - you can just wrap that around your log function, and add a check afterwards to catch the fact that a power of 10 would return 1 less than expected.