question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
69,632,161
69,632,442
Extremely basic question about namespaces in c++
using namespace X; cout << var; using Y::var; cout << var; So say I have a namespace X and a namespace Y that both contain a variable of type int called var. When I say using namespace X; what I imagine happening is if I use some variable that isn't in the global namescope what basically happens is it goes...
After the using directive using namespace X; the compiler uses the unqualified name lookup to find the name var used in the following statement cout << var; And due to the using directive it will find the variable var in the namespace X. This using declaration using Y::var; introduces the variable var from the names...
69,633,053
69,664,316
How can I convert an existing project with .c and .h files into a dynamic link library in visual studio 2019?
I am using the simple Open EtherCAT Master (SOEM) https://github.com/OpenEtherCATsociety/SOEM. I want to use the existing files in SOEM to create a .dll dynamic link library to build other projects with. I have tried creating a DLL in visual studio and simply uploading all the .c and .h files from SOEM to the DLL. When...
Making the DLL: put all .c and .h files into dll project set directories to all files in solution properties > configuration properties > c/c++ > additional include directories add additional dependecies to libraries for wpcap and others (Ws2_32.lib, wpcap.lib, winmm.lib) solution properties > configuration properties...
69,633,196
69,633,269
lambda iso std::bind for member function
I have the following class on which I run clang-tidy. template<typename Foo> class Bar { public: template<class THandlerObj> Bar(void (THandlerObj::*pCmdHandler)(const Foo&), THandlerObj* pCmdHandlerContext) : m_cmdHandlerFunc(std::bind(pCmdHandler, pCmdHandlerContext, std::pla...
You can use lambda's capture list to capture member function pointer and object pointer and invoke them inside the lambda. Try this: #include <functional> template<typename Foo> class Bar { public: template<class THandlerObj> Bar(void (THandlerObj::*pCmdHandler)(const Foo&), THandlerObj* pCmdHa...
69,633,205
69,633,400
libcurl C++: How to correctly install and use on CentOS 7
Goal: To correctly install and use libcurl C++ on CentOS 7. Current output: When I go to compile a program using libcurl with the command g++ somefile.cpp -lcurl -std=c++11 -o somefile, the following error is received: [user@localhost ~]$ somefile.cpp -lcurl -std=c++11 -o somefile somefile.cpp:10:23: fatal error: curl/...
You will need to install the libcurl-devel package as it contains the headers files you are missing. The libcurl-devel package includes header files and libraries necessary for developing programs which use the libcurl library. It contains the API documentation of the library, too
69,633,343
69,638,174
Write Apache Arrow table to string C++
I'm trying to write an Apache Arrow table to a string. My big example has problems and I can't get this little example to work. This one segfaults inside of Arrow in the WriteTable call. My bigger example doesn't appear to serialize correctly. #include <arrow/api.h> #include <arrow/io/memory.h> #include <arrow/ipc/api....
Two things jump to mind. First, I think this is a typo: longBuilder.Finish(&(columns.at(0))); arrow::DoubleBuilder doubleBuilder; doubleBuilder.Append(10.0); longBuilder.Finish(&(columns.at(1))); // Shouldn't this be doubleBuilder? Whenever you create an arrow table by yourself it is a good idea to ca...
69,633,363
69,633,373
How does the linker know where to find a dll file
I am working with Visual Studio and I am trying to get into dlls. I'm wondering how the linker knows where to find a DLL just from the lib file alone. I specify the lib file and its location in the project settings but where isthe location of the associated dll file specified? Or maybe i don't understand the topic corr...
The Standard Search Order for Desktop Applications from the Microsoft Dll Search Order documentation: If SafeDllSearchMode is enabled, the search order is as follows: The directory from which the application loaded. The system directory. Use the GetSystemDirectory function to get the path of this directory. The 16-bi...
69,634,096
69,636,536
Configured CMake to compile in C++20 but the executable compiles in C++17
I am trying to configure CMake to compile my C++ project using the C++20 standard, but it keeps compiling in C++17. My compiler settings in CMakeLists.txt are as follows: cmake_minimum_required(VERSION 3.21.3 FATAL_ERROR) list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) option(OPTIMISER "Optimiser level 3" OF...
So I have managed to compile using C++20 after upgrading to GCC version 11.1.0. Thank you @NicolBolas and @Frank for the insights :)
69,634,207
69,648,754
Using mutable for a preallocated working area
I have a C++ class A that can be constructed to perform a certain computation using a function A::compute . This function requires to write to a preallocated memory area (working area) that was allocated at construction of A to perform this computation efficiently. I would like to A::compute to be const in relation to ...
It is perfectly reasonable to use mutable in this case. While it is not physically const, the compute(...) method is logically const. That is, to an outside user, compute(...) leaves the object unchanged, despite any internal changes. Here in the isocpp.org FAQ, the Standard C++ committee recommends that we should pref...
69,634,466
69,634,524
Why template argument deduction doesn't work in C++?
I have an issue with template arguments deduction in C++. I don't know why the sample below doesn't work. The sample: #include <iostream> template<size_t n> void PrintArray(const int arr[n]) { for (int i = 0; i < n; i++) printf("%d\n", arr[i]); } int main() { int arr[5] = {1, 2, 3, 3, 5}; PrintAr...
This function declaration void PrintArray(const int arr[n]) { is equivalent to void PrintArray(const int *arr) { due to adjusting by the compiler the parameter having an array type to pointer to the array element type. From the C++ 14 Standard (8.3.5 Functions) 5 A single name can be used for several different funct...
69,634,555
69,635,110
GMock std::any argument
I have an interface class IUObject { public: virtual void setProperty(const std::string& name, const std::any& value) = 0; virtual void setProperty(const std::string& name, std::any&& value) = 0; }; I`ve created mock object: class MockUObject : public IUObject { public: MOCK_METHOD(void, setProperty, (cons...
AFAIK, there is no matcher for std::any, so you need to write your own. MATCHER_P(AnyMatcher, value, "") { // assume the type of parameter is the same as type stored in std::any, // will not work e.g. when any stores std::string and you pass a literal // you'd need to write a template matcher for that case...
69,634,598
69,634,882
std::vector of std::array of different sizes
As an exercise, I would like to construct a vector containing std::array<unsigned char, N> objects (where N varies). My attempt was to construct a base class GenericArray from which a MyArray<N> will derive, such that the container will actually be: std::vector<GenericArray*>. However, since the actual array variable m...
You seem to be mixing two concepts. I recommend the version in eerorika's answer but if you really want base class pointers in your container, here's one way: #include <array> #include <iostream> #include <vector> #include <memory> class GenericArray { public: using value_type = unsigned char; using iterator =...
69,635,212
69,635,422
What's the time-complexity function [ T(n) ] for these loops?
j = n; while (j>=1) { i = j; while (i <= n) { cout<<"Printed"; i*= 2; } j /= 2; } My goal is finding T(n) (function that gives us number of algorithm execution) whose order is expected to be n.log(n) but I need exact function which can work fine at least for n=1 to n=10 data I have tried to predict the f...
using log(x) is the floor of log based 2 1.) The inner loop is executed 1+log(N)-log(j) the outer loop executed times 1+log(N) with j=1,2,4...N times the overall complexity is T(N)=log(N)log(N)+2*log(N)+1-(log(1)+log(2)+log(4)...+log(N))= log(N)^2-(0+1+2+...+log(N))+2*log(N)+1= log(N)^2-log(N)(log(N)-1)/2+1= log(N)^2/...
69,635,343
69,640,909
Is there a way to save CGAL::Linear_cell_complex_for_combinatorial_map as .off or .obj format?
I have just implemented an algorithm that takes a surface mesh, tetrahedralizes it and saves the tetrahedralization data inside the CGAL data structure CGAL::Linear_cell_complex_for_combinatorial_map. I'm new to using CGAL library and I would like to know if there is a way to write CGAL::Linear_cell_complex_for_combina...
There is an undocumented function write_off(lcc) (cf here). In the off, when a face is shared by two volumes, the face is saved twice. Moreover, the output mesh is not a surface, and some tools (like meshlab) does not like such a mesh. It is easy to modify the code of write_off to save only the surface of your volumic ...
69,635,557
69,636,001
Conversion between types: C++ to C++/CLI
I am trying to wrap a C++ library into a C++/CLI library for use in C#. I am having trouble with conversion between types... The C++ function looks like this (this is from MyCppLib.h file, I can't change the C++ code): int CppFunc(void* Handle, wchar_t* Feature, long long* Value) My C++/CLI wrapper function looks like...
The marshal_context class is a native type, not a garbage-collected type. So you cannot write gcnew marshal_context() The intended use is as follows: marshal_context context; const wchar_t* unmanagedString = context.marshal_as<const wchar_t*>(managedString); // use unmanagedString // when context goes out of scope, bo...
69,635,623
69,635,687
Deleting dynamic array in C++ causes an error
I have a class called Myclass. In the main function, I have created an array object for this class. Whenever I try to delete this dynamically allocated array, the visual studio will say, Error: Debug Assertion Failed!. Expression: is_block_type_valid(header->_block_use). Can you please tell me what is causing this or s...
This: Myclass *obj[3] = { new Myclass, new Myclass, new Myclass }; is not a dynamically allocated array. It is an array with automatic storage, holding pointers to dynamically allocated objects. To properly clean up, you need: delete obj[0]; delete obj[1]; delete obj[2]; Because every new must be matched with a delet...
69,636,257
69,636,937
C++ Linked List Insert Implementation
Disclaimer: I am somewhat new to coding, and this is a pretty simple question, but I can't quite find the answer anywhere else, so I decided to ask my first question here, I hope it hasn't been asked already(if it has, I haven't found it). I hope this is an appropriate forum for my question. I'm trying to create a link...
First things first, this code snippet is inserting a new node at the beginning of our linked list (which is identified by the head pointer) and not at the end. v is a temporary identifier to hold our new node which is not attached to our list yet. Let's say our list looks like this initially: [head] -> [1,n2] -> [2,n3]...
69,636,423
69,636,472
Functor or boolean comparator
What should I use? bool compare or sCompare() functor? And why? Are there some differences between using this two options? struct Dog { int m_age{}; int m_weigt{}; }; bool compare(const Dog& a, const Dog& b) { return a.m_age > b.m_age; } struct sCompare { bool operator()(const Dog& a, const Dog& b) ...
Your two comparators result in opposite ordering (< vs >). Other than that the biggest difference is that you cannot define a function within a function, but you can define a type in a function. Moreover, lambda expressions offer straightforward syntax to do that: int main() { vector<Dog> dogs{ Dog{1,20}, Dog{2,10}...
69,636,479
69,647,357
QTimer::singleShot(..) inside connect(..) function
I want to update the background of my game after 10 seconds. I used singleShot function of QTimer inside the connect function. It does work correctly for the first time but after the first call, update background function is being called after every 1 second (or so). I am new to Qt, please excuse my ignorance. Here is ...
So I removed the singleShot function and inserted simple connect function with a timeout 100000 ms. void Scene::setUpPillarTimer(QGraphicsPixmapItem* pixItem) { QTimer *backgroundTimer = new QTimer(this); int durationOfPillar = 0; connect(backgroundTimer, &QTimer::timeout, this, [=](){ updateBack...
69,636,506
69,667,646
Rationale behind the usual implemention of std::swap overloads
Let's consider the following minimal code sample: // Dummy struct struct S { int a; char * b; // Ctors, etc... }; void swap(S & lhs, S & rhs) { using std::swap; swap(lhs.a, rhs.a); swap(lhs.b, rhs.b); } Context I know that when we intend to call a swap() function, the proper and recommended...
since S members are built-in types, is it fine (well-formed) to define it as below instead: [std::swap usage] Yes. I mean, it works because std::swap just "swaps the values a and b" if they are both MoveAssignable and MoveConstructible, which built-in types are. If the members are all built-in types (or pointer type...
69,636,547
69,637,173
C(++): Replace function declaration with macros but not its invocations
I have a library I can't change where some function is declared, implemented and used, in single file. Lots of other stuff is done in that same file. I want to override that single function to do another thing. The issue is that when I use renaming macro, all the places where that macro/function name is found are repla...
It may or may not be possible depending on how exactly the function is defined and used. Assuming the exact declaration and usage you've shown, you can do this: #define foo(a, b) FOO_LOW(CAT(DETECT_, a) CAT(DETECT_, b))(a, b) #define CAT(a, b) CAT_(a, b) #define CAT_(a, b) a##b #define DETECT_int , #define FOO_LOW(....
69,636,593
69,658,895
Predefined C++ Types (compiler internal) Not Found error
I'm attempting to write a game of tic tac toe just for fun and am running into this error when I try to debug the application. The error occurs on line 23, the multidimensional std::array declaration. I can't find any material on the subject or come up with my own solution. The error shows up in a "Source not found" ta...
This is an error of VS. It works when I remove /permissive-. This problem has already been reported.
69,637,120
69,637,163
How to avoid copy/memory overhead when wrapping a stack allocated object?
Let's say I have a large blob object that is stack allocated. I need to put that in a wrapper object but I want to avoid a copy. Should I just use std::move with a move constructor? What would be the easiest way to prove that it works? struct Blob { char blob[1024 * 1024]; // imagine something big here }; template...
In this case, Blob is plain old data. The compiler is free to optimize the variable Blob blob out of existence. It is also free to make a million copies of it for no reason whatsoever. The standard does not constrain it. There is an optimization called "static single assignment" that represents local object states as...
69,637,186
69,637,277
Cast pointer of the base class to pointer of the inherited class with template
My code looks something like this: class A { ... }; template<typename T> class B: public A { ... }; A* pointerA = new B<X>(...); But now I want to cast another pointerB to pointerA: B<...>* pointerB = (B<...>*)pointerA; How do I know what to insert into <...> or how I should do this correctly?
You can try the cast with dynamic_cast. If you dynamic_cast to a pointer type and it fails, you get a null pointer back. If you dynamic_cast to a reference type and it fails, you'll get an exception. Example: #include <iostream> class A { public: virtual ~A() = default; }; template<typename T> class B : public A ...
69,637,240
69,765,184
"ferror" tests "scanf" input
I tried to enter error data in next program but it can't recognize the error. Once I entered numeric data, and next time entered string data but the program made no reaction: #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; int main(void) { int i; scanf("%d",&i); if(ferror(s...
Don't assume what a function does. Read it's documentation. https://www.cplusplus.com/reference/cstdio/ferror/ int ferror ( FILE * stream ); Check error indicator Checks if the error indicator associated with stream is set, returning a value different from zero if it is. This indicator is generally set by a previous o...
69,638,177
69,638,363
How do you block shared memory access until it is ready?
I'm trying to share a mutex between several processes. Each process will begin running at some random time so I need each to to be capable of setting up the shared memory and getting the mutex ready for usage. This works great so far: int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR); if (fd < 0) { fd = s...
I've actually solved my own question here, anyone have any suggestions for improvements? Solution: int lock_fd shm_open(setup_control, O_RDWR | O_CREAT, S_IRUSR, S_IWUSR); flock(lock_fd, LOCK_EX); int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR, S_IWUSR); if (fd < 0) { fd = shm_open(name, O_RDWR, S_IRUS...
69,638,421
69,638,546
Conway's game of life algoritm is not working
I'm trying to simulate conway's game of life. The algorithm I made is not working, but I can't figure out how. If I have a situation like this: |.........| |....x....| |....x....| |....x....| |.........| a . is a dead cell, an x is an alive cell It is expected that the vertical bar flips into a horizontal bar, bu...
You count the neighbor cells wrong Both x and y are runing from 0 to 2 not from -1 to 2. in for (int y=0; y<2; y++) {//should be int y=-1; y<2; y++ for (int x=0; x<2; x++){//should be int x=-1; x<2; x++ if (i != 0 and j!= 0) { // shold be x!=0 or y!=0 if (world[i+y][j+x]) count++; } ...
69,638,521
69,644,144
C++ multithreaded access of boolean member
Due to low latency requirement, I'm using parallel execution of for_each to recognize intention of a sentence (a set of strings). I learnt before that there is no need for mutex to protect bool or any data type that its size is less than one byte. So I'm asking if accessing boolean member Tag.m_Found is thread safe? Ot...
The issue is if adding "std::mutex m_Found_access;" or making "atomic_bool m_Found;" the default move constructor is deleted so I need to define a move constructor for Tag. And m_Found should only be set to true to avoid race condition (as @Nate Eldredge mentioned). The code becomes: #include <iostream> #include <unord...
69,639,021
69,639,101
Comparator for member variable of type std::set that requires access to other member variables
I have a class ShapeDisplay that stores a set of Rectangles. I would like to store them sorted, therefore I use a std::set. My intention is to provide a custom comparator, which compares the origin (x, y) of the rectangle to a reference point (x, y) in the display. However, in order to achieve this, the comparator need...
CenterComparator isn't related to ShapeDisplay, it isn't aware of its members and it isn't derived from ShapeDisplay. You need to provide CenterComparator with its own reference Point. You then need to provide an instance of CenterComparator whose reference point is set. Note that if you change that comparator's refere...
69,639,305
69,639,413
How can i save every move that was made "a, w, s, or d" to an array?
I want to save every move 'char' to an array, and then call back all arrays to see the history cout << "=== Chose ===" << endl; cout << "Choose were to GO" << endl; cout << "a, w, s, or d" << endl; cout << endl; cin >> Сhoice_1; if (tolower(Сhoice_1) == 'a') { cout << "You made a step to the left" << endl; ...
You could run into trouble with the length of your array, but this would work. char moveArray[1024]; int moveArrayIndex = 0; ... cin >> Сhoice_1; moveArray[moveArrayIndex++] = Choice_1; moveArray[moveArrayIndex] = 0; // This makes it a printable string. ... The problem with this is that you're flow off the end of ...
69,639,392
69,639,699
Getting value from Edit to work with region
I needed to divide the picture into sectors and count the number of black dots in each of them. I use regions for this. Can I do this with the Edit input field somehow? HRGN region [n]; HRGN requires a constant value like const n = 35; Please, help if it is possible to somehow link HRGN with Edit, for example, if Edi...
I think you are asking how to allocate an array using a TEdit to specify the array's count, is that right? Consider using T(C)SpinEdit instead of TEdit for numeric input. You can allocate an array dynamically at runtime using new[]: HRGN *region = NULL; ... int n = Edit1->Text.ToInt(); // or SpinEdit1->Value region = n...
69,640,526
69,640,618
Prime numbers - I need clarification on code implementation
This is the code I know: bool checkPrime(int n) { bool prime = true; for (int i = 2; i < n; i++) { if ((n%i) == 0) { prime = false; } } return prime; } But is this ok if you’re looking for prime numbers: List<int> arr = [2, 3, 5, 7]; // Already known int n = 30; // Between...
Your code is incorrect. This code only works because you are taking the value of n as 30, for a greater number like 1000 this will produce an incorrect result. List arr = [2,3,5,7]; // already known int n = 1000; // between 1 to 1000 it could be any number List<int> arr = [2,3,5,7]; for (int i = 2; i < n; i++) { i...
69,640,788
69,643,297
Casting a reference to a pointer to a reference to a void*
Is the following well defined behavior? #include <cstdlib> #include <iostream> void reallocate_something(void *&source_and_result, size_t size) { void *dest = malloc(size); memcpy(dest, source_and_result, size); free(source_and_result); source_and_result = dest; } void reallocate_something(int *&sourc...
Is the following well defined behavior? No, it's not. You can't interpret int * pointer with void * handle, int and void are not similar types. You can convert an int * pointer to void * and back. If your function takes a reference, to do the conversion you need a new temporary variable of type void * to hold the res...
69,640,896
69,640,990
How to understand the first type of pair?
I am learning C++ recently and am confused by this data type: pair<map<string, size_t>::iterator, bool> ret = word_count.insert(make_pair(word, 1)); It should be easy to see that we’re defining a pair and that the second type of the pair is bool. The first type of that pair is a bit harder for me to unders...
iterator is a nested type inside of the std::map class. The first member of the pair is an iterator to an element in the map. The insert() method returns an iterator to the element that was inserted, or to the element that prevented the insertion. The bool in the pair indicates whether the insertion was successful or ...
69,640,911
69,640,946
Should I use the "delete" for the object member which initialized by "new" operator in constructor?
I have a question about new and delete: Should I use delete for the input parameter or member object, e.g.: https://github.com/jwbecalm/Head-First-Design-Patterns-in-CPP/blob/main/ch01_Strategy/main.cpp Should I use delete on the object allocated by new FlyNewWay()? // change behavior in runtime mallardDuck->setFlyBeha...
Yes whenever you use new keyword to allocate some memory then you must always use delete to free up that memory later when no longer needed. Otherwise you will have a memory leak as in your program. In your case you should use delete inside the destructor in the MallarDuck.cpp . Other solution would be to use smart poi...
69,641,196
69,750,186
Configure vscode to build and run c++ in one terminal
I installed mingw64 toolchain with MSYS2, and managed to successfully run my code from vscode. However, running it creates two terminals, one for building and one for running the generated file: C/C++: g++.exe build active file and cppdbg: main.exe. cppdbg: main.exe leaves the text from the previous runs and "presenta...
You are asking two questions and I can answer both. How do I build and debug the application, by making sure that it is launched only when the build is successful? How do I configure it to run the application similarly? Let me answer 2 first. To solve this, you need the dependsOn property of tasks. For example, thi...
69,641,336
69,646,291
How do I make the operating system save my credentials when I use WNetAddConnection2 or WNetAddConnection3?
I wrote a window to enter my username and password to login. I can't save the credential when I use the following method, what should I do NETRESOURCEW net_resource {0}; net_resource.dwType = RESOURCETYPE_DISK | RESOURCETYPE_ANY; TCHAR szRemotePath[MAX_PATH] {0}; _tcscpy_s(szRemotePath, MAX_PATH, remote_path.toStdWStri...
You need to write the credentials into the credential vault, e.g. with CredWriteDomainCredentials. See my answer in this question for an example (written in Delphi but should be very straightforward to convert to C/C++)
69,641,471
69,641,634
Variadic macro for checking if variable equals one of variadic arguments
I'm currently working on a WebGL-like OpenGL wrapper in c++, which involves verifying that arguments are actually valid. The problem, more or less, is that OpenGL has a ton, and I'm not exaggerating here, of valid arguments for certain functions. (Image of a naive conditional (possible internalformat constants for glT...
You might want to use C++17 fold expression: template<class... Args> bool check(const unsigned int var, const Args&... args) { return ((var == args) || ...); } Then you can invoke something like this: check(var, CONSTANT_1, CONSTANT_2, CONSTANT_3);
69,641,553
69,644,294
Decision tree- delete from a specific node
I have a decision tree that includes node and answer that leads us to another nodes. Answers begin with ":" and nodes are the rest. I have to do a function that delete a subtree from a specific node. For example If I want to delete node "brand?", I want that after that the tree will print from car-color? to blue-is-be...
Now having understood the problems (highly restrictive requirements and what is causing your code to fail), I now have an answer for you. The issue is, that you need to remove the node you've deleted from the collection it is stored in. For this purpose, you need to use an alternate version of your search to detect, wh...
69,641,838
69,819,339
TCP packet drop (ns3)
I am new to ns3 network simulator and wanted to know how to get the number of packet drops in a TCP connection. I know of the following command: devices.Get (1)->TraceConnectWithoutContext ("PhyRxDrop", MakeBoundCallback (&RxDrop, stream)); But this is helpful only for a single TCP connection over a p2p link. In my to...
The usage of RxDrop tells me you're using referring to fourth.cc in the ns-3 tutorial. Connecting to the PhyRxDrop TraceSource will result in the requested CallBack being invoked for each dropped packet. ns-3 doesn't have a packet filter such that the CallBack would only be invoked for some packets. However, you can de...
69,642,411
69,642,522
Can I use dijkstra_shortest_paths in BGL on "cyclic" directed graph
At first, Sorry for my english :( my graph's spec is cyclic directed edge weight is positive or zero As I know dijsktra algorithm cannot find shortest path of "cyclic" graph. But there is no that restriction in BGL docs (https://www.boost.org/doc/libs/1_77_0/libs/graph/doc/dijkstra_shortest_paths.html) So I wonder I ...
Yes, you can in fact use the method. Dijkstra works with cycles in graphs as long as they are positive The documentation of the method states, which does not apply given your specs: Use the Bellman-Ford algorithm for the case when some edge weights are negative See also https://cs.stackexchange.com/questions/101637...
69,642,797
70,500,694
ESP32 Arduino httpSecureClient -1 error at core 0 without reason why
I'm having an issue with the httpsecureclient library for the ESP in the Arduino IDE. I try to send http requests to a https domain (that doesn't change) and works alot of times just fine. Like I do some HTTP calls to obtain certain data to let the ESP do it's thing. But when I want to let the ESP post a payload to a s...
I currently run into same troubles after updating the libraries, old code for esp32 http clients stopped to work with the same symptoms. I could solve this by switching to simply use HTTPClient only, without WiFiClientSecure. And it works with https. #include <HTTPClient.h> #include <Arduino_JSON.h> void getPrices...
69,642,941
69,643,678
Clarification on difference in ODR rules for structs in C and C++
I am aware of how ODR, linkage, static, and extern "C" work with functions. But I am not sure about visibility of types since they cannot be declared static and there are no anonymous namespaces in C. In particular, I would like to know the validity of the following code if compiled as C and C++ // A.{c,cpp} typedef st...
I will use for references the n1570 draft for C11 for the C language and the draft n4860 for C++20 for the C++ language. C language Types have no linkage in C: 6.2.2 Linkages of identifiers §6: The following identifiers have no linkage: an identifier declared to be anything other than an object or a function... That...
69,642,963
69,643,213
Recursive function for digit sum in c++
Tried writing a recursive function for digit sum in c++ ; ended up getting the last digit instead. Can anyone suggest fixes.. ''' #include<iostream> using namespace std; int dsum (int n, int sum) { if(n>0) { sum = sum + (n%10); n = n/10; return(n ,sum); } else return sum; } in...
You didn't call the recursion as seen in here: int dsum (int n, int sum) { if(n>0) { sum = sum + (n%10); n = n/10; return(n ,sum); // <-- this line } else return sum; } Notice you return(n ,sum); instead of return dsum(n ,sum);. return(n ,sum); fist evaluates the left operand: ...
69,643,315
69,643,414
Collect all boost fusion map keys into a std::tuple
Consider this snippet: #include <boost/fusion/container/map.hpp> #include <boost/fusion/sequence/intrinsic/at_key.hpp> #include <boost/fusion/sequence/intrinsic/value_at_key.hpp> #include <tuple> struct MyEvents { struct EventA; struct EventB; using EventMap = boost::fusion::map<boost::fusion::pair<EventA,...
You can get the key type of boost::fusion::pair by using T::first_type. template <typename T> struct GetTypes; template <typename... Pairs> struct GetTypes<boost::fusion::map<Pairs...>> { using type = std::tuple<typename Pairs::first_type...>; }; Demo.
69,643,551
69,643,594
Does make_shared ignore explicit specifier?
Consider the following example: #include <iostream> #include <memory> struct A { explicit A(int x) { std::cout << x << std::endl; } }; void Foo(A ) {} std::shared_ptr<A> Foo2(int x) { // why does this work? return std::make_shared<A>(x); } int main() { A a(0); Foo(a); // Fo...
This is expected behavior, because std::make_shared performs direct-intialization, which considers explicit constructors too. The object is constructed as if by the expression ::new (pv) T(std::forward<Args>(args)...) Direct-initialization is more permissive than copy-initialization: copy-initialization only conside...
69,643,998
69,644,108
C++ ifstream is reading last line only
I am working on a program that allows a user to register an account. When a user registers for an account, the username and password are output to a text file "database.txt". There is also an option for a user to search for their password by inputing their username if they forget their password. I find that this works ...
You should break out of the while loop once you have found the user name here: while(searchUserName >> su >> sp) { if(su == searchUser) { count = 1; break; // add this } } Now it will continue to overwrite a previously found us...
69,644,031
69,644,491
Can an enum class variable take the full range of integer values?
Sometimes it happens that you want to give names to some integer values, but allow for other values than the named ones. In C++, this is easily achieved with an ordinary enum: enum { red, green, blue }; int color = 999; Suppose in some unusual context, you want to use enum class for type checking, but also allow for o...
[dcl.enum] 8 For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. Once the underlying type is fixed, any value in its range is a value of the enumeration. The enumerators are just named constants in that range. There is some minutiae involved in deter...
69,645,963
69,646,192
templating a random number generator in c++
I know my code is wrong. I should have uniform_int_distribution<int>, but I need a random number generator that works whatever the type is. I mean I could generate int and divide them by 10^n to get a float but I dont like the elegance of it. template <class T> T aleaGenVal(const T &min,const T &max) { std::random_...
std::uniform_int_distribution is only defined for some fundamental integer types, and std::uniform_real_distribution is only defined for the fundamental floating point types. You could choose between those with std::conditional_t Unfortunately there are a number of integral types that are not usable with std::uniform_i...
69,646,072
69,646,227
how can i use (!(cin>>a)) twice times?
enter image description here i have used code ( if (!(cin >> arr[i])) ) to check if input from user is different with type int (like string, char) to stop reading into array (arr1), and then i can't use it twice with the second array (arr2), it didn't read input and go straight to cin.clear and return... Can you help m...
It seems you mean the following #include <limits> //... if ( not ( std::cin >> arr[i] ) ) { //... std::cin.clear(); std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); }
69,647,075
69,729,897
Defining namespace in g++ works for some files but fails for others
I won't be able to show any code, but let me explain what is happening: I'm attempting to compile some software with g++; I have my Makefile setup. There is a main file which calls the necessary functions to get this software working. I have all of my dependencies includes, i.e. all of the header files, all of the .cpp...
The solution to my original question was to compile the source files that needed OPTLEVEL defined into their own libraries. Then when it came to compiling the main.cpp file, I had to ensure I linked those .a's, and added the linking flags i.e. -llibName. It took a lot of effort, but this is exactly what needs to be don...
69,647,361
69,647,462
how to store struct in a text file in c++
I want to store the elements of struct into a text file. I have multiple inputs and this is what I have done, however, I can only store the latest inputs but not all the input. Thanks in advance for the help! Here is my code: #include <iostream> #include <fstream> using namespace std; struct ProcessRecords { strin...
First In C++(by C++ i mean standard C++ and not extensions), the size of an array must be a compile time constant. So you cannot write code like: int n = 10; int arr[n]; //incorrect Correct way to write this would be: const int n = 10; int arr[n]; //correct For the same reason the following statement is incorre...
69,648,232
69,659,045
Cannot modify Process DACL that I own with my code but Process Hacker can
I have a process (let's call it ProcessX) that runs by default with only Terminate, Synchronize, and Query Limited Information permissions. When I look at ProcessX in Process Hacker, I can see the permission (ACE, Owner, etc). I can see that I'm the owner of ProcessX, I can see the 3 limited permissions associated with...
Problem solved ! I've assumed that READ_CONTROL will be refused because it wasn't available on the DACL of the running process. Turns out, when you own an object, you have implicit READ_CONTROL and WRITE_DAC permission on it, even if zero ACE are set on the object for the user owning it. #include <windows.h> #include <...
69,648,820
69,649,512
Is passing of a function pointer through a class type in non-type template parameter allowed in C++20?
Recently, after playing around with the C++20 feature of being able to pass class types in non-type template parameters (P0732R2), I've encountered something rather strange. Consider the following code: template <typename T> struct abc { T p; consteval abc(T p) : p(p) { } consteval operator decltype(p)() co...
Which compiler is correct here? Clang is correct, the code as written is valid. GCC not handling that specific case is a known issue.
69,649,035
69,649,401
c++ calculate depth of the function calls that led to the current function
say we have a set of function calls that are executed in the following order similar to a tree. that is func0 call func1 and func2 in order. and func2 results in calling func3, afterwhich func0 continues to its next line for executing func4. func0 // depth 0 func1 // depth 1 func2 // depth 1 func3 // depth...
One way is to create an RAII class that counts the depth, and instantiate it at the top of each function you wish to track. I've done this sort of thing for debugging purposes. class DepthCounter { static int depth; public: DepthCounter(const std::string& name) { std::cout << std::string(depth*2, '...
69,649,469
69,649,830
Ambiguity when inheriting ostringstream
I have a simple struct which inherits from std::ostringstream, in order to handle some values better for databases. If I just inherit, and add in a simple constructor to set widths for precision of doubles, it works fine. struct myostream : std::ostringstream { myostream() noexcept( false ) { this->precisio...
Here's one option: struct myostream : std::ostringstream { using std::ostringstream::operator<<; // bring in all the member overloads myostream() noexcept( false ) { this->precision( 6 ); this->setf( ios_base::fixed, ios_base::floatfield ); } // call the base class member functi...
69,649,478
69,649,496
-Wunused-but-set-variable is emitted when I use 'auto' and not when I use the corresponding type instead of 'auto'
Please consider the following: #include <functional> int main() { std::function<int(int)> f_sq = [](int i) -> int { return i *= i; }; // No warning auto f_sub = [](int a, int b) -> int { return a - b; }; // -Wunused-but-set-variable return 0; } Why compiler warns when the auto keyword is used...
std::function<int(int)> has a non trivial destructor, so might be a RAII object. Your lambda (remember, lambda is NOT a std::function) has trivial destructor, so it is not a RAII object, so it is really unused. You might minimize your example with simpler types to avoid confusion lambda/std::function: std::vector<int> ...
69,649,792
69,649,954
How to publish Int16MultiArray from rosserial arduino
I am trying to publish an Int16MultiArray for the ros package mecanum_drive: https://github.com/dudasdavid/mecanum_drive My issue is that I cant seem to publish the array from my arduino. (I am using Teensy 4.1) #include <std_msgs/Int16MultiArray.h> ros::NodeHandle nh; std_msgs::Int16MultiArray wheel_ticks; ros::Publi...
A very specific limitation of rosserial is arrays have an extra field specifically for data length. This is needed since the data field is implemented as a pointer, thus having no real good way to get data length. The message type actually looks like this class Int16MultiArray{ Header header; int data_length; ...
69,650,085
69,650,343
Why does Child Class shaddow Parent methods even though parameters are of different type
My parent class holds two functions: On is supposed to be overwritten by the child, the second (same name) just uses as input a different type and than uses the overwritten method. Now I understand that if I define in the child class a method with the same name and same input parameters, it will shadow (is that the rig...
You can choose to expose the method with a using statement: class B : public A { // ... using A::getSize; } In your code snippets, you have used uninitialised values in many places, this invokes UB.
69,650,183
69,650,624
Why is 1 for-loop slower than 2 for-loops in problem related to prefix sum matrix?
I'm recently doing this problem, taken directly and translated from day 1 task 3 of IOI 2010, "Quality of life", and I encountered a weird phenomenon. I was setting up a 0-1 matrix and using that to calculate a prefix sum matrix in 1 loop: for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if...
If you look at assembly you'll see the source of the difference: Single loop: { if (a[i][j] < x) { lower[i][j] = 0; } else { lower[i][j] = 1; } b[i][j] = b[i-1][j] + b[i][j-1] - b[i-1][j-1] + lower[i][j]; } In this case, there's a data ...
69,650,616
69,650,688
How to retrieve the captured substrings from a capturing group that may repeat?
I'm sorry I found it difficult to express this question with my poor English. So, let's go directly to a simple example. Assume we have a subject string "apple:banana:cherry:durian". We want to match the subject and have $1, $2, $3 and $4 become "apple", "banana", "cherry" and "durian", respectively. The pattern I'm us...
If the input contains strictly items of interest separated by :, like item1:item2:item3, as the attempt in the question indicates, then you can use the regex pattern [^:]+ which matches consecutive characters which are not :, so a substring up to the first :. That may need to capture as well, ([^:]+), depending on th...
69,650,647
69,650,704
How to bring std::cout output back to the top after a new line
I have the following menu, which is supposed to update based on whether the user has typed the keys F1 or F2: int main() { bool f1 = false; bool f2 = false; while (true) { std::cout << "[F1]: " << (f1 ? "ON" : "OFF") << std::endl; std::cout << "[F2]: " << (f2 ? "ON" : "OFF") << s...
You can use SetConsoleCursorPosition to set the cursor location back to the top left after doing the clear. There are also ANSI escape codes (similar to the one you use to clear the screen) that would allow you to reposition the cursor. "\033[r;cH" replacing r with the row and c the column to move to. They are 1-based...
69,651,022
69,694,907
pjsip (pjsua2) - opus codec for windows
is it possible to build pjsip with opus-codec for windows as dll? I built pjsua2.dll alone but seems no way to use opus with it.
I downloaded opus and pjsip , opened pjsip from visual studio solution, added opus projects to solution and made reference to them from libpjpproject, then build it using this link link
69,651,088
70,844,055
clang-format AlignAfterOpenBracket list params
This post asked a similar question about how to modify formatting when there are too many parameters. I quite like the rust-fmt styling for this. Is there any way to do this with clang-format? e.g. 1: with AlignAfterOpenBrackets: AlwaysBreak return_t foo( some_t param_1, some_t param_2, some_t param_3, some_t ...
clang-format AlignAfterOpenBracket just got a new option - BlockIndent (landed on 17/1/22) which does exactly that. See https://reviews.llvm.org/rG966f24e5a62a: [clang-format] Add a BlockIndent option to AlignAfterOpenBracket This style is similar to AlwaysBreak, but places closing brackets on new lines. For example, ...
69,651,774
69,652,959
Debug assertion failure - C++, using smart pointers
I have been trying to debug this for a while now without any luck. I was hoping to get some help here. Apologies if my question isn't relevant or something, I'm new. So basically what I have is: #include <iostream> template<typename T> class Node { using NodePtr = std::shared_ptr<Node<T>>; private: Node() {} ...
There are a few problems. First, if you want to get a shared_ptr from this, you have to inherit from std::enable_shared_from_this: template<typename T> class Node : std::enable_shared_from_this<Node<T>> { // ... The main problem is that there is a shared_ptr referencing a shared_ptr (the parent to the child, vice-...
69,651,777
69,652,256
Generate High Quality textures Realtime C++
I am having a procedural terrain generation application. Now i want to generate textures for the terrain based on height. Say i have got 5 textures for different height levels now for every pixel i calculate the the position of it on the mesh then get its height and then decide which texture to sample from. Note textur...
Use a varying variable between your vertex and fragment shader. A single float value should suffice, since you're only interested in the height coordinate. Other than that, introduce 5 uniform varaiables for your textures in the fragment shader and do the calculations on the GPU. In more detail: For each fragment you g...
69,652,171
69,652,207
What does # operator do in C++ macros?
I came across this macro: #define STR_ERROR(ecode) case ecode: return #ecode; What does the #ecode part do? ecode is an int, and this function returns a const char*. I'm sure that this has been answered already, but my search-foo has abandoned me. ecode itself is specific to this code. Searching for c++ # gives generic...
According to cppreference: # operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal Example from Microsoft Docs #include <stdio.h> #define stringer( x ) printf_s( #x "\n" ) int main() { stringe...
69,652,417
69,653,214
Receive values from dynamic array
I recently asked question about how to work with element Edit1 dynamically, now I want to ask something about values, which I received from dynamical arrays. First I try to divide image into sectors: const n=20; unsigned short i, j, line_length, w = Image1->Width, h = Image1->Height, l = Left + Image1->Left, t = To...
The problem is that I received different values if I do it dynamically or statically(n=20) There is no difference whatsoever in accessing elements of a static array vs a dynamic array. Your problem has to be elsewhere. For instance, your static code is initializing all of the array elements to 0, but your dynamic co...
69,652,544
69,652,717
When a template is instantiated?
The fact that a template is not instantiated until it is used so for example if I have this class template: template <typename T> struct Pow{ T operator()(T const& x) const{ return x * x; } }; void func(Pow<double>); // Pow<double> instantiated here? void func(Pow<int>){} // Pow<int> instantiated here? int main...
The general rule for implicit instantiation of class templates is as follows [temp.inst] 2 Unless a class template specialization is a declared specialization, the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type ...
69,652,744
69,652,829
C++ Singleton private constructor not accessible from static function
I have a singleton class declaration here: #ifndef GLFW_CONTEXT_H #define GLFW_CONTEXT_H #include <memory> class GLFWContextSingleton { public: static std::shared_ptr<GLFWContextSingleton> GetInstance(); ~GLFWContextSingleton(); GLFWContextSingleton(const GLFWContextSingleton& other) = delete; GLFWCon...
The static function does have access to private members. make_shared does not. make_shared is a template function that forwards the arguments it gets and calls the constructor of the specified class. So the call to the default constructor happens inside the make_shared function, not inside the GetInstance function, hen...
69,653,208
69,653,558
If a function definition has a parameter of class template type and didn't use it (its members) then is it instantiated?
From the previous example I've posted here about when the template is instantiated?, I got the answer that only when a template is used the compiler instantiates it. But look at this example: template <typename T> struct Pow{ T operator()(T const& x){ return x * x; } }; extern template struct Pow<int>; // explicit...
The program works just fine and doesn't complain about the missing definition of Pow<int>! Because it isn't missing. Both forms of explicit instantiation (declaration and definition) cause the instantiation of class templates. An explicit instantiation definition causes the instantiation of member functions (which ar...
69,653,849
69,654,056
Mysterious C++ variadic template expansion
The following C++ function is extracted from lines 151 - 157 here: template <typename... T> std::string JoinPaths(T const&... paths) { boost::filesystem::path result; int unpack[]{0, (result = result / boost::filesystem::path(paths), 0)...}; static_cast<void>(unpack); return result.string(); } The function Joi...
int unpack[]{0, (result = result / boost::filesystem::path(paths), 0)...}; The first 0 is there to not try to create an empty array if someone calls the function with zero arguments. (result = result / boost::filesystem::path(paths), 0) This evaluates result = result / boost::filesystem::path(paths) and discards it. ...
69,654,196
69,659,720
Is it possible to control the Openmp thread that is used to execute an openmp task in C++?
Is it possible to control the openmp thread that is used to execute a particular task? In other words say that we have the following three tasks: #pragma omp parallel #pragma omp single { #pragma omp task block1(); #pragma omp task block2(); #pragma omp task block3(); } Is it possible to control the set o...
In a certain sense, this can be accomplished using the affinity clause that has been introduced with the OpenMP API version 5.0. What you can do is this: float * a = ... float * b = ... float * c = ... #pragma omp parallel #pragma omp single { #pragma omp task affinity(a) block1(); #pragma omp task affinity(b) ...
69,654,338
69,654,437
Read access violation when running my program
I am creating a simple Bank system in c++ to test my knowledge since I'm a beginner. I am having trouble with writing data to a private class, and after looking around on the internet I came up with a solution that I thought would work but doesn't. There is an exception thrown when I finish the "Creating a user" part w...
Your pointer casting is all over the map and certainly "unusual" and incorrect for what you're trying to do. This line *i = createusern; is incorrect because i is not pointing to a string. It is pointing to a User object. That you really want to do here is something like this User.setUsername( createusern ); …and the ...
69,654,724
69,655,422
How do I read in a text file separated by spaces into an array in c++?
I have a text file of number called InputFile.txt. The file looks like this: 10.5 73.5 109.5 87 45 108 66 117 34.5 13.5 60 97.5 138 63 130.5 4.5 40.5 43.5 60 18 I want to read this file and insert each individual number as an element of the array arr. I know what I have does not attempt to add the elements to the arr...
I have given 2 solutions to this problem. The below program reads double from input.txt and if there is some invalid entry in the file lets say there is some string then it will skip that string and read the next value and only if that value is valid(double) it will put it into the array as you desire. Solution 1: Usin...
69,654,793
69,655,875
How to find line number in ThreadSanitizer stack trace
I compile using Clang with -g3 and -O1 flags, but TSan complains that it found a data-race and it outputs a totally obscure stack trace with no clear line numbers. How to find line numbers in this case? Output on Pastebin since Stack Overflow doesn't support more than 30k chars. https://pastebin.com/raw/6izxznym
Look for "/home" for finding your code. The stacks of the threads look nice with well shown line numbers. Your MediaServer::initialize() created the thread T1. Thread T1 (tid=2667937, running) created by main thread at: #2 MediaServer::initialize /home/MediaServer/MediaServerMethods.cpp:1808 #3 main /home/MediaServ...
69,654,900
69,667,187
Is there any rule against putting more than one parameter in a mutator?
I need my mutator to call a different function in my constructor and another function anytime after that, so I was thinking of putting a bool as a second parameter to differentiate as follows: void SetName(const char* name, bool init) { init ? this(name) : that(name); } Is this against convention or anything? Sho...
It allows you to make a mistake which can instead be prevented at compile-time. For example: Example example; example.SetName("abc", true); // called outside the constructor, `init == true` anyway To prevent such situations, just replace your struct Example { Example() { SetName("abc", true); } void SetName(co...
69,655,137
69,655,212
How to contruct header file for class with struct define inside in C++
If I have class that contains a struct in it. How do I declare that struct inside of a header file? See example below. Is this the correct syntax? context: my professor has a IList.h file that we have to implement in a LinkedList class. That's why there's inheritance syntax in my examples. LinkedList.cpp #include "Link...
You'll need to redeclare at least the pure-virtual methods from IList in your LinkedList class, otherwise LinkedList will be an abstract class and so the compiler won't allow you to instantiate a LinkedList object: // LinkedList.h #ifndef LINKED_LIST_ #define LINKED_LIST_ #include "IList.h" class LinkedList: public I...
69,655,333
69,657,647
Clunky movement on transformable objects SFML
So I am working on a game in SFML and am having a weird problem with movement. I have implemented a delta time so the movement speed is constant but I have this weird issue where I press a move key, the object jumps by speed units, pauses, then proceeds to move smoothly. I haven't been able to find much on this as I do...
Your main is mixing event processing and state updates with drawing, which makes it hard to respect the fractional updates you intend to do with dt. The code below undoes that: it first eats all events, then updates the game state, then draws. In order to have smooth movement, you need to remember the Player velocity d...
69,655,477
69,689,950
In Openmp is there a way to find out the place to which the master thread is assigned?
With openmp's thread affinity mechanisms, the master thread is assigned to the place where the parent of the master thread is running (where the set of places is specified by OMP_PLACES). It is my understanding that effectively this means that the OS determines the place where the master thread gets executed. Is there ...
How about omp_get_place_num()? The OpenMP specification states: The omp_get_place_num routine returns the place number of the place to which the encountering thread is bound. Another possibility is to set the OMP_DISPLAY_AFFINITY environment variable to true which will cause the affinity information to be displayed.
69,655,884
69,655,987
LinkedList class implementation cannot declare variable to be of Abstract Type
Where am I going wrong in constructing my LinkedList class? I've re-declared the pure-virtual methods from IList in your LinkedList class, but LinkedList seems to be getting treated like an abstract class and so the compiler doesn't seem to allow me to create a LinkedList object in my main function: main.cpp #include <...
Your IList is an abstract class with six pure virtual member functions. In order to create the instance of the derived one (i.e. LinkedList) you need to implement those functions inside the child as well. class LinkedList : public IList { // ..... other members public: // ..... other members virtual int ge...
69,655,949
69,660,821
Load images in QLabel
How to show more number(folder) of images in Qlabel or QScrollArea? QImage image("E:/Raul/Images"); ui.label->setPixmap(QPixmap::fromImage(image)); Like this but i want more number images will load in one label.
Result: Code: #include <QApplication> #include <QLabel> #include <QLineEdit> #include <QPointer> #include <QPushButton> #include <QVBoxLayout> #include <QWizardPage> #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget widget; QVBoxLayout *layout=new QVBoxLayout(); ...
69,656,454
69,691,861
Check for end-of-list in boost::intrusive::list without container?
I'm getting started with Boost.Intrusive, specifically interested in the doubly-linked list (boost::intrusive::list). This would be trivial to do in a "hand-rolled" linked list, but so far I can't find a Boost equivalent: Given a node that belongs to a list, how do I check to see if it represents the end of the list, w...
After some more research and thought, it seems that there is no way to do what I want with the standard boost::intrusive::list functionality. The list provided is, in fact, a circular linked list, not a linear one. So, there is no "null pointer" at the end. The implementation seems to follow a similar design to the Lin...
69,656,682
69,658,539
Using ESP_NOW with loop and delays
I'm trying to receive a data from one esp32 to another. I'm also doing some looping with delays for reading a sensor data and switch on/off relay cooling. This device also use ESPAsyncWebServer as API server (not included in code for the size). I'm receiving the data from one eps32 in POST request to API right now. I w...
I assume you're trying to send your sensor data from this device to another one while more or less accurately maintaining the 5-second sampling interval. You can create a simple asynchronous architecture yourself using 2 threads. The existing thread (created by Arduino) runs your current loop() which reads the sensor e...
69,657,686
69,658,058
Running thread periodically every 20 ms fails
currently i am programming for an embedded application which reads values from sensors periodically. I want them to be read, every 20 ms. Im using this tutorial struct periodic_info { int sig; sigset_t alarm_sig; }; static int make_periodic(int unsigned period, struct periodic_info *info) { static int next...
To be more accurate, don't take time twice on each iteration, keep the last value, like this: static void *thread_1(void *arg) { struct periodic_info info; printf("Thread 1 period 10ms\n"); make_periodic(20000, &info); auto start = std::chrono::high_resolution_clock::now(); while (1) { wait...
69,657,816
69,658,099
C++ difference between passing argument from a function call or passing argument from variable
Whats the difference between this: function1(function2()); And this: var1 = function2(); function1(var1); In terms of efficiency or whatever, what is the best option?
Before C++11 there is no big difference. Since move semantics were introduced the difference can be substantial. For example when a function needs to make a copy of its parameter it can have two overloads: one that actually does make a copy and another one that can move when the parameter is a temporary: #include <iost...
69,658,500
69,663,906
Using destructor to finish a task
I am currently experimenting with the following approach to finalize processing some data (pseudo-code). void run_processing(container datas) { // runs some conversion on data and sends it somewhere. } struct process_item { container datas; process_item(const char* data) { datas.add(data); ...
A problem with your strategy is that at destruction time, you have no (safe) ability to Throw an exception to report an error, or Return a result Throwing exceptions from destructor is a really, really bad idea, because destructors are run during stack unwinding if someone else throws an exception, and if you throw...
69,658,562
69,684,417
What algorithm meets the complexity requirements of the C++ `std::stable_sort`?
The docs from www.cppreference.com says that the complexity of std::stable_sort() is O(n * log(n)^2) [...]. If additional memory is available, then the complexity is O(n * log(n)). What algorithm would meet this requirement, and how much is the specified "additional memory"?
According to the commenters on the question and some further reading, the complexity is specified as such because there is no trivial stable in-place O(nlogn) sorting algorithm. With some further inspection on the source code, the implementation of libc++ and libstdc++ are similar, both are a merge sort where the in-pl...
69,659,009
69,660,162
Storing an variant of references for a view type in C++
I have an environment where I have no C++17 (C++14 ATM) features nor boost. Currently I have a class responsible for sending messages between services in our domain, this class uses multiple types of addressing (both types are non trivial) and one of them can be converted to other (lets say A can be converted to B). Cl...
There are lots of boilerplate missing, but PoC might be sth like this: #include <utility> #include <cassert> #include <iostream> struct A {}; struct B {}; struct EitherRef : private std::pair<A*, B*> { EitherRef(A& a) : std::pair<A*, B*>(std::addressof(a), nullptr){}; EitherRef(B& b) : std::pair<A*, B...
69,659,326
69,677,144
initialize a vector by a pointer of a CLASS
I am trying to initialize a vector of pointers of a class UNITCallback. Here is the code: file vector.h #include <memory> #include <unistd.h> class UNITEvent_Loop; class UNITCallback { public: UNITCallback(); virtual ~UNITCallback(); virtual const fd_set & FdSet() = 0; virtual void ...
I found the solution, I did a casting to (UNITCallback*) and it worked like a charm. here is the code: #include <iostream> #include <vector> #include <algorithm> #include"vector.h" struct UNITEvent_LoopImpl { UNITEvent_LoopImpl() : stopLoop(false), callBacks(1024,(UNITCallback*)0),//(FD_SETSIZ...
69,659,434
69,700,603
Template argument deduction when mixing variadic template with C-style variadic function
Inspired by this answer, I produced this code whose output depends on the compiler: template <typename... Args> constexpr auto foo(Args&& ...args, ...) noexcept { return sizeof...(args); } constexpr auto bar() noexcept { return (&foo<int>)(1, 2); } If compiled with GCC 11, bar calls foo<int> and returns 1, wh...
Edit: after the question was edited, it now comprises two orthogonal sub-questions, which I've handled separately. Given foo<int>(1, 2), should the parameter pack be deduced to cover all args? Yes. The parameter pack does occur at the end of the parameter-declaration-list, which is the criterion for whether it's non-de...
69,660,033
73,834,148
Is it possible to only link a project without compiling when using visual studio 2019?
In my project, there is a common header file shared by many source files. Usually, a modification of the header only affects several source files. I want to recompile those files manually and then let vs to link the project.
Sure, compile your C++ files only (ctrl-F7). Then link the project (right click project, then "Project only" -> Link), then run. In Options => Build And Run, make sure you specify "Prompt to build" when projects are out of date, and then choose to run instead of build. Good luck!
69,660,173
69,660,525
Return iterator for c type arrays?
In the MRE https://godbolt.org/z/jdjPzdGeo, is there a way to return an iterator for c type arrays in Func like what you see with std::array in Func2 and Func3? IDK what the return type would be. Also, is there a way to make Func constexpr like in Func2? Edit: Add the code here #include <array> std::pair<int*, std::si...
Return iterator for c type arrays? IDK what the return type would be. The iterator type for arrays is a pointer. for example, if you have an array of int, then the iterator type for the array is int*. and am expecting the return type to be an iterator of some sort. int* is an iterator. int* works for std::begin bu...
69,660,858
69,661,903
QString Resets after appending 10 characters
I just started QT Language. A strange error occurred when I tried appending a character 10 times to it. It resets and starts over. Does anyone know a solution? #include "mainwindow.h" #include "ui_mainwindow.h" #include<string> #include<iostream> // First Number / Second Number double num1...
A 32-bit integer value can have a maximum value of 2^31 - 1, or 2147483647, which happens to be 10 digits long. So an 11 digit number would fail when calling toInt(). QString s = "12345678901" qDebug() << s.toInt(); // prints '0'
69,660,887
69,667,881
UWP TabView change tab programatically
How can I change TabView's tab programatically? For example user have 2'nd tab opened and I want to change tab to the first one.
In C++ you have to do it as following: int index = 1; if (tabcontrol->TabItems->Size > index) { tabcontrol->SelectedIndex = index; }
69,661,158
69,661,460
Define a macro which defines a pow function only in the case where the exponent is an integer
Following a profiling of my C++ code, it appears that the pow function is used a lot. Some of my pow functions have an integer exponent and another non-integer exponent. I am only interested for the ones with integer exponent. To gain in performance, I am looking a way to define a macro like this: #define pow(x,n) ({\ ...
If you only need to switch between floating point types or not you can use templates instead of macros. #include <cassert> #include <cmath> #include <type_traits> namespace my_math { template<typename type_t> inline double pow(const double x, type_t n) { // this is compile time checking of types ...
69,661,240
69,661,551
Can Someone help me point out where my code is going wrong with the output?
#include <iostream> #include <vector> using namespace std; /* Sample Input: 2 2 ---------> Number of Arrays, Number of commands 3 1 5 4 -----> length of array, elements to add 5 1 2 8 9 3 -> length of array, elements to add 0 1 ---------> Command 1, row and column (first element of main vector, second element) 1 3...
You are missing a vector.clear() statement in your for loop that inserts values into the sub_vectors. // now take n vectors input : for(int x = 0; x < n; x++) { //taking input length cin >> length_of_sub_vector; for(;length_of_sub_vector > 0; length_of_sub_vector--) { cin >> input_element; ...
69,662,180
69,663,769
fgets not able to read from pipe twice on Ubuntu 20.04
I have the following code that used to work on Ubuntu 18.04. Now, I compiled and run it in Ubuntu 20.04, and, for some reason, the code stop working. The code is meant to read from a named pipe. To test it, I create the pipe with mkfifo /tmp/pipe and then I write into the pipe with echo "message" >> /tmp/pipe. The firs...
if( fgets (buf, BUFSIZ, result_pipe_stream) != NULL ) --> Once fgets() returns NULL due to end-of-file, it will continue to return NULL on subsequent calls without reading unless the end-of-file indicator for result_pipe_stream is cleared - like with clearerr(). Codes gets stuck in an infinite loop, never reading any...
69,662,346
69,757,714
CMake, JNI boost read json file - Android
What is the proper way to open a file with boost::property_tree::json_parser::read_json Current tree: boost::property_tree::ptree config; boost::property_tree::json_parser::read_json("conf/file.json", config); But I get the error that it cannot find the file terminating with uncaught exception of type boost::wrapexc...
I used this code to get it working, basically you copy the file from Android raw dir to some location on the device that the C++ JNI code can see. MainActivity code: private static final String RES_RAW_CONFIG_PATH_ENV_VAR = "RES_RAW_CONFIG_PATH"; private static final String RES_RAW_CONFIG_FILE_NAME = "res_raw_config.js...
69,662,387
69,662,475
How can I fix the missing template arguments before '(' token problem here?
I am getting the problem on line 15 and 20 where i am trying to pushback elements in to the pair vector #include <iostream> #include <vector> #include <utility> using namespace std; int main() { int x, y, a, b, c, d, j, m, v; vector<pair<int, int> > ladder; cin >> x >> y; for (int i = 0; i < x; i++) ...
Your issue is on these two lines: ladder.push_back(pair(a, b)); ladder.push_back(pair(c, d)); You need to specify what types of pairs these are: ladder.push_back(pair<int, int>(a, b)); ladder.push_back(pair<int, int>(c, d));
69,662,832
69,663,400
How to add void/null as default argument to a function/lambda pointer, in C++?
Present signature is template<class TypeData,typename TypeFunc> bool isPrime(const TypeData& n,TypeFunc fSqrt,bool debug = false) and this works perfectly with std::cout<<(isPrime(n,fSqrt)?"Positive":"Negative")<<'\n'; But, my intension is something like template<class TypeData,typename TypeFunc> bool isPrime(const T...
Overloading actually is an option, you can let one overload call the other one: template<class TypeData, typename TypeFunc> bool isPrime(const TypeData& n, TypeFunc fSqrt, bool debug = false); template<class TypeData> bool isPrime(const TypeData& n, bool debug = false) { using std::sqrt; if constexpr (std::is_...