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
72,949,462
72,995,909
How to dynamically BLE advertise on ESP32 and reflect on flutter app
My ESP32-based custom-PCB BLE peripheral is advertising LiFP batteries dynamic physical values, such as current or SoC (State of Charge). Basically, the code is as follows: /// Returns the manufacturer data as a String void Ble :: setAdvertisingManufacturerData(BLEAdvertisementData *advertisementData) { const floa...
I finally did that, that makes my advertising being dynamic. I removed the setScanResponseData()and replaced by another call of setAdvertisementData() as I do in advertise(). But I still don't get what setScanResponseData() is for. void Ble :: loop() { // == Dynamically advertise static unsigned lastAdvertise...
72,949,593
72,950,434
Float to Double adding many 0s at the end of the new double number during conversion
I'm facing a little problem on a personal project: When I'm converting a float number to a double to make operations (+-*/) easy, it adds a lot of 0s behind the default float number. For example: float number = -4.1112 -> double number = -4.1112000000000002 I convert the float to a double with the standard function std...
The problem you are having is completely different. All your checks are wrong. Think about it: if a variable is of type, say, int32_t, its value is necessarily between the minimum and maximum possible values that can be represented by an int32_t, by definition. Let's simplify: it's like having a single-digit number, an...
72,949,669
72,950,296
Is it possible to modify type definitions at runtime?
Is it possible to modify type definitions at runtime? For example if you were to define a class like this class Test { public: int x; int y; }; could I remove the x or y field from the class at runtime? Or could I add more fields to this like adding a z field? EDIT: This question is strictly out of cu...
No. It is definitely impossible. For example, we are updating the field x in the structure Test and we must know the size at the compile time because of operations on machine code level performs on data offsets class Test { public: int x; int y; }; int main(){ Test t; t.x = 10; return t.x...
72,950,362
72,951,084
Inheriting constructors with initializer_list from multiple base classes deletes constructor
Apparently my compiler deletes my constructor for reasons I can't understand. Compare this: This is working (Compiler Explorer): using val = std::variant<std::monostate, int, bool>; struct keyval { keyval(std::string, int) { } }; struct base_A { base_A(std::initializer_list<val>) { } }; str...
As per cppref:, If overload resolution selects one of the inherited constructors when initializing an object of such derived class, then the Base subobject from which the constructor was inherited is initialized using the inherited constructor, and all other bases and members of Derived are initialized as if by the de...
72,950,584
72,950,754
C++ lambda capture list by value or by reference doesn't give me different results
I am having the below code : std::vector<std::function<void()>> functors; class Bar { public : Bar(const int x, const int y):d_x(x),d_y(y){} ~Bar(){ cout << "Destructing Bar" << endl; } void addToQueue() { const auto job = [=](){ ...
This kind of confusion iss probably one of the reasons why C++20 deprecated the implicit capture of this with [=]. You can still capture [this], in which case you have the usual lifetime issues with an unmanaged pointer. You can capture [*this] (since C+=17), which will capture a copy of *this so you don't have lifetim...
72,951,653
72,962,469
Using conan packages in CMake: Library 'mylibrary.a' not found in package
I am using cmake to build my project. I have a library, mylibrary, which is a dependency of my project. mylibrary is packaged with conan. I use the conan CMakeDeps and CMakeToolchain Generators when packaging mylibrary. This is the package_info function of mylibrary's conanfile: def package_info(self): sel...
So, I did it. I don't understand why or how, but to solve my problem, I had to change this line: self.cpp_info.components["libmylibrary"].libs = ["mylibrary.a"] to this: self.cpp_info.components["libmylibrary"].libs = ["mylibrary"]
72,951,952
72,959,254
Boost serialization base class without default constructor
How to serialize/deserialize derived class inheriting base class without default constructor? Please offer serializing boost functions for the following classes struct Base { Base(int b) : b(b) {} const int b; } struct Derived : public Base { Derived(float d, int b) : Base(b), d(d) {} const float d; }
Your use-case straddles two of the "special considerations" documented by Boost Serialization: Non-default constructors Pointers to objects of derived classes Note that I'm going to assume you want dynamic polymorphism, and to get this you need at least a virtual destructor. If you don't you will end up with Undefine...
72,951,953
73,184,794
How to compute floating-point remainders with CGAL's exact number types?
I'm trying to get familiar with CGAL's exact number types and in the process, I'm trying to implement a function to compute the floating-point remainder of the division of two exact numbers (like std::fmod()). However, I'm wondering how to do any arithmetic with exact numbers outside of the trivial operator+, -, *, /. ...
Your code compiles for me, but it prints 1.66667 while I expect you wanted 1? I do get a similar error if I define CGAL_USE_GMPXX=1 or CGAL_DO_NOT_USE_BOOST_MP=1, so the error depends on the type used internally for exact rationals. There is also a function integral_division. The simplest way I can think of it to compu...
72,953,293
72,953,684
C++ Polymorphic Array Syntax or Polymorphic Vector Syntax
So I have the main parent class called item and that class has 2 child classes called book and periodical. The ideas behind what I am trying to do is have a polymorphic array or a polymorphic vector that would be able to do something like this: Now the example is in C# (but I want to do it in C++) item [ ] items = ...
Here is an example (if you have questions let me know): #include <iostream> #include <memory> #include <vector> class Item { public: virtual ~Item() = default; // base classes with virtual methods must have a virtual destructor virtual void read() = 0; }; class Book final : public Item { public: void ...
72,953,676
72,953,744
How to use a variable inside a _T wrapper ? (MFC Dialog app C++)
I want to generate 17 service names in the List Control. How can i use a formatted string variable inside a _T wrapper ? // TODO: Add extra initialization here #define MAX_VALUE 17 int numberOfService = 0; CString StringServiceName; StringServiceName.Format(_T("Sense Counter %d"), numberOfService); ...
You can't - _T is just a macro to generate narrow or wide string constants, depending on whether you're compiling for Unicode or not. I'm not over-familiar with CString, but perhaps you meant this: for (numberOfService; numberOfService < MAX_VALUE; numberOfService++) { StringServiceName.Format(_T("Sense Counter %d"...
72,953,783
72,953,912
How to efficiently initialize a std::variant data member in a class template
Consider the following class template, that can hold either a value of type T or an instance of some ErrorInfo class, using a std::variant data member: template <typename T> class ValueOrError { private: std::variant<T, ErrorInfo> m_var; }; How can I efficiently initialize the variant T alternative? I can initia...
A C++20 version using perfect forwarding: #include <concepts> // std::constructible_from template <class T> class ValueOrError { public: explicit ValueOrError(const ErrorInfo& error) : m_var{error} {} template<class... Args> requires std::constructible_from<T, Args...> explicit ValueOrError(Args&&... ...
72,953,855
72,954,448
Are struct scalar members zero-initialized when using value-initialization on a struct with a default non-trivial-constructor
If I have the following struct struct test { char *x; std::string y; }; And I initialize with test *t = new test(); That should value-initialize the object and do the following based on the standard: if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the...
The warning is not correct for modern C++(including C++17) as explained below. should I be able to reliably assume that after doing test *t = new test(); if I immediately check t->x == nullptr, that should be true because char *x (a pointer / scalar type) should get zero-initialized during value-initialization of test...
72,954,344
72,955,355
Is there a way to teach gtest to print user-defined types using libfmt's formatter?
I'm wondering if there is a way to make gtest understand a user-defined types libfmt's formatter, for the means of printing a readable error output? I know how I can teach gtest to understand user-defined types via adding the stream insertion operator operator<< for this very user-defined type, e.g. std::ostream& opera...
To avoid problems caused by ambiguity of PrintTo or operator<< namespace is needed. Here is some demo when namespaces is used: #include <fmt/format.h> #include <gmock/gmock.h> #include <gtest/gtest.h> namespace me { struct Foo { int x = 0; double y = 0; }; bool operator==(const Foo& a, const Foo& b) { ret...
72,954,488
72,954,672
gMock Visual Studio test crashes when using EXPECT_CALL
When running my test from the Test Explorer in Visual Studio 2022 [17.2.0], testhost.exe crashes when my unit test has a gMock EXPECT_CALL call in it. What am I doing wrong? Minimal code: #include <CppUnitTest.h> #include <CppUnitTestAssert.h> #include <gmock/gmock.h> #include <gtest/gtest.h> using namespace Microsof...
You mix the very different test frameworks. The more important thing is that you do not initialize Google test framework. TEST_CLASS, TEST_METHOD are of another test framework, do not perform required pre and post stuff, Google mock is not supposed to work there. Choose one framework and use it. #include <gmock/gmock...
72,955,067
72,955,535
Cleaner way to specify type to get from a std::variant?
I've got code that can be simplified to std::variant<float, int> v[2] = foo(); int a = std::get<decltype(a)>(v[0]); float b = std::get<decltype(b)>(v[1]); Obviously this can go throw if foo() returns the wrong variants, but that's not my problem here. (The real code has a catch). My problem is that the decltype(a) vio...
You could wrap your call to get in a template that implicitly converts to the target type. template<typename... Ts> struct variant_unwrapper { std::variant<Ts...> & var; template <typename T> operator T() { return std::get<T>(var); } }; See it on coliru
72,955,386
72,956,032
Techniques for managing application shutdown in Win32
We have a Win32 application written using WTL (Windows Template Library), and I'm looking for patterns for exiting the application. The issue that I'm dealing with is that some of the views in the application contain resources which may take some time (measured in 1 to 2 seconds), to destroy (i.e. waiting for a thread ...
The question is, how would you handle a case where you want to keep the message loop running, while shutting down the application. I would have the WM_CLOSE handler display a "Please wait" message to the user, and then asynchronously initiate whatever shutdown logic is needed. Do not call DefWindowProc() or DestroyW...
72,955,625
72,955,792
objdump -t columns meaning
[ 4](sec 3)(fl 0x00)(ty 0)(scl 3) (nx 1) 0x00000000 .bss [ 6](sec 1)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x00000000 fred the number inside the square brackets is the number of the entry in the symbol table, the sec number is the section number, the fl value are the symbol's flag bits, the ty number is the symbol...
You talk about nm, thus you talk about ELF files. Continue reading the manual: The other common output format, usually seen with ELF based files, looks like this: 00000000 l d .bss 00000000 .bss 00000000 g .text 00000000 fred The symbol is a local (l), global (g), unique global (u), neither global nor lo...
72,956,610
72,958,056
What is system:80 error showing while trying to copy file content?
I have this code: #include <filesystem> #include <fstream> using namespace std::filesystem; int main() { std::error_code ec; bool hi = copy_file("hi.txt" , "sth.txt",ec); std::cout << ec; return 0; } When I compile and run this, it throws system:80, which according to System Error Codes (0-499) is ER...
The default behavior of std::filesystem::copy_file() is to fail with an error if the destination file already exists. To avoid that, you need to call the overloaded version of the function which takes a std::filesystem::copy_options parameter so you can tell it what to do with the existing destination file, eg: bool ...
72,956,706
72,957,260
How to read this C++ function
Maybe someone here could help me to understand more about C++ While reading about Unreal Engine 4, I came across this function which is used as the following class ClassSample1 { public: Babu* pBabu; //0x022C }; void SetFuncton(Babu* param1, bool param2) { (*(int(__fastcall**)(Babu*, bool))(*(DWORD64*)param1 +...
What I want to know. What will this function produce? That's the fun part, from what you've shown, nobody knows! What datatype will this function produce? I guess the answer is "nothing", SetFunction() returns void, but this appears to be calling some kind of class parameter setter so it will probably have side...
72,957,006
72,957,990
Mapping a type to a function of that type in c++
Let's suppose I have a character that can have 1 out of 3 states at a time(crouching, jumping and walking). For each of the 3 states I have a function of type void() that does whatever they are assigned to. I also have an enum that stores the different states and a number for each state. class Player { private: enum...
You need to do what the compiler tells you - use the & operator to get a pointer to a member method. You will also have to specify the class the methods belong to, eg: class Player { private: std::unordered_map<State, void(Player::*)()> stateToFunc; void playerJump(){ /* code here */ }; void playerCrouch(){ /...
72,957,178
72,959,794
C++ intel_driver.hpp C1083 Cannot open include file: 'atlstr.h':No such file or directory (compiling source file main.cpp) I can't build the release
I would like to build this kdmapper project but unfortunately I can't because with 'altstr.h' has an issue in the attachment can you see the details: Kdmapper compiling and building issues Has anybody an idea how to resolve this issue? Thanks forward!
Just install the MFC package in Visual Studio. https://learn.microsoft.com/en-us/cpp/mfc/mfc-and-atl?view=msvc-170
72,957,382
72,968,754
Cannot create org.webrtc.voiceengine.WebRtcAudioManager on Android
I have a functional implementation of native (C++) WebRTC in Windows, which I'm trying to get working on every other platform now. Currently, I'm attacking Android. When I call webrtc::CreatePeerConnectionFactory, it cannot create the java class org.webrtc.voiceengine.WebRtcAudioManager. I get the following result (fo...
Fixed! This is what I was missing: I was calling webrtc::JVM::Initialize prior to webrtc::CreatePeerConnectionFactory (which is one of many Droid specific requirements they don't bother mention in any docs...). But, I missed the fact there is an overload which takes the Droid app context (i.e. static void Initialize(J...
72,957,449
72,957,484
Difference between subscript [] operator and push_back method for inserting charachter in a string in C++
I am stuck on this stupid doubt and can't understand which part have I understood wrong. I am trying to fill an empty string and I thought of doing it using the subscipt [] operator but found that although loop runs perfectly but the final string is still empty with size zero. However push_back runs perfectly fine. I c...
As simple as it is for std::vector, std::string doesn't have bounds check when using subscript operator. When creating empty string, you have a container of zero length, thus when you assign values by index, the values are assigned to memory out of the collection's bounds
72,957,592
72,958,310
Exception: STATUS_ACCESS_VIOLATION when trying to read value of pointer from another program
I am practicing the use of ReadProcessMemory and one task I have is to read the value of a pointer, and then read the value of the address stored in that pointer. I can get up to the part of reading the value of the pointer, but every time I try to access the value stored in the address in that pointer, I get Exception...
You can't just retrieve a pointer with ReadProcessMemory() and then dereference it normally, like you would with pointers in your own process. You have to use ReadProcessMemory() for each value you want to read from the remote process. 0x00F3F990 is the address of ptr2int in the remote process. You are reading the val...
72,957,821
72,958,071
Cascade variadic template template parameters
How can I cascade variadic types? I.e.: template <typename... T> using Cascade = ???; // T1<T2<T3<...>>> Example: using Vector2D = Cascade<std::vector, std::vector, double>; static_assert(std::is_same_v<Vector2D, std::vector<std::vector<double>>>);
You cannot have CascadeRight. T1 is not a typename, it is a template, and so are most of the others, but the last one is a typename. You cannot have different parameter kinds (both types and templates) in the same parameter pack. You also cannot have anything after a parameter pack. You can have CascadeLeft like this: ...
72,958,194
72,958,602
What is the relationship between Boost::Asio and C++20 coroutines?
I started trying to learn Boost::Asio by reading the documentation and example code. I found things difficult to understand, particularly because the model seemed similar to coroutines. I then decided to learn about coroutines, starting with this cppcon talk. In the linked talk, the following line was given in an exam...
Q. What is the relationship between Boost::Asio and coroutines? C++20 coroutines are one of the completion token mechanisms provided with any Asio compliant async API Q. Do coroutines replace parts of Boost::Asio? Not 1 on 1. In practice people may feel a lot less need to write asio::spawn (stackful) coroutines, be...
72,958,305
72,958,636
Google test error: '*' can only follow a repeatable token
Trying to create some unit tests with EXPECT_EXIT where the error message contains a '*'. The test fails but not with expected error. What am I missing here? Here a very simple example to reproduce the issue: void test_Death() { std::cerr << "*Error\n"; exit(EXIT_FAILURE); } TEST(ErrorWithStar, Star) { EXP...
The character * is reserved by the regular expression grammar to indicate matching zero or more of the previous tokens or groups. Some simple examples: .* matches zero or more of any character a* matches zero or more of the character a [A-F]* matches zero or more of the characters A through to F The error is occurrin...
72,958,341
73,095,301
Why is CMake ignoring the compiler settings via command line?
I am trying to build MAGMA from Windows 10 but it's not working. I downloaded the project MAGMA from here http://icl.utk.edu/projectsfiles/magma/downloads/magma-2.6.2.tar.gz. I downloaded and installed Intel's One API compilers and MKL. I'm taking the following step as part of my command line setup: > call "C:\Program ...
I'm guessing you're running a version of CMake > 3.0? CMake doesn't necessarily honor the environment paths correctly as it is doing its lookups. I tried installing 2.8.12.2 (the version recommended by the author) and it seems to build fine. I also tried with the latest 3.x version (3.22.x) and I see the same error as...
72,959,009
72,959,050
Pointing on vector elements
I've got a vector of objects (apples) and I need a pointer to jump through every element, to print "size" value on every object in "apples". I tried vector::iterator, pointing whole vector but I still cannot get correct solution #include <iostream> #include <vector> class Apple{ public: int size; Apple(int siz...
To iterate through any T[] array using a pointer, you need to use a T* pointer, and you need to point it initially at the address of the 1st element, not the value of the element. Your vector's element type is T = Apple*, not T = Apple, so you need to use an Apple** pointer rather than an Apple* pointer, eg: #include <...
72,959,496
72,959,775
GLFW undecorated window on MacOS after turning on and off again, gains black outline
So, there is a window, that is being created with these hints: glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE); glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); glfwWindowHint(GLFW_TRANS...
I don't think this is a GLFW side issue or an issue in your code, I think this might be an issue with macOS's Quartz Compositor. QC is responsible for drawing all your windows to the screen just like Windows' DWM. Or if the window covers the full screen (without "actually" being full screen, just a large window), you c...
72,959,582
72,968,820
Update console output while slowing down program as little as possible
I have a single threaded program that does some operations on a large file (~16GB) in a loop, and has a variable count that increments on each loop, I want to be able to see what the count is at by outputting to console every so often, but I dont want it to significantly slow down my program, so I wanted to know if it ...
count % 1'000'000 is a slow operation, even though the compiler optimizes that to multiplication by an inverse. If you use a power of 2 on the other hand this operation becomes much simpler. For example here is x % n == 0 for 1'000'000 and 1 << 20 == 1'048'576 with int. mod_1_000_000(int): imul edi, edi, 175...
72,959,590
72,961,938
How to save bounded-length strings as quickly as possible for a timing mechanism?
I have a thin wrapper around rdtsc that I use as a timer. It supports "stepping" and all timestamps are saved in a std::array (you specify when creating the timer how many steps you will make). That way, you can do something like, void funcToTime() { timer<2> t; ... t.start(); ... t.step(); ... ...
A string literal evaluates to the address at which that literal is stored in memory. As such, there's no need to copy the string in response to each step call. template <class N> class Timer { struct TimeRecord { unsigned long long timestamp; char const *tag; }; std::array<TimeRecord, N> ...
72,959,945
72,960,035
How to write an overload function for std::array that calls a variadic function?
I have the following variadic function: template <typename... Args> CustomType<Args...> method(const Args& args...); which works fine when I just do e.g. method(1.0f, 2.0f, 3.0f); However I also want to write an overload for std::array<T, N>: template <typename T, std::size_t N> auto method(const std::array<T, N>& ar...
You can wrap it in a lambda and let the compiler deduce the type for you template <typename T, std::size_t N> auto method(const std::array<T, N>& arr) { return methodArr(arr, [](const auto&... args) { return method(args...); }); } Demo In C++17, methodApply can be replaced with std::apply template <typename T, std:...
72,960,867
72,960,963
Why is string::resize and string::substr O(1)
I am working on a coding problem in which I have to delete all occurrences of a substring T in a string S (keeping in mind that removing one occurrence of T in S may generate a new occurrence of T), and then to return the resulting string S after all deletions. The size of both S and T can be up to 10^6. For example, i...
string::resize isn't always linear. If you're expanding a string, it's linear on the number of characters copied, which is potentially the total number in the resulting string (but could be less, if the string already has enough space for the character(s) you add, so it only has to write the new characters). Using resi...
72,961,236
72,961,338
Fixing error: *** No rule to make target '/usr/lib/x86_64-linux-gnu/libdl.so'
I have recently upgraded my OS (to PopOS! 22.04) and now a bunch of builds in my cmake workflow aren't compiling, halting at this particular error at the linking stage: *** No rule to make target '/usr/lib/x86_64-linux-gnu/libdl.so' This file now no longer exists. There is however a libdl.so.2. Running apt-file searc...
Jammy's GNU C Libarry version is 2.35. The dl library is now part of the C standard library. The release notes, tells that, starting from version 2.34, all functionality formerly implemented in the libraries libpthread, libdl, libutil, libanl has been integrated into libc. New applications do not need to link with -l...
72,962,924
72,963,089
How to extract relevant info from the body of http response with Arduino?
I am currently doing a project with Arduino MKR WiFi 1010 and I send a GET request to the server and it sends me back a response contains "clientId". The only info I desire is this client ID. But I am pretty struggling with obtaining it. The complete response is as following: HTTP/1.1 200 OK Date: Wed, 13 Jul 2022 07:2...
If I understand it well, you retrieve it in a String. So the easiest way to find your client ID is to find the String "clientID" with a provided Arduino's function indexOf, this will give you the index in the String. So on and on you retrieve the string between "clientId":" to ", mystring.indexOf(val, from) start = in...
72,963,090
72,963,126
C++ non-generic class in template
I would like to know how to make a template with an own class: #include <iostream> using namespace std; template<C cc> void A() { cout << cc.l << endl; } int main() { C cc; A<cc>(); } class C { public: int l = 10; }; But it doesn't work, so how to use that class, like a non-generic class parameter, ...
You can do it as shown below with C++20(&onwards): //moved definition of C before defining function template `A` struct C { int l = 10; }; template<C cc> void A() { cout << cc.l << endl; } int main() { //--vvvvvvvvv--------->constexpr added here constexpr C cc; A<cc>(); } Working demo Two changes ha...
72,963,463
72,969,788
Calling copy and assignment operators from base class to create inherited class instances in C++
I have te following classes (e.g.) : class A { public: A(void) : i(0) {} A(int val) : i(val) {} A(const A& other) : i(other.i) {} A& operator=(const A& other) { i = other.i; return *this; } int i; }; class B : public A { public: B(void) : A(), j(0) {}; B(const B& other) ...
Yes, you would have to define something like that. B(const A& other); This would allow constructing B out of A. This would also allow assigning A to B by way of implicitly converting A to B and then assigning. So that alone should suffice. But you get an extra copy. B& operator=(const A& other); This makes assigning A...
72,963,630
73,000,332
Problem with receiving mails from the SENT folder
if ( IdIMAP1->SelectMailBox( "SENT" ) ) { TIdIMAP4SearchRec sr[1]; sr[0].SearchKey = skAll; IdIMAP1->UIDSearchMailBox( EXISTINGARRAY(sr) ); int ile = IdIMAP1->MailBox->SearchResult.Length; } Error: First chance exception at $757BF192. Exception class EIdReadLnMaxLineLengthExceeded with message ...
Error: First chance exception at $757BF192. Exception class EIdReadLnMaxLineLengthExceeded with message 'Max line length exceeded.'. ... What does this error mean and how can I fix it? It means TIdIMAP4 called the IOHandler.ReadLn() method and received more than 16K worth of data that had no line breaks in it. The...
72,963,777
72,964,058
Is casting to (void**) well-defined?
Suppose A is a struct and I have a function to allocate memory f(size_t s, void **x) I call f to allocate memory as follows. struct A* p; f(sizeof(struct A), (void**)&p); I wonder if (void**)&p here is a well-defined casting. I know that in C, it is well-defined to cast a pointer to void* and vice versa. However, I a...
The conversion is not defined by the C standard, and, even if it were, code in f that assigned to it via the void ** type would not be defined by the C standard. C 2018 6.3.2.3 7 says a pointer to an object type may be converted to a pointer to a different object type. This covers (void **) &p, since &p is a pointer to...
72,964,318
73,041,001
Wrapping a C++ library using msl-loadlib in python
I am currently writing a wrapper for a C++ library. The library is a 32-bits dll file and I'm using 64-bits so I'm using msl-loadlib. I have a problem wrapping a function that has pointer parameters. Here is the header of the function in C++ int CUSB::GetMeasurement(int Group, int StartPoint, int* NumberOfPoints, doubl...
I'm ignoring msl-loadlib as extraneous to the problem of calling ctypes correctly. Here's an example of calling the function shown. The YData needs to be an array of 3 double* and then each of those pointers needs to be initialized with the next dimension of the array. Note this parallels the C++ example of calling t...
72,964,591
72,965,299
C++: Deep Copy Diamond Pointer Structure
In my simulation software, I generate objects with pybind11. So all objects are stored in std::shared_ptr with a not known structure at compile time. For parallelisation of my simulation I need to run the same configuration with different seeds. I want to implement the duplication of these objects in one call on the C+...
You can use std::shared_ptr<void> to type-erase all your shared pointers, using std::static_pointer_cast to go to and from your actual types. using Seen = std::set<std::shared_ptr<void>>; template <typename T> std::shared_ptr<T> deep_copy(std::shared_ptr<T> source, Seen & seen) { if (auto it = seen.find(std::stati...
72,965,037
72,981,545
How To Package Binary Projects Using Conan?
The Problem: The package's consumer couldn't load the package's binary's shared libraries. find_package(MyThirdParty REQUIRED) # MyThirdParty is installed using Conan find_program(binary_paty MyThirdParty REQUIRED) execute_process(COMMAND ${binary_path} COMMAND_ERROR_IS_FATAL ANY) The execute_process command will fail...
On Linux we could use patchelf and change the binary RPATH during the packaging state: def package(self): cmake = CMake(self); cmake.install(); self.run("patchelf --set-rpath '$ORIGIN/../lib' " + self.package_folder + "/bin/MyThirdParty"); And for Windows just put the shared libraries files besides the binar...
72,965,227
72,970,337
How can I converting multi page PDF file to many images .jpeg with Vips in C++?
I'am trying using vips in c++ to read a .PDF and convert to .jpeg files. The problem is that the code save all the pages in a single file .jpeg. How can i save in many .jpeg files? My Code VOption *voptions = new VOption(); voptions->set("dpi",150); voptions->set("page", 0); voptions->set("n", -1); ...
I found a way to solve this using crop. VImage in = VImage().pdfload("/Users/MyUser/Desktop/PDF_Reader/files/TEST_DOC_READER.pdf", voptions); pages = in.get_int("n-pages"); h = in.height()/pages; for(int i=0; i<pages; i++){ in.crop(0,i*h, in.width(), h).jpegsave((outdir+to_string(i)+format).c_s...
72,965,466
72,966,229
Does referencing a shared pointer in a lambda preserve object lifetime?
Basically the question from the title. Consider I have to use some asynchronous API, does a reference to the local scope shared ptr in lambda preserve it's lifetime? And is this a safe practice? class A { public: static void foo(); } A::foo() { std::shared_ptr<MyType> MyTypePtr = std::make_shared<MyType>(); ...
This lambda captures the shared_ptr by reference. That's what "&" means, in the capture list. It only captures a reference to the shared_ptr. When the function returns the shared_ptr gets destroyed, leaving the lambda holding a bag with a reference to a destroyed object. Any further usage of this object results in unde...
72,967,144
72,991,974
c++ get indices of duplicating rows in 2D array
The task is following: find indices of duplicating rows of 2D array. Rows considered to be duplicated if 2nd and 4th elements of one row are equal to 2nd and 4th elements of another row.The simplest way to do it is something like that: std::unordered_set<int> result; for (int i = 0; i < rows_count; ++i) { for (int...
You could take advantage of the properties of a `std::unordered_set. A small helper class will further ease up things. So, we can store in a class the 2nd and 4th value and use a comparision function to detect duplicates. The std::unordered_set has, besides the data type, 2 additional template parameters. A functor fo...
72,967,220
72,967,387
How to write a wrapper around a templated class that modifies the template parameters in C++?
We have a templated class A and derived classes A1 and A2: template<typename T> class A { }; template<typename T> class A1: public A<T>{ }; template<typename T> class A2: public A<T>{ }; I need a wrapper that accepts any class of type A*, ie any derived type of A, as a template parameter and modify its template para...
You do not need to explicitly state int as argument. The template and its argument can be dissected from a given instantiation by partial specialization (provided that all derived have same number of arguments). The fact that there is a base class A is actually not that relevant when the derived classes are templates t...
72,968,151
72,969,376
shared_ptr CUDA cudaStream_t
I am trying to make a CUDA stream instance automatically delete itself once all its usages have been removed and I was wondering if when calling cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), if it is created the object on the heap or not? (I am assuming it is but I am not sure). In the end I want to do som...
As mentioned in several comment above (including mine), your first attempt involves creating std::shared_ptrs managing dangling pointers. This is because these pointers are actually addresses of automatic variables created on the stack in the scope of the loop body (and therefore become dangling once the variables get ...
72,968,744
72,968,842
Using class alias for its constructor definition
This minimum reproducible piece of code class MyClass { public: explicit MyClass(); ~MyClass(); }; using MyClassAlias = MyClass; MyClassAlias::MyClassAlias() { } MyClassAlias::~MyClassAlias() { } int main() { MyClassAlias obj; return 0; } gives the error: a.cpp:11:1: error: ISO C++ forbid...
The "names" (although these are not names in the technical sense of the standard) of the constructor and destructor are MyClass and ~MyClass respectively. They are based on the injected class name. You need to use these two to define them or write any declaration for them. You cannot use an alias name for these. The sa...
72,970,796
72,971,329
C++ / WinAPI: How do I get a value from a function in the injected x64 DLL?
x86 way of doing this is easy and straightforward - through GetExitCodeThread. Unfortunately it's limited to returning 32 bit values. As I understand it WinAPI provides no 64 bit alternative. So the problem is - I have no trouble calling the injected function by finding its base address through CreateToolhelp32Snapshot...
I suggest that you use a shared memory region, have it open in both the injecting process and the injected DLL. When the injected library finishes you know that the memory should be ready. Doing this, you aren't limited to 4 or 8 bytes, you can make the region of whatever size is needed to return the collected data.
72,970,939
72,971,155
Why the object is not getting modified when passing the callable object with reference to async
Since we are passing the object by reference to std::async, it will call the operator () on same object, then why its member variable is not getting updated struct Y { int m_val; Y():m_val(0){} double operator()(double val) { m_val = val*val; return m_val; } }; int main() { Y y; ...
Before C++17, the evaluation of arguments to << was unsequenced. That means you have no guarantee that f.get() would be called before y.m_val's value is taken. As a consequence, your program has a potential data race, and therefore undefined behavior. Since C++17, the evaluation order is specified as left-to-right, and...
72,971,188
72,971,223
Why main loop stops at last iteration
my program should accept input from: 3 UUUDU DDD UU the output should be 302 but it stops at 0 int t; cin >> t; for(int i=0;i<t;i++){ string s; vector<int> n; int m; cin>>s; for(int j=0;j<s.length();j++){ if( s.at(j) =='U' ) { m++; } else { n.push_back(...
You mustn't read n[0] when n has no elements. To avoid the error, the part if(n.size()>0){ sort(n.begin(),n.end()); } cout<<n[0]<<endl; should be if(n.size()>0){ sort(n.begin(),n.end()); cout<<n[0]<<endl; } else { cout<<0<<endl; } Also there are other logical errors: The variable m is used without in...
72,971,696
72,971,740
iterating through an array to transfer its elements to a vector with certain conditions (c++)
I am a Grade 10 student taking a Computer Science course over the summer and I am having trouble with my homework question. The question asks to write code that will allow a user to enter 6 grades and sort the grades into two different vectors; one that stores passing grades and another that stores failing grades (>=60...
The vectors passingGrades and failingGrades have no elements, so any access to their "elements" are invalid. You can use std::vector::push_back() to add elements to a std::vector. Also note that the loop using y looks meaningless because the code inside the loop doesn't use y and executes break; in the first iteration....
72,972,139
72,976,471
Passing complex data structures between Fortran and C++
Background: I am tasked with a work project of creating interoperability between an existing large Fortran code basis and a modern C++ GUI using Qt. I am using Qt Creator 6.0.2 based on Qt 6.2.2 (MSVC 2019, 64 bit) and VS 2019 Pro with the Intel Fortran Compiler. I have been able to successfully pass basic data types a...
Unless your structure is bind(C), no exact correspondence between C(++) and Fortran can be guaranteed. The compilers can choose to use different paddings or similar. But you cannot make a bind(C) structure with allocatable components. All that is left are hacks. As a workaround you could make a proxy structure with typ...
72,972,898
72,973,086
How to Initialize a Mutex Inside a Struct?
I'm kind of new to multithreading, and this is a small piece of a very large homework for my operating systems class. Currently, I have a C++ struct as follows: struct arguments { std::string string1; std::string string2; pthread_mutex_t bsem; pthread_cond_t wait = PTHREAD_COND_INITIALIZER; pthread_...
You can't perform non-declarative statements inside of a struct declaration. What you can do is add a constructor (and destructor, in this case) that performs the extra statements you need, eg: struct arguments { std::string string1; std::string string2; pthread_mutex_t bsem; pthread_cond_t wait = PTHR...
72,973,635
72,973,874
How to properly check keys in a map c++
I have been using maps lately and wanted to know how to check for existing keys in a map. This is how I would add/update keys: map<int> my_map; my_map[key] = value; The [] operator adds a new key if one doesn't exists. If I were to check for a key like this, map<int> my_map; if(check_value == my_map[key]){....} Would...
In C++20, there is std::map::contains, which returns a bool. if ( my_map.contains(key) ) { ... } Before C++20, there is also std::map::count, which (unlike std::multimap::count) can only ever return 0 or 1. if ( my_map.count(key) ) { ... }
72,974,766
72,974,905
How to find middle of a button on screen
Ok I'm coding a button. I have done the box collision and all of the other stuff. The problem I'm having is putting text in the middle of the button. No matter what I try it doesn't work :/ . Please help I'm bad at math. x = 120, y = 120, w = 120, h = 50 Screen dimensions = 480, 240 Is there an equation for this? I tri...
You can compute the center-point of the button easily enough: const int buttonCenterX = x+(w/2); const int buttonCenterY = y+(h/2); ... for the next step you'll need to center the text around that point. If your GUI API doesn't provide a way to center the text for you, you can calculate the appropriate x/y position b...
72,974,836
72,974,882
How to convert an absolute path to a relative one?
Let's say I have a base path D:\files and an absolute path D:files\images\1.jpg. Is there a way to convert this absolute path into a relative one with respect to the base path?
Using std::filesystem::relative (C++17 needed) #include <filesystem> #include <iostream> int main() { std::cout << std::filesystem::relative("D:files/images/1.jpg", "D:files") << "\n"; std::cout << std::filesystem::relative("D:files\\images\\1.jpg", "D:files") << "\n"; } Output "images\\1.jpg" "images\\1.jpg"...
72,974,869
72,974,904
Correct syntax for operator >> overloading to members of nested class?
I have class Address nested in class Student, and I want to feed each input line into the class Student with operator>> overloading through istream. class Address { public: .... private: int house_no; string street; string city; string postcode }; class Student { public: .... friend istre...
The problem is not in the operator itself, but in the visibility of the members. You are using the Address class as a member of Student, but the Address::house_no member is not accessible from it (not only for the input operator). One solution (a simple but bad one) would be to open the members of Address: class Addres...
72,976,808
72,977,444
Multithread share 2 variable problem with nonlock
I have a question about multithread share variable problem. the two variable is like: { void* a; uint64_t b; } only one thread can modify the two variable, other thread will frequently read these two variable. I want to change a and b at one time, other thread will see the change together(see new value a and n...
You're looking for a SeqLock. It's ideal for this use-case, especially with infrequently-changed data. (e.g. like a time variable updated by a timer interrupt, read all over the place.) Implementing 64 bit atomic counter with 32 bit atomics Optimal way to pass a few variables between 2 threads pinning different CPUs ...
72,977,135
72,978,419
In MFC, how to add Buttons according to the user input
What I want to achieve is that user can input a number in the Edit Control, and according to that number the exact same number of buttons will be created (in the same dialog would be the best). How will I be able to achieve that?
Dynamically creating controls with MFC is a two-step process: Construct a C++ class instance that will represent the control by invoking the c'tor (CButton::CButton) Construct the actual control by calling CButton::Create If you need to create n button controls, perform this sequence n times. This solves the easy par...
72,977,403
72,977,728
std::tolower example from website not giving expected result
I found an example of std::tolower, here: https://en.cppreference.com/w/cpp/string/byte/islower There's an example which, according to the website, should return false and true for this bit of code: #include <iostream> #include <cctype> #include <clocale> int main() { unsigned char c = '\xe5'; // letter å in ISO-...
Ok so problem is that on Windows locale names are not same as on Linux. On Windows iso88591 is represented by codepage 1252 so one of possible locale name is:.1252: std::setlocale(LC_ALL, ".1252"); Not sure, but it is possible also .Windows-1252 will do the job too. You can also try boost.locale to try unify locale na...
72,977,690
72,978,056
Simple template to pass a c++ member method as a callback
I have a set of classes which have many very similar methods, grouped into 2 call signatures. These calls are of the form: bool fn( const std::string& ) and bool fn( const std::vector<std::string>& ) I need to do some common logic around each call and I'm trying to make my life easy but without much luck. Conceptually,...
You can just pass the member pointer as function argument: template <typename T> bool CFG_STR( T& cfg, bool(T::*fn)(const std::string&), const char* key, Nodes data, bool flag ) { /*...*/ } And instead of repeating the class name you can just write decltype(config): success &= CFG_STR( config, &decltype(config)::metho...
72,977,902
72,978,084
2d push_back doesnt save to vector values
I have a 2d vector which should save x and y coordinates. Everything works as intended except saving this values to vector. What did I do wrong? void Game::GetShips(Board &b) { vector<vector<int>> shipCors; for (int i = 0; i < BOARDSIZE; i++) { for (int j = 0; j < BOARDSIZE; j++) { if (b.g...
You declared an empty vector vector<vector<int>> shipCors; So you may not use the subscript operator shipCors[i].push_back(j); You could write for (int i = 0; i < BOARDSIZE; i++) { shipCors.resize( shipCors.size() + 1 ); for (int j = 0; j < BOARDSIZE; j++) { if (b.getSpaceValue(i, j) == SHIP) { ...
72,978,401
72,978,874
Why is masking needed before using a pshufb shuffle as a lookup table for nibbles?
This code comes from https://github.com/WojciechMula/sse-popcount/blob/master/popcnt-avx2-lookup.cpp. std::uint64_t popcnt_AVX2_lookup(const uint8_t* data, const size_t n) { size_t i = 0; const __m256i lookup = _mm256_setr_epi8( /* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2, /* 4 */ 1, /* 5 */ 2,...
[v]pshufb looks at the high bit to zero that output element, unfortunately. In the pseudocode you quoted: IF b[i+7] == 1 # if high-bit set dst[i+7:i] := 0 # zero that output element ELSE ... the part you were looking at # else index the source Tthe intrinsics guid...
72,978,941
72,979,038
Total time in different parts of recursive function
I am new to C++ and I need to measure the total time for different parts of a recursive function. A simple example to show where I get so far is: #include <iostream> #include <unistd.h> #include <chrono> using namespace std; using namespace std::chrono; int recursive(int); void foo(); void bar(); int main() { int...
You can use some container to store the times, pass it by reference and accumulate the times. For example with a std::map<std::string,unsinged> to have labels: int recursive(int n, std::map<std::string,unsigned>& times) { if (n >= 0) return; // measure time of foo times["foo"] += duration_foo; // measu...
72,979,702
72,979,793
How to make a reference refer to another node of an std::unordered_map
I have an std::unordered_map<int, int> which stores the frequency count of each element present in a given array. I need to find the max frequency element and print the key and frequency count. #include <iostream> #include <unordered_map> #include <type_traits> int main() { std::unordered_map<int, int> mp { ...
std::remove_reference is not a callable. Its a type trait with a type member alias. Same goes for std::add_lvalue_reference. As you know all types, adding those type traits adds unnecessary complexity for no obvious gain. The code is barely readable, and frankly I don't understand how you expected it to work. Anyhow yo...
72,979,811
72,979,955
difference between using std::move and adding 0 to the number?
I'm curious about that is there any practical difference between using std::move to convert an l-value integer to r-value, and adding a 0 to that integer? or any other neutral arithmetic operation (multiplying by 1, subtracting 0, etc). Adding 0: int f(int&& i){ i++; return i; } int main(){ int x = 43; ...
std::move(x) and x+0 do not do the same thing. The former gives you an rvalue (specifically xvalue) referring to x. The latter gives you a rvalue (specifically prvalue) which (after temporary materialization) refers to a temporary object with lifetime ending after the full-expression. So f(x+0); does not cause x to be ...
72,980,035
72,981,895
'runtime_error' from c++ not captured in iOS
In my iOS project, I use a C++ module. The C++ module throws exception for some cases and the Objective C++ wrapper fails to catch it. For instance Here is my HelloWorld.h #include <string> using namespace std; class HelloWorld{ public: string helloWorld(); }; #endif Implementation HelloWorld.cpp #include "Hello...
C++ Interoperability In 64-bit processes, Objective-C exceptions (NSException) and C++ exception are interoperable. Specifically, C++ destructors and Objective-C @finally blocks are honored when the exception mechanism unwinds an exception. In addition, default catch clauses—that is, catch(...) and @catch(...)—can cat...
72,980,706
72,980,855
c++: is it better to have a global variable or create a local variable?
for example i have a library function which needs to be used for validating signatures,and is only called when requested. lets say i have a library class to verify signature sigverify.hpp class SigVerify { bool verifySignature(std::string path); } sigverify.cpp bool Sigverify::verifySignature(std::string path) { //ve...
Consider a third option mentioned in comments: void ServiceClass::makeLibCall() { static Sigverify m_sigVerify; bool result = m_sigVerify.verifySignautre(path); } m_sigVerify will be initialized once, when the function is called for the first time. However, to know what is more performant you need to measure. Th...
72,980,766
72,983,330
C++ Eigen initialise dynamic matrix with raw data
Suppose I have raw data, whose size I don't know at compile time, and that's why I need to store it in a dynamically sized matrix. I know I can initialise a static-sized matrix as follows: std::vector<double> v {1.1, 2.2, 3.3, 4.4}; // "Raw data". Eigen::Matrix<double, 2, 2> m(v.data()); std::cout << m << std::e...
If you want to copy the raw data, assign the Map to a normal matrix. std::vector<double> v {1.1, 2.2, 3.3, 4.4}; Eigen::MatrixXd m = Eigen::MatrixXd::Map(v.data(), 2, 2); BTW: You don't need to deal with the template parameters such as Matrix<double, 2, 2> or Matrix<double, Dynamic, Dynamic>: There are type definition...
72,981,018
73,265,624
How to cancel background noise while playing PCM Audio in STM32?
I am trying to play Audio from PCM data in STM32(blackpill_f411ce). I can hear the audio but there is a steep noise also coming with the audio. I am working in PlatformIO with Audrino's framework. The PCM data is defined inside the code as an unsigned char array like below unsigned char sample[98216] = {0x52, 0x49, 0x4...
In setup, I added analogWriteFrequency(200000) and the problem solved void setup() { analogWriteFrequency(200000); } And also no need to put sine values void playPcmData() { for (size_t i = 0; i < 98216; i++) { int val=int(sample[i]); analogWrite(OUT_PIN_STM_32,val); delayMicroseconds(50); } }
72,981,024
72,981,052
weird behavior of #undef
#include <iostream> #define MY_CONST 10 #define MY_OTHER_CONST MY_CONST #undef MY_CONST int main() { enum my_enum : int { MY_CONST = 100 }; std::cout << MY_OTHER_CONST; return 0; } I would expect 10 as an output, but this program outputs 100. Can someone explain what is going on here? https://godb...
#define MY_OTHER_CONST MY_CONST defines the macro MY_OTHER_CONST to have a replacement list of MY_CONST. No replacement is performed when defining a macro. In std::cout << MY_OTHER_CONST;, MY_OTHER_CONST is replaced by its replacement list, becoming MY_CONST. At this point, there is no macro definition for MY_CONST, so...
72,981,284
72,981,317
Why is this code not printing the prime factors of num?
I wrote this code for obtaining the prime factors of a number taken as an input from the user. #include<bits/stdc++.h> using namespace std; void prime_Factors(int); bool isPrime(int); int main() { int num; cout << "Enter the number to find it's prime factors: "; cin >> num; prime_Factors(num); } void...
The ranges of the loops are wrong. Firstly, the loop for(int i = 2; i<n1; i++) will fail to find prime factors of prime numbers (the numbers theirself). It should be for(int i = 2; i<=n1; i++). Secondly, the loop for(int i = 0; i*i <= n0; i++) will result in division-by-zero. It should be for(int i = 2; i*i <= n0; i++)...
72,981,526
72,981,859
Efficient creation of thread pool (C++)
What is the 'best' way to create a thread pool for more efficient calculation? Suppose I have the following code to print out how many primes are in a given interval (for demonstration only, I know it's super slow): #include <future> #include <iostream> #include <thread> #include <math.h> bool is_prime(int n) { if (...
Consider you would calculate the results for the intervals sequentially. Then you would use loops and you can do the same with std::asynch and std::future (std::asynch does not return a thread). auto get_future_chunk(int from, int to){ return std::async(std::launch::async, primes_in_range, from,to); } int main() {...
72,982,010
72,982,455
Makefile with multiple separate *.cpp files to output separate *.exe files in different dir
I am stuck, writing my Makefile. Directory structure: .\ Makefile .\src\*.cpp(s) .\bin Desire: What I want to achieve with one Makefile. Run: make Output (Terminal): g++ -g -Wall -c -o src/program1.o src/program1.cpp g++ -g -Wall -c -o src/program2.o src/program2.cpp g++ -g -Wall -c -o src/program3.o src/p...
The introductory parts of the GNU make manual describe that all: $(BIN) creates a target all that depends on a target bin. That means make will try to create bin. Then you have $(BIN): $(OBJS) which says bin depends on all the object files, so make will try to create all the object files. Then there's a recipe for t...
72,982,157
72,982,359
variadic template 'ambiguous call to overloaded function' seems a false error
I try to write a template function to initialize given systems and run the app and at the end run shutdown function on initialized systems. This code should work in my eye and intellisense doesn't give any error but compiler: 1>C:\VisualStudio\DirectApp\AppMain.cpp(32,2): error C2668: 'initialize_these': ambiguous call...
the Rest can be empty, so both are valid. you can make the variadic one accept 2 or more argument template<class Type> static void f(){ // do something with Type } template<class First, class Second, class... Rest> static void f(){ // do something with First f<Second,Rest...>(); }
72,982,826
74,358,932
How to detect whether GPU is AMD or NVIDIA from inside HIP code
I'm currently writing a HIP equivalent to NVIDIA's deviceQuery sample code. I want my code to work on both AMD and NVIDIA hardware. Now, hipDeviceProp_t isn't exactly the same as cudaDeviceProp_t, because the former has both new and missing fields in the struct compared to the latter. Currently the code I wrote works o...
When using HIP you known at compile time if you are compiling for AMD or Nvidia GPUs (there is no support for both AMD and Nvidia GPU code in one binary). Thus you could try relying on the following pre-processor definitions: #if defined(__HIP_PLATFORM_AMD__) // AMD GPU code should take this code path #elif defined...
72,984,593
72,984,675
GoogleMock trying to set a function argument to a specific value using EXPECT_CALL
I have the following function prototype std::int16_t Driver::ListDevices( struct BoardInfo devInfo[], size_t len, int* pCount ) struct BoardInfo { int iBoardNum; WORD wSlot; char cSite; }; I have created a Mock for it as follows MOCK_METHOD3( ListDevices, std::int16_t( struct BoardInfo devInfo[], size_t ...
Your actions are not combined properly. EXPECT_CALL( *m_pMockObject, ListDevices( testing::_, testing::_, testing::_ ) ) .WillOnce(testing::DoAll(testing::SetArgPointee<2>( 1 ), testing::Return( 0 )));
72,985,114
72,986,766
Deplying a C++ application on Linux- linking everything statically to simplify deployment?
I am building a C++ project from Github and want to deploy the code to a remote Linux machine. This is all new to me. The project has a main.cpp, which includes the various headers/sources like a library. The CMake outputs an executable (to represent main.cpp) AND a separate static library. The project also uses OpenSS...
ITNOA I it is very helpful to make URL of your GitHub's project, but I write some public notes about that In generally in CMake for static linking your library to your executable, you can write simple like below (from official CMake example) add_library(archive archive.cpp zip.cpp lzma.cpp) add_executable(zipapp zipapp...
72,985,253
72,985,549
STL algorithm to get a per-vector-component min/max
I have a std::vector<vec3> points where vec3 has float x, y, z. I want to find the min/max bounds of all the points. I.e. the min and max of all vec3::x, vec3::y, vec3::z separately in the vector of points. I see that STL has std::minmax_element() which is almost what I want, but it assumes there is a min/max of the wh...
Of course you can use a lambda with std::reduce on a std::pair<vec3, vec3> collext both min and max at the same time. std::pair<vec3, vec3> minmax_elements(const std::vector<vec3>& points) { assert(!points.empty()); return std::reduce(points.cbegin(), points.cend(), std::make_pair(points.front(), points.front()...
72,985,711
72,985,758
QT signal and slot connection not working
I am making a simple game and want to send a signal from my Game class to my MainWindow. My signal and slot share the same parameter but I can't connect them. I have tried sending very simple signals with a dummy variable but failed to connect. The code is as follows. game.h class Game : public QObject { Q_OBJECT p...
I think the problem may be in the fact that you have g->gameLoop(); BEFORE the connect. If your someFunction is called from the gameLoop, then the connect is performed only after the game has finished and after the execution returns from the gameLoop(). But of course it's just guessing. I wouldn't expect to see 'gameLo...
72,986,106
72,986,218
C++ / warning: control reaches end of non-void function [-Wreturn-type]
I am just a beginner today and trying to learn desktop programming with C++. And I am confused that why doesnt this work: The code: int math(int opt, int x, int y){ switch(opt){ case 1: return x + y; break; case 2: return x - y; break; case 3: ...
The problem is, if you pass "invalid" opt value, default case gets selected, and your function returns nothing. So one solution would be to decide what to return if you pass invalid opt. You should fix your problem like this: enum class Opt { PLUS, MINUS, TIMES, DIVIDED }; int math(Opt opt, int x, int y) { switch(...
72,986,187
72,986,915
Will a source file be recompiled multiple times if its nested header file is modified?
In the attached image, if D.h is modified, will Visual Studio recompile A.cpp twice? Or will it be recompiled only once?
No. Compiling a.cpp once is sufficient to produce an object file that incorporates all the latest changes from the header files (if they are relevant to the code in a.cpp). Your build system should be considered to be buggy and broken if it has to compile a.cpp twice during a single build, because the second compilati...
72,986,476
72,986,592
Macro with a C++ class
I was going through this code (line 41): https://github.com/black-sat/black/blob/master/src/lib/include/black/logic/parser.hpp and came across something like this: #include <iostream> #define YES class YES myClass{}; int main(){ cout << "Hi\n"; return 0; } What is the purpose of defining a macro and using it in fron...
The way you've written it there isn't much point. But if you look at the project's common.hpp file to see how it's used, it makes a lot of sense, and is a common pattern in C and C++: #ifdef _MSC_VER #define BLACK_EXPORT __declspec(dllexport) #else #define BLACK_EXPORT #endif ... class BLACK_EXPORT parser { ...
72,986,697
72,986,930
C++ fstream object passed as reference, but it won't make
I'm trying to do a bunch of stuff with the .txt file I'm trying to read, so I want to break it up into functions. But even when I pass the file stream in by reference, I can't get the program to compile. #include "Executive.h" #include "Clip.h" #include <string> #include <iostream> #include <fstream...
ITNOA simple answer for resolve your problem you can just remove const keyword in declaration of findStart funciton. TL;DR; in generally if you want to only read from file, please use ifstream instead of fstream. your code problem is stream >> temp; does not work with const fstream because operator >> has declared like...
72,986,941
72,986,978
Join a container of `std::string_view`
How can you concisely combine a container of std::string_views? For instance, boost::algorithm::join is great, but it only works for std::string. An ideal implementation would be static std::string_view unwords(const std::vector<std::string_view>& svVec) { std::string_view joined; boost::algorithm::join(svVec," ");...
ITNOA short C++20 answer version: using namespace std::literals; const auto bits = { "https:"sv, "//"sv, "cppreference"sv, "."sv, "com"sv }; for (char const c : bits | std::views::join) std::cout << c; std::cout << '\n'; since C++23 if you want to add special string or character between parts you can j...
72,987,131
72,987,510
Slow performance using std::distance to get std::map index
I have a std::map and I need all its key, value and index for some process. My code works correctly. The only issue is: it's too slow. Below is an example: void run(const std::map <key, value>& myMap) { std::map <key, value>::const_iterator iter; for (iter = myMap.begin(); iter != myMap.end(); ++iter) { ...
std::map is a tree structure. It's not random access, and elements don't have indices, and the only way to advance through the tree is to follow the links, one at a time. Because of this, std::map::iterator is a BidirectionalIterator. That means it only supports increment and decrement operations. It doesn't suppor...
72,988,260
72,988,898
Problem with using derived class where base class is expected
I am writing a code for a little system that should run on an arduino. The objective is to control several cycles which each have a certain amount of sub-cycles. Both the cycles and the subcycles are defined by their duration and ultimately, the system's operations will be performed at the subcycle level (didn't implem...
You aren't passing an event or event pointer to your event manager; you are passing an array of events. While accessing individual objects through a pointer is polymorphic, this does not extend to raw arrays. Raw arrays are simple collections of only 1 type of object (naturally all of the same size). And all they conta...
72,988,487
72,992,193
Is it safe to access stack variable after `this` has been deleted
Found similar questions: Is it safe to `delete this`? I know that it's unsafe to access member variable. Because this becomes a dangling pointer after delete. But what about stack variable?Clang ASAN does report error if member variable is accessed. But it does not report any problems about stack variable access. IMHO....
The problem is having counter_ equal to task_num_ - 1 does not mean all threads are finished. It just mean that the fetch_add call has been executed by all threads here. The thing is the == in the expression counter_.fetch_add(1, std::memory_order_acq_rel) == task_num_ - 1 is parsed from left to right. Thus, the fetch_...
72,988,494
72,989,010
C++ File How to auto generate number for next data to store
#include <iostream> #include <fstream> using namespace std; class Customer { private: fstream database; string customerRecord = "customerRecord.txt"; int movieID = 0; public: void write() { database.open(customerRecord, ios::app | ios::in); string li...
If you read to the end of the file and stop reading because you tried to read past the end of the file, the fail bit and the eof bit are set and you cannot read or write until both are cleared. The only way out of while(getline(database, lines)) { movieID++; } is to be unable to read any further and set fail and e...
72,988,701
72,989,508
Using std::is_same with structural (non-type) template parameters
Consider a templated type containing a structural template parameter of any type. For the purpose of the example value_type<auto V> is defined. We also declare a constexpr structure containing some member integral types with custom constructors that set the member values using a non-trivial expression (requiring more t...
How exactly is the comparison of those types performed? Is this behavior standardized across compilers or is it just pure luck that they all seem to follow the same pattern here? As per NTTP on cppref, emphasis mine: An identifier that names a non-type template parameter of class type T denotes a static storage du...
72,988,735
72,990,619
Replacing THC/THC.h module to ATen/ATen.h module
I have question about replacing <THC/THC.h> method. Recently, I'm working on installing different loss functions compiled with cpp and cuda. However, what I faced was a fatal error of 'THC/THC.h': No such file or directory I found out that TH(C) methods were currently deprecated in recent version of pytorch, and was r...
After struggling for a while, I found the answer for my own. In case of THCState_getCurrentStream, it could directly be replaced by at::cuda::getCurrentCUDAStream(). Therefore, modified code block was formulated as below. //Comment Out //#include <THE/THC.h> //extern THCState *state; //cudaStream_t stream = THCState_g...
72,989,501
72,989,538
How to read a text file into parallel arrays
I must have a function that reads card information from a text file (cards.txt) and insert them to parallel arrays in the main program using a pointer. I have successfully read the text file, but cannot successfully insert the info to the arrays. #include <iostream> #include <stream> #include <string> using namespace s...
The main problem is that you have two sets of arrays, one in main, and one in readCards. You need one set of arrays in main and to pass those arrays (using pointers) to readCards. Like this void readCards(int* id, string* beybladeName, string* productCode, string* type, string* plusMode, string* system); int main() { ...
72,989,685
72,989,867
C++ Memory Layout: Questions about multiple inheritance, virtual destructors, and virtual function tables
I have a main.cpp file as follows. #include <stdio.h> class Base1 { public: int ibase1; Base1() : ibase1(10) {} virtual void f_b1_1() { printf("Base1::f_b1_1()()\n"); } virtual void f_b1_2() { printf("Base1::f_b1_2()()\n"); } virtual ~Base1() { printf("Base1::~Base1()\n"); } }; class Base2 { public...
What is the meaning of the content in the red box? Does the above relate to "C++ trunk"? The symbols you highlighed are mangled, you can use some demangle tools, like c++filt > c++filt _ZThn16_N6Derive6f_b2_1Ev non-virtual thunk to Derive::f_b2_1() As to your rest questions, you could refer to What is a 'thunk'? t...
72,989,699
72,990,097
Include SDL_image in mingw build on ubuntu
I'm trying to build a windows executable for a C++ application I've made that uses SDL2, and SDL_Image. I've seemingly managed to include the SDL libraries and headers just fine, but now I'm trying to include the SDL_Image ones. The command I'm currently using is as follows: i686-w64-mingw32-gcc -lSDL2main -lSDL2 -I ~/...
SDL2_Image is a plugin for SDL2, and needs to be downloaded separately. You also need to specify -I and -L for it, the same way you did for the SDL2 itself. Also you forgot -lmingw32 (must be -lmingw32 -lSDL2main -lSDL2 in this exact order), plus -lSDL2_image after those. As always, a shameless plug: I've made quasi-m...
72,989,732
72,989,817
How to structure base class where derived classes operate on different data types
I have a class that is supposed to fetch an object from the server. // T types struct RequestLicense { // arbitrary data }; struct RequestTrial { // arbitrary data } // U types struct LicenseData { // arbitrary data }; struct TrialData { // arbitrary data } struct Fetcher { template <typename T> ...
I think I would make the whole Fetcher structure a template, with the member functions being abstract virtual functions: // R is the request type // D is the data type template <typename R, typename D> struct Fetcher { virtual std::wstring FetchBlob(R const& requestParameters) = 0; virtual std::unique_ptr<...
72,990,065
72,990,093
Two sum but sum is in a range
How this can be solved faster than O(N^2) without using Binary indexed tree (O(NlogN), but Memory Out Limit) arr = [6, 2, 3, 5, 1, 6], l = 5, h = 7 Find number of pairs i, j such that i < j && (arr[i] + arr[j] >= l && arr[i] + arr[j] <= r) O(N^2) solution is very straight-forward, but TLE. What I tried: Using Binary ...
Sort the array in ascending order and, for each i, binary search (in (i , n]) the first j for which the first condition is true. Let it be j1. Then, binary search (again in (i, n]) the last j for which the second condition is true. Let it be j2. If everything is ok, add |j2 - j1 + 1| to the answer. The overall time co...
72,990,156
72,990,369
Question about reference return type in C++
I write the following code: const string& combine(string &s1,string &s2) { return s1+s2; } but when I pass two strings to this function, the result I use "std::cout" to print is the empty string.I don't know what the reason is. Thanks in advance.
The behaviour of your code is undefined. This is because s1 + s2 is an anonymous temporary and you are attempting to bind that to a reference return type. The output you observe is a manifestation of that undefined behaviour. Changing the return type of the function to a std::string value is a fix. Another more interes...
72,990,607
72,991,800
"const std::stop_token&" or just "std::stop_token" as parameter for thread function?
Since clang-tidy was complaining about "The parameter 'stop_token' is copied for each invocation but only used as a const reference; consider making it a const reference" I was asking myself the question, why every example I find about std::jthread/stop_token takes the stop_token by value, but I did not find any explan...
As per cppref, Creates new jthread object and associates it with a thread of execution. The new thread of execution starts executing std::invoke(std::move(f_copy), get_stop_token(), std::move(args_copy)...), ... And the return type of std::jthread::get_stop_token is std::stop_token. So, if your f is only used to cons...