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,428,516
72,428,803
Have 2 Lambda expressions within the same function call each other
I've been using SFML for a project, and I'm attempting to make a pause state while still using the SFML game loop. Long story short, I have been attempting to use 2 Lambda expressions within the same function to toggle between the pause and run states I have running. Here's some example code: int main() { //some stuf...
As long as your lambdas have captures, and it seems like yours do, you can't have them call each other directly because there is a circular dependency when you declare them. To work around this, you can assign them to pointers. If you did not have captures, the compiler would simply generate anonymous functions for you...
72,428,603
72,429,946
Optimize Binary Search in sorted array find number of occurences
Im trying to do the smallest number of operations possible to find the number of occurences of an element in the array. Save even 1 operation if possible. So far this is the best binary search version I know. I cant use vectors or any other std:: functions int modifiedbinsearch_low(int* arr, int low, int high , int key...
Here's a performance issue. In the main while loop, you aren't breaking out fo the loop when you find the target value. while(low<=high){ int mid=(low+high)/2; if(a[mid]==k) { result=mid; // you need to break out of the loop here if(searchfirst) high=mid-1; else l...
72,429,210
72,438,310
How to read n bytes of a file in QT C++?
Hi im new to Qt and im trying to read for example the first 4 bytes of my .txt file and show it. I've been searching and figure that QbyteArray may help me best in this situation. so I really like to know how can i read the first 4 bytes of my file with QbyteArray? (appreciate if u write any example code)
Assuming your code contains something like this: QFile file{ "path/to/file.txt" }; You can read a number of bytes from a file with file.read(n), assuming n to be a number of bytes. you can also use file.readAll() to get the entire thing for more advanced input/output operations, you can use the QTextStream class as ...
72,429,519
72,429,582
C++: Cannot use designated initializers on extended structs/classes
I am trying to figure out a way to use designated initializers to build a struct, which has been extended off of another one. In my use case, the struct S is a domain object, and the struct S2 adds some application-specific logic for converting it to/from json. As far as I can tell, you cannot use designated initialize...
i is data member of S, but not S2. You can add another braces referring to the base subobject, e.g. return S2 { {.i = 1234} }; Or you can just take advantage of brace elision: return S2 { 1234 };
72,430,369
72,430,675
How to check that a type is 'formattable' using type traits / concepts?
I would like to check if a certain type can be used with std::format. This is my naive attempt: template<typename Object> concept formattable = requires(const Object & obj) { std::format("{}", obj); }; But this does not work. It basically returns true for all types. Even those that can't be used with std::format. ...
Since std::format is not a constrained function, the expression std::format("{}", obj) is always well-formed. You might want to do #include <format> template<typename T> concept formattable = requires (T& v, std::format_context ctx) { std::formatter<std::remove_cvref_t<T>>().format(v, ctx); }; which mainly base...
72,430,383
72,432,821
make error: undefined reference to cpp_redis::client::set(..) and cv::Mat::~Mat()
Complete error stack trace: undefined reference to `cv::Mat::Mat(int, int, int, void*, unsigned long)' undefined reference to `cv::imencode(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&, std::vector<unsigned char, std::allocator<unsigned char> >&, std::ve...
Your CMakeLists.txt is wrong and messy try this: cmake_minimum_required(VERSION 3.16) project(DisplayImage CXX) find_package(OpenCV REQUIRED COMPONENTS core imgproc video) ... add_executable(${PROJECT_NAME} ${SOURCES}) target_link_libraries(${PROJECT_NAME} PRIVATE opencv_core opencv_video ...
72,430,636
72,430,993
Clean way to get function pointer from external std::function
Because C, I need a function pointer from a std::function I receive at runtime. Let's call defineProxyCallback the C function taking as input a function of unsigned char. My hack to make this work has been : struct callBacker { std::function<void(unsigned char)> normalKey; }; callBacker cb = callBacker(); extern ca...
I don't think this is ever going to be super-neat and tidy. If it were me I would probably use inline functions so that they could go in a header file and I would use thread_localstorage to add a little thread safety. Something a bit like this: // force the compiler to make sure only one of these functions // is linked...
72,431,090
72,431,427
Can I use an std::ostream to print into a given buffer?
I have a given buffer of characters (maybe even the buffer backing an std::string, but never mind that). I want to print into that buffer using an std::ostream, i.e. I want to be able to write: span<char> my_buffer = get_buffer(); auto my_os = /* magic */; static_assert( std::is_base_of<std::basic_ostream<char>,decl...
(Thank @BoP and @T.C. for the two parts of this solution) This can be done... if you're willing to use a deprecated C++ construct: std:ostrstream. #include <strstream> #include <iostream> int main() { const size_t n = 20; char my_buffer[n]; std::ostrstream my_os(my_buffer, n); my_os << "hello" << ',' <...
72,431,265
72,431,869
How to print .html files using ShellExecuteExW?
The goal is to print a htm/html file via Windows-API ::ShellExecuteExW. The parameters of ::ShellExecuteExW are shell_info.lpVerb = "open"; shell_info.lpFile = "C:\Windows\System32\rundll32.exe"; shell_info.lpParameters = "C:\Windows\System32\mshtml.dll ,PrintHTML "C:\Temp\test.html""; lpFile and lpParameters are fetc...
Is it possible that the code that generates the error in the screenshot looks different from what you show us here? I'm asking this because you don't seem to escape any double quote or backslash. Seems to me your compiler should at least give one error when compiling that code. However I just tried the code below and t...
72,431,311
72,431,434
When I am trying to implement a vector inside a strcuture I am getting garbage values, How can I remove those garbage values
#include <iostream> #include <vector> using namespace std; #pragma pack(1) struct person{ int age = 25; int salary = 20000; vector<int> a = {1,2,3,4,5}; }; #pragma pack() int main() { person obj; person *p = new person(obj); int* ch = reinterpret_cast<int*>(p); for(int i=0;i<32;i++){ ...
The problem is that you're typecasting a person* to an int* and then dereferencing that int* which leads to undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that h...
72,431,360
72,431,533
Serial.write(5) not able to send decimal?
I am trying, as a test to Serial.write the int value: 5, to serial monitor, and if received, i want to print the the text "SUCCESS!" to the serial monitor. But when writing Serial.write((int)5); All i get in the serial monitor is: I have tried using Serial.println(5); which works fine, but then i am not able to read i...
Serial.write(5) sends the byte 5 to the computer. It appears as a square, because it's not an ASCII code of a letter or number or symbol. Serial.print(5) sends the ASCII code for 5 (which is 53). The reason you can't read what you wrote is because Serial.write sends data to the computer and Serial.read returns data rec...
72,431,414
72,435,116
IBM xlc compile fail with error message "The test "std::function" is unexpected
I use IBM xlc to compile C++ code but it failed with error message "The test "std::function" is unexpected. I use std::function in my code and add compile option "-qlanglvl=extended0x". The xlc version is 13.1. By the way, the same code is compiled successfully with G++. Does anybody know the reason. Thanks.
The xlC compiler -qlanglvl=extended0x only has experimental C++11 support and is notably missing C++11 library. You need to move up to the V16 xlclang++ compiler or V17 ibm-clang++ compiler to get full C++11 support.
72,431,661
72,432,505
Are C++ exceptions expected to be handled in main()?
I am doing a project in C++, and I am new to OOP. I have some doubts regarding C++ exceptions and where they have to be handled. I read that it is a good practice to insert the try/catch block into the main() function, letting the exceptions thrown into "deep placed" methods to climb up to main() and be handled there, ...
There is no general rule where these handlers should go. But you describe your program as "high level functions called in main() return a bool value". That is a reasonable choice: any specific exception handling is taken care of by those high-level functions. From the perspective of main, these high-level functions eit...
72,432,379
72,432,783
Allocate a dynamic array of pointers to the structure
I have created the dynamic array struct Student{ string name; string dateOfBirth; }; Student **students = new Student*[5] But I'm getting error when I try to store data Exception thrown: read access violation. this was 0xCDCDCDCD. (*students[iterator]).name = name;
If you want to allocate memory like this: struct Student{ string name; string dateOfBirth; }; Student **students = new Student*[5]; Just like the comments say, you need to think about what the datatype of students[0] actually is. In this case, it's a Student *, meaning you have to treat it as such. If you try...
72,432,729
72,439,826
Having trouble iterating over the right children to change their color
I'm looking to make a menu where there are more than one wxStaticTexts and when one of them is clicked it turns black and the rest are/revert back to being grey (if they were clicked before, otherwise they would just stay grey) The problem is I usurped this code which works great for doing the first part, it turns the ...
This works for me: void MyFrame::OnMenuTxtBtnLeftClickPanel(wxMouseEvent& event) { wxWindow* cur = wxDynamicCast(event.GetEventObject(),wxWindow); wxColor fg = m_panel1->GetForegroundColour(); wxWindowList& children = m_panel1->GetChildren(); for ( auto it = children.begin() ; it != children.end() ; +...
72,433,291
72,436,570
operator [][] matrix c++
Im trying to create an operator that gives me the value for the position i,j of a certain matrix and another one that "fills" the matrix in the given positions, ive tried to put the operator that you can see in the header but it isnt working, the problem might be somewhere else but i think this it the main issue: ...
Fixing the array resize as 463035818_is_not_a_number suggested gives you a somewhat working matrix. matriz(int L, int C): iLargura (L), iComprimento (C) { m.resize(L); for (int i = 0; i<L;i++) m[i].resize(C); }; If you also print the matrixes a and b you get: a: 1 1 1 1 1 1 1 ...
72,433,476
72,433,841
how to use a parent class as a parameter in an inherited child class in c++?
it could be not good question and i know i need more time to learn about it but i'm really wondering how to make it work here is my code #include <bits/stdc++.h> using namespace std; class Parent{ protected: int value; int size; public: Parent(); Parent(const Parent &p); }; Pa...
This Child(const Parent& p); is not a proper copy constructor. A copy constructor for a class T takes a &T (possibly with CV-qualifier) as argument. In this case it should be Child(const Child& p);. Furthermore, if we look at https://en.cppreference.com/w/cpp/language/access, then we can see that: A protected member o...
72,433,545
72,448,172
Hook APIs that imported to program by LoadLibrary/GetProcAddress
I know how I can hook functions from the IAT table, but I have a problem with APIs which were imported by calling LoadLibrary/GetProcAddress functions. I want to know exactly how someone could hook those functions. I realize that I should hook the GetProcAddress function but how can I check the parameters that were pas...
In order to hook APIs that they are loaded into a binary dynamically with help of LoadLibrary/GetProcAddress, you should intercept return address of the GetProcAddress and name of the functions that passed to it (for example, consider a program try to load MessageBoxA in this way). In the second step, you should save t...
72,433,547
72,433,836
C++ "for" loop with a pow function in it gives incorrect results
I'm studying coding basics, and had to make a code that calculates how many levels of a pyramid could be built with blocks available "x", if each level is squared (e.g. 1st=1, 2nd=4, 3rd=9 etc.) here's what I have so far, and for the life of me, I can't see where I'm wrong, but the code keeps returning a value of 2 mor...
It is because your for loop works even if next layer is impossible to make and then it increments i once more . That's why your result is bigger by 2 than it should be . Try this: int tmp; while(true){ tmp = y+i*i; if(tmp > x) //check if this layer is possible to create { i--; //its impossible , so answer is ...
72,433,667
72,434,289
How to deal: if boost::asio::post is endlessly repeated, when boost::asio::thread_pool destructor is triggered?
I have a class wrapper for boost::asio::thread_pool m_pool. And in wrapper's destructor i join all the threads: ThreadPool::~ThreadPool() { m_pool.join(); cout << "All threads in Thread pool were completed"; } Also I have queue method to add new task to threadpool: void ThreadPool::queue(std::function<void()> ...
1+1 == 2: just remove the join(). As you've noted, that risks blocking indefinitely. You don't want/need that, so why ask for it? Alternatively, you could manually stop and join the pool. I'd suggest removing the destructor.
72,434,281
72,435,212
ZeroMQ pub-sub send last message to new subscribers
Can ZeroMQ Publisher Subscriber sockets be configured so that a newly-connected client always receive last published message (if any)? What am I trying to do: My message is a kind of system state so that new one deprecates previous one. All clients has to have current states. It works for already connected clients (sub...
There is an example in the ZMQ guide called Last Value Caching. The idea is to put a proxy in between that caches the last messages for each topic and forwards it to new subscribes. It uses an XPUB instead of a PUB socket to react on new connections.
72,434,416
72,435,146
What's the difference between Radio r = Radio("PSR", 100.8) and Radio("PSR", 100.8)?
I'm new to C++ and trying to understand something. I have this code in my main.cpp: Radio r = Radio("PSR", 100.8); or that code: Radio r("PSR", 100.8); Both seem to work and doing the same thing. So what's the difference?
Radio r = Radio("PSR", 100.8); is copy initialization while Radio r("PSR", 100.8); is direct initialization. C++17 From C++17 due to mandatory copy elison both are the equivalent. Radio r = Radio("PSR", 100.8); //from C++17 this is same as writing Radio r("PSR", 100.8); Prior C++17 But prior to C++17, the first case R...
72,434,675
72,502,244
How to transform different containers with std library?
Does it exist a way to transform containters of different types using std functions? QSet<QString> res; QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces(); for(const auto& interface : allInterfaces){ res.insert(interface.name()); }
std::transform can accept different containers. You can see it in the function signature: template< class InputIt, class OutputIt, class UnaryOperation > OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first, UnaryOperation unary_op )...
72,434,731
72,435,031
Why does the compiler try to instantiate the wrong STL template? (BinaryOperation instead of UnaryOperation)
I want to use std::transform with a parallel execution policy. The documentation tells to use the template (2): template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryOperation > ForwardIt2 transform( ExecutionPolicy&& policy, ForwardIt1 first...
My code [...] seems to match the template: It doesn't: template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryOperation > ForwardIt2 transform( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ...
72,434,897
72,435,847
Enforcing a common interface with std::variant without inheritance
Suppose you have some classes like Circle, Image, Polygon for which you need to enforce a common interface that looks like this (not real code): struct Interface { virtual bool hitTest(Point p) = 0; virtual Rect boundingRect() = 0; virtual std::string uniqueId() = 0; } so for example the Circle class would...
The simplest and quite execution time optimal solution is have separate container for each type. Any example showing that Data Oriented Design is better then Object Oriented Programing is using this approach to show difference in performance. Other way is to create some wrapper for variant: class VisualElement { Ba...
72,435,013
72,435,428
Why bind function does not work with dereferencing iterator?
I am new to c++ programming. I am using bind function to bind an object with class setter and call the setter. When I try to dereference the iterator as the object in the bind function, the object variable does not change. However, when I just pass in the iterator as the object in bind function, it works. Can anyone pl...
As stated in the std::bind page on cpprefrence: The arguments to bind are copied or moved, and are never passed by reference unless wrapped in std::ref or std::cref. If you want to change the objects pointed to by *employee, you should wrap them in a std::reference_wrapper, e.g. by means of helper function std::ref: ...
72,435,144
72,436,561
Control may reach end of non-void fct in recursive function
I know why and whats happening for this error. Mainly bc the return in inside the if. However Id like to fix the flow so its error/warning free. Ive added inconsequential returns at the end as well as modifying the flow the best I could but with no luck. int modifiedbinsearch_low(int* arr, int low, int high , int key){...
The both functions return nothing when the control is reached if statements if(key > arr[mid] ) { modifiedbinsearch_low(arr,mid + 1 , high,key); } else { modifiedbinsearch_low(arr,low,mid,key); } and if(key < arr[mid] ) { modifiedbinsearch_high(arr,low,mid,key); } else { modifiedbinsearch_high(arr,mid+1,hig...
72,435,397
72,455,108
How to get date (day/month/year) from MonthCalendar in C++ Builder 6?
I'm creating an age counter app, but I couldn't use the date, which is user chose from the calendar. How can I use the day/month/year specified in MonthCalendar in my program?
TMonthCalendar has a Date property, which returns the user's selected date as a TDateTime value. You can extract the individual month, day, and year values from that, if needed, by using the TDateTime::DecodeDate() method. TDateTime dtSelected = MonthCalendar1->Date; Word wYear, wMonth, wDay; dtSelected.DecodeDate(&wY...
72,435,574
72,435,695
Thread leak detected when using condition variable instead of join() with pthread
I'm new to pthread synchronization, searched "pthread condition variable" in google and grab an example from the pdf: https://pages.cs.wisc.edu/~remzi/OSTEP/threads-cv.pdf . The example code is as follow, whose purpose is "use condition variable and a variable done to implement pthread_join()" (as I understand): // htt...
Is this C++ code really a thread leak, or just a false positive report from tsan? It is really a thread leak, arising from the fact that you cannot implement a substitute for pthread_join(). At least, not in any portable way or based only on the C++ (or C) and pthreads specifications. The program starts a thread an...
72,435,683
72,435,863
std::any_cast without needing the type of the original object
Is it possible to use std::any_cast without putting in the first template argument (the type of the object the any is covering)? I tried using any_cast<decltype(typeid(toCast).name())> but it didn't work. Also tried to store the objects types from the beginning, but that also didn't work because variables can't store t...
One of the fundamentals principles of C++ is that the types of all objects are known at compile time. This is an absolute rule, and there are no exceptions. The type of the object in question is std::any. It is convertible to some other type only if that type is also known at compile time. You will note that std::type_...
72,435,684
72,435,725
Reference to object method
I would like to have a reference to the call of an object's method. Is this possible in C++? What is the technical name I should be searching for? Can we supply some arguments with predetermined values? The following code highlights what I would like to use struct Foo { void barNoArgs(); void barMultArgs(int, float...
What is the technical name I should be searching for? This is called Argument Binding, or sometimes a Partial Function But first, you should know that both of your examples are the exact same problem. Methods are essentially functions with a hidden first parameter called this after all. So refToBarNoArgs is a functio...
72,435,808
72,435,986
Why is this recursive selection sort not working
I tried to run the code but it just gets stuck. NO error no warning nothing.Is there a better way to write a recursive selection sort? #include <iostream> using namespace std; void scan(int *arr, int size){ for(int i = 0; i < size; i++){ cin >> arr[i]; } } void print(int *arr, int size){ for(int ...
There was 1 small problem in your code. When you call the swap function in the insertion function you have to call it with &arr[max] and &arr[size-1], you can also use i-1, as the value of i is size here. Code Attached for insertion function void insertion(int *arr, int size){ if(size <= 1)return; int i, maxInd...
72,435,912
72,448,008
Windows gcp List objects fails - Curl error [77]
Trying to list all object in a google storage bucket - this code runs fine in UNIX systems(centos 7/Mac), However when run from a windows server 2012/16 Vm I get Permanent error in ListObjects : EasyPerform() - CURL error [77]=Problem with the SSL CA cert (path? access rights?)[UNKNOWN] void gcpFileDialog::getListOfObj...
I think you need to install the certificate bundles as described in: https://curl.se/docs/sslcerts.html With newer versions of google-cloud-cpp you can use CARootsFilePathOption to override the default location of the CA cert file.
72,436,303
72,438,175
I get no sound in Game in UE 5
Same project ToonTanks had sound normally in UE4 but when I migrated to UE5 there is no projectile sound. In projectile.h I declare a sound like this UPROPERTY(EditAnywhere, Category="combat") USoundBase* LaunchSound; and I set it in the blueprint then in projectile.cpp BeginPlay I play the sound like this if (Launch...
Fixed using these steps: 1-Delete the folder Intermediate 2-Right click the uproject file and select generate vs files 3-open rider and choose for ex development editor build 4-wait until rider update source files 5-build from rider 6-open UE5 editor and run and sound work as expected.
72,436,604
72,437,204
Visual Studio compiling to wrong path AND trying to run wrong path when used with CMake
I'm very new to CMake (and new to C++ too, although that shouldn't matter here), and I am having a problem using CMake with Visual studio. I have created a directory, let's say it's called Project, and put in it a simple project with the following structure: Project/ build/ <empty> src/ main.cpp CMa...
Default project is set to ALL_BUILD to change the default for the VS generators use the following CMake statement: set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT Project) Anywhere after the add_executable command.
72,436,671
72,436,961
ADSI GetInfoEx not retrieving mail attribute
I can't get the Win32 ADSI c++ GetInfoEx API to retrieve the an AD user's mail attribute. The Get call instead returns hr 0x8000500D (E_ADS_PROPERTY_NOT_FOUND). Any ideas of how I can get the get the mail attribute? Here's my code. HRESULT hr = CoInitialize(NULL); if (hr == S_OK || hr == S_FALSE) { IADs *pUsr = NU...
The mail attribute is not available when using the WinNT provider: Unsupported IADsUser Properties You have to use LDAP. If you have the distinguishedName of the account, you can use that: hr = ADsGetObject(L"LDAP://CN=someuser,OU=Users,DC=example,DC=com", IID_IADs, (void**)&pUsr); If all you have is the domain and us...
72,437,210
72,441,224
How to call derived destructor using my custom shared pointer class without virtual destructor?
I am creating my custom shared pointer class and I want my shared pointer class should call derived class destructor when it goes out of scope for the below code. ... ... template<class T> MySharedPtr<T>::MySharedPtr(T * p) : ptr(p), refCnt(new RefCount()) { refCnt->AddRef(); } template<class T> void MySharedPtr<T...
You can store a callback as part of the RefCount object which will be called when the reference count goes to zero. This callback can "remember" what it needs to do based on the pointer type that was used to originally construct the MySharedPtr object, even though the knowledge of that most derived type might have been...
72,437,284
72,437,685
Alternatives for CMake commands
I am new to CMake and was going through the CMake documentations and tutorials. I was able to understand that the target_include_directories command is just the -I option for the compiler (gcc for me). I tried doing it adding the directories manually by using set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I <Path>") and it worke...
To answer your question literally: There is the variable CMAKE_EXE_LINKER_FLAGS and its specializations CMAKE_EXE_LINKER_FLAGS_<CONFIG> for certain configurations like RELEASE or DEBUG or whatever configurations you might have defined. See the CMake documentation for more. BUT, I highly disrecommend to use these unless...
72,437,379
72,442,710
Win32:Does ImageList_ReplaceIcon failed with unproper ImageList_Create
As the title says, I'm trying to write a simple window program, but when I try to change the icon of my TreeView, it goes wrong. I'm pretty sure my icon was loaded because I did this: HICON hIcon; //hinst is my global variable hIcon = LoadIcon(hinst,(char*)IDI_ICON_MAIN); if (hIcon == NULL) { MessageBox(NULL, "Load...
I can see my icon now, thanks. I appreciate those who gave me advice. ReplaceIcon() can only be used when I have already added an icon into it. If there's no icon in it then the only condition I can use is to set the index to -1, so that the ReplaceIcon() can add the icon for me.
72,437,399
72,437,483
why do we need a reference count in this Reentrant lock example?
Why do we need m_refCount in the example below? What would happen if we leaved it out and also removed the if statement and just left its body there ? class ReentrantLock32 { std::atomic<std::size_t> m_atomic; std::int32_t m_refCount; public: ReentrantLock32() : m_atomic(0), m_refCount(0) {} void Acqui...
The count is needed to implement recursive locking. If it were not there, Release would always unlock no matter how many Acquire calls there were, that is not what you expect and want in many cases. Consider the following common pattern: void helper_method(){ Acquire(); // Work #2 Release(); } void method...
72,437,676
72,437,859
Overriding only some virtual funtion of base class with the same name
I have a base class with a virtual fonction foo(int i) and foo() (same name, not same arguments). The derived class override only foo(). Now the derived class doesn't knows foo(int i) anymore. class Base { public: virtual void foo(int i) { std::cout << "Base::foo(int i)" << std::endl; } virtual void foo() { ...
Just add a using declaration inside derived class as shown below. In particular, a using declaration for a base-class member function (like foo) adds all the overloaded instances of that function to the scope of the derived class. Now you can override the version that takes an argument of type int and use the implement...
72,437,818
72,439,230
Traverse 2D Matrix diagonally omitting first row and first column
I am trying to traverse a 2D matrix diagonally and the function below prints all elements in a diagonal.I want to skip the first row and first column elements and start the diagonal traversal from matrix[1][1] because the values in the 0th row and 0th column are not required.So it is like slicing the matrix from the to...
From your example it looks like you want to print antidiagonals not diagonals, ie third line is 3 4 5 3 not 3 5 4 3. To get started keep things simple: Indices (i,j) along an antidiagonal are those i and j where i+j == some_constant. Hence this is a simple (not efficient) way to print elements along one antidiagonal: v...
72,438,381
72,438,966
How to pass a class member function that modifies class members to a function that takes a function pointer
I am writing software for an Arduino-powered weather station. I have a class for each of the sensor systems (some simple, some complex) and the rain gauge one needs to use the Arduino attachInterrupt function. Signature: void attachInterrupt(uint8_t interruptNum, void (*userFunc)(), int mode) This is used to execute a...
The problem is, on what object should the function be invoked when the interrupt occurs? You could do it this way for example: class RainGauge { int pulses; public: void begin(int pin, void (*callback)()); void increment(); }; void RainGauge::begin(int pin, void (*callback)()) { pulses = 0; attachInterrupt(d...
72,438,547
72,438,917
C++ linked list input memory not carrying over (Maybe)
I am quite inexperienced at coding so I am not sure what is going on, but I have run my code through godbolt compiler/debugger, and it says that there is a memory leak but I don't know how to solve this problem I do believe the issue is within the void end function though. GodBolt Link #include <iostream> #include <std...
For every use of new to dynamically allocate memory, you must also use delete to deallocate that memory. You have used new but not delete so you have a memory leak. When dealing with a linked list, each node links to the next. The trick is that if you delete a node, you've deleted the pointer to the rest of the list, b...
72,438,610
72,438,708
std::map with custom key
I would like to use a standard map with the following custom key: struct ParserKey{ ParserKey(uint16_t compno, uint8_t resno, uint64_t precinctIndex) : compno_(compno), resno_(resno), precinctIndex_(precinctIndex...
If you don't care about the specific order and just want to satisfy the requirements for sorting, a common and simple pattern is to use std::tie with all of the class members of the compared instances, and compare those results instead. std::tie creates a std::tuple of references to the members, and std::tuple implemen...
72,438,768
72,441,795
Making guides for function template argument deduction in C++
Before anyone says that this question is duplicate... I checked the other question and that didn't satisfy me. It was not what I was looking for. Is it possible to have argument deduction guides for function templates ? If yes then how ? It will be appreciated if someone can give easy examples. Thanks in advance.
OK I got the answer actually functions can't have deduction guides. It only works with class templates. Thanks for pointing me to the right direction.
72,438,852
72,439,045
std::function vs callable as template parameter
In the example below, why line 20 causes the error described from line 27 to 30? Calling exec1 in line 33 works fine. #include <cstdint> #include <functional> #include <iostream> #include <tuple> #include <type_traits> template <typename... t_fields> void exec0(std::function<std::tuple<t_fields...>()> generate, ...
Even though you specified <uint32_t> as a template argument, the compiler seems to try to deduce more elements for the parameter pack, fails to do so (because the type of a lambda is not std::function<...>), and becomes upset. You need to somehow inhibit template argument deduction. Either call it as exec0<uint32_t>({_...
72,439,654
72,440,114
C++ adding string and int
I have been tasked to rewrite a small program written in C++ to C#. But I came across this line that I couldn't understand fully. Is it concatenating the string length to the string or the pointer? int n = _keyData * int(*(int*)(_chap + strlen(_chap) - 4)); This is the variables: short _ver = 12; short _keyData = shor...
*(int*)(_chap + strlen(_chap) - 4) is a strict aliasing violation. Reinterpreting raw bytes as an int is type punning and is not allowed in C++ (even though some compilers tolerate it). To fix it (assuming a little-endian system), you can rewrite it like this: short _ver = 12; short _keyData = short(_ver * _ver); char ...
72,439,702
72,439,840
CMake & C++ : linker error : undefined reference to function
I am trying to compile a simple C++ program with CMake, but I am getting a linker error : [2/2] Linking CXX executable bin/MY_PROGRAM FAILED: bin/MY_PROGRAM : && g++ -g CMakeFiles/MY_PROGRAM.dir/src/main.cpp.o -o bin/MY_PROGRAM && : /usr/bin/ld: CMakeFiles/MY_PROGRAM.dir/src/main.cpp.o: in function `main': /home/user...
The first sentence in the manual link_libraries Link libraries to all targets added later. You use this directive after the target MY_PROGRAM is added - the target MY_PROGRAM is added prior link_libraries. Prefer use target_link_libraries(MY_PROGRAM MY_LIBRARY) - other targets can require different dependencies and i...
72,440,057
72,440,324
C++ chrono: How do I convert an integer into a time point
I managed to convert a time point into an integer and write it into a file using code that looks like the following code: std::ofstream outputf("data"); std::chrono::time_point<std::chrono::system_clock> dateTime; dateTime = std::chrono::system_clock::now(); auto dateTimeSeconds = std::chrono::time_point_cast<std::ch...
You have some strange conversions and assign to a variable that you don't use. If you want to store system_clock::time_points as std::time_ts and restore the time_points from those, don't involve other types and use the functions made for this: to_time_t and from_time_t. Also, check that opening the file and that extra...
72,440,193
72,448,375
Undefined reference grpc and protobuf error - C++
I am writing a grpc communication code between two entities, matchmaker and host. My makefile looks as below: CXX = g++ LDFLAGS += `pkg-config --cflags --libs protobuf grpc grpc++`\ -lgrpc++_reflection\ -ldl host: comm hosts/host.cc hosts/host.h $(CXX) $(LDFLAGS) hosts/host.cc build/matchma...
You need to move the $(LDFLAGS) until after the object files that depend on it: host: comm hosts/host.cc hosts/host.h $(CXX) hosts/host.cc build/matchmaker.grpc.pb.o build/matchmaker.pb.o -g -o build/host $(LDFLAGS)
72,441,174
73,968,626
AWS Gamekit - Could not create resources Identity And Authentication feature
I am new to AWS Gamekit as I am trying to create the resource Identity and Authentication but it gives me this Error in Unreal Engine: LogAwsGameKit: Display: [@22920]~ Plugin settings file loaded from C:/Users/najb1/OneDrive/Documents/Unreal Projects/MyProject2/myproject2/saveInfo.yml LogAwsGameKit: Display: [000001F4...
I just got this using eu-west-2 (yours looks like us-east-1). Changed the environment region to us-west-2 (or try whichever else) and there were no problems. Also, noticed in aws GameLift they don't offer matchmaking in certain regions, etc., so keep these region limitations in mind.
72,441,275
72,442,063
segmentation fault when try reading binary file using overloaded operator >>
I am trying read a binary file which was created with code like that: #include <list> #include <string> #include <bitset> #include <fstream> struct Node { char data; int frequency; friend std::istream& operator>>(std::istream& input, Node& e) { input.read(&e.data, sizeof(e.data)); input.read(reinterpret...
You have a typo in your Node::operator>>. When reading e.frequency, you are missing a &: input.read(reinterpret_cast<char*>(&e.frequency), sizeof(e.frequency)); ^ That was a typo in my previous answer where you got this code from. I have corrected that mistake. With that said, I see...
72,441,329
72,441,631
TPMT_PUBLIC Serialize to other Format file?
[a similar questions link][1] [1]: https://stackoverflow.com/questions/60340870/serialize-tpm-public-key-to-der-or-pem But,I don't Know how to do that,using botan to covert data. TPMT_PUBLIC ===> PEM
TPMS_RSA_PARMS *rsaParms = dynamic_cast<TPMS_RSA_PARMS*>(&*persistentPub.outPublic.parameters); if (rsaParms == NULL) { throw domain_error("Only RSA encryption is supported"); } TPM2B_PUBLIC_KEY_RSA *rsaPubKey = dynamic_cast<TPM2B_PUBLIC_KEY_RSA*>(&*persistentPub.outPublic.unique); auto rsaPublicKey = Botan::...
72,441,818
72,442,751
CMake cannot link executable -ljsoncpp: no such file using github submodules
I am working in a project which uses jsoncpp for parsing and cmake for compilation. I added the jsoncpp official git repository as a submodule to my project with git submodule add REPO_URL external/jsoncpp, so as to keep every dependency together. When running cmake -B out/build, it works normally. But when I do make, ...
The jsoncppConfig.cmake defines property INTERFACE_INCLUDE_DIRECTORIES for targets jsoncpp_lib and jsoncpp_lib_static. You need to query the target property and set it manually: get_target_property(JSON_INC_PATH jsoncpp_lib INTERFACE_INCLUDE_DIRECTORIES) include_directories(${JSON_INC_PATH}) Linking is done via: targe...
72,441,942
72,442,369
Keep track of boolean variable when class is called
I have a class named Colorblind which has getter and setter methods for a boolean variable called bool toggleColorBlind = false. I have multiple other classes such as Menu which a user can toggle the boolean variable and set it to true. When I try to get the variable from another class, like Game, the boolean variable ...
If you goal is to share the same toggleColorBlind across all the instance of different classes like Menu and Game, then you can make toggleColorBlind a static data member as shown below. Making it a static data member would allow you use it without any instance of ColorBlind. This is because a static data member is not...
72,442,114
72,442,779
insertion at the end of linked list function not working
I don't know where I am wrong, when I debugged the code I found out that the 'new node' address is 'new node' address, basically the new node is referring to itself void insertend(struct node *parent, int item) { while (parent->addr != NULL) parent = parent->addr; struct node new_node; new_node.a =...
void insertend(struct node *parent, int item) { while (parent->addr != NULL) parent = parent->addr; struct node new_node; new_node.a = item; parent->addr = &new_node; parent->addr->addr = NULL; } The lifetime of new_node is limited to the function. Once that function returns, it is no longer ...
72,442,534
72,442,704
C++ Compile time index/tuple access for tensor
I have a compile time tensor class. Now i would like to implement index access like this: std::array<std::array<std::array<int, 3>, 2>, 1> myTensor; template <class... Indices> auto get(Indices... indices) { return myTensor[indices][...]; } int main() { myTensor[0][1][2] = 3; std::cout << get(0, 1, 2) << ...
You cannot fold over [] (for multidimensional indexing). You can achieve this with a pair of functions: // This is written as generically as possible, but can be // pared down by removing forwarding in your use case template <class Container> constexpr decltype(auto) get_of(Container&& c) noexcept { return std::for...
72,442,797
72,442,872
Why this code is printing "YES" infinite number of times while it should have printed "NO" one time
for s="0" and k=20 this code is printing YES infinite number of times but the for loop condition (0<=1-20) is not true. it should print NO. Please help me. #include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; int k; cin>>k; for(int i=0;i<=s.size()-k;++i){ cout<<"YES...
The short answer is: unsigned integer underflow. To see it more clearly, let's assign the values to variables of type size_t (which is the type that s.size() returns): const size_t ssize = s.size(); const size_t ssize_minus_k = ssize-k; cout << "ssize=" << ssize << " ssize_minus_k=" << ssize_minus_k << endl; for(int i...
72,442,899
72,443,651
c++ template structure about iterator_traits
I'm studying about iterator and I found some source code on github. I realize what this code do but cannot find how. template <class T> struct _has_iterator_category { private: struct _two { char _lx; char _lxx; }; template <class U> static _two _test(...); template <class U> ...
First thing first, this code is completely interpretable on it's own, if you know C++. No documentation on external components is required. It's not depending on anything. You have asked questions which suggest some gaps in basic C++ syntax understanding. 1. Template definition _test is a template member of class templ...
72,444,600
72,444,739
Remove strings that contain digits and convert others in upper case and separate them with comma
I've almost finished this task but have a little trouble in result. Here's the problem description: Given a vector of strings, please implement the following 2 functions to process and output it: process(): remove strings that contain digits and convert others in upper case output(): print the strings and separate th...
Sometimes, good old syntax is a good thing. void output(std::vector<std::string>& v) { // clean array size_t n = v.size(); while(n--) if(v[n] == '\0') v.erase(v.begin() + n); // print words for(size_t i = 0; i < v.size(); ++i) { std::cout << v[i]; if(i < (v.size() - 1) std...
72,444,766
72,444,949
Is there a way of creating a shorthand map to be passed to a function in C++?
I wonder if there is a way of constructing a temporary map to be passed so that the following implementation is possible: void func(map<string,int> & input) { cout << input["m1"] << endl; cout << input["m2"] << endl; } func ( map<string,int>{{"m1",1},{"m2",2}} ; // causing error when compiled
The problem is that you're trying to bind an rvalue expression to an lvalue reference to non-const std::map. To solve this you can add a low-level const in the parameter and use std::map::find as shown below: void func(const std::map<string, int>& input) { auto it1 = input.find("m1"); if(it1!=input.end()) ...
72,444,998
72,445,228
Preprocessing multiple source files with one command using g++
Question I have three files in my current working directory: hello.cpp goodbye.cpp prog.cpp I would like to only preprocess hello.cpp and goodbye.cpp and dump the output in files hello.i and goodbye.i. Is there a way to achieve this using g++ in a Ubuntu Linux command line using one command? The reason I would like t...
You can use a pattern rule so Make knows how to generate a .i file from a .c file: %.i: %.cpp g++ -E -o $@ $< and then if your makefile ever requires hello.i, Make will know that it can use the command g++ -E -o hello.i hello.cpp E.g. if you have all: hello.i goodbye.i and run make all it will know that it needs h...
72,445,056
72,487,420
How to compose a string literal from constexpr char arrays at compile time?
I'm trying to create a constexpr function that concatenates const char arrays to one array. My goal is to do this recursively by refering to a specialized variable template join that always joins two const char*'s . But the compiler doesn't like it and throws an error message that I can't get behind. I've already check...
As alternative, to avoid to build the temporary char arrays, you might work with types (char sequences) and create the char array variable only at the end, something like: constexpr auto size(const char*s) { int i = 0; while(*s!=0) { ++i; ++s; } return i; } template <const char* S, type...
72,445,523
72,463,675
How to use an executor from a boost::asio object to dispatch stuff into the same execution thread?
Ok, I don't have enough code yet for a fully working program, but I'm already running into issues with "executors". EDIT: this is Boost 1.74 -- Debian doesn't give me anything more current. Which causes problems elsewhere, but I hope it had working executors back then as well :-) Following one of the beast examples, I'...
Post, defer and dispatch are free functions: boost::asio::dispatch(resolver.get_executor(), function); Live: http://coliru.stacked-crooked.com/a/c39d263a99fbe3fd #include <boost/asio.hpp> #include <iostream> struct Test { Test(boost::asio::any_io_executor executor) : resolver(executor) {} void doSomething() { ...
72,445,583
72,583,056
Why pragma comment(linker,"/export ...") unresolved external symbol
The header file just like below #define CoverWinAPI extern "C" __declspec(dllexport) CoverWinAPI BOOL RunDll(); CoverWinAPI void ReplaceIATEntryInOneMod(PCSTR pszCalleeModName,PROC pfnCurrent,PROC pfnNew,HMODULE hmodCaller); #pragma comment(linker,"/export:MyCreateWindowExW=_MyCreateWindowExW@48") CoverWinAPI HWND ...
The problem you encountered is due to the way function names are decorated by the compiler. _MyCreateWindowExW@48 is a x86-style decorated name, valid for x86 build only, its x64 counterpart is simply MyCreateWindowExW (x64 has only one calling convention which resembles __cdecl in that the caller is the one responsibl...
72,445,864
72,446,064
how to reduce the amount of functions that defines pointer function
i'm implementing some pointer functions/Callbacks in my code as follow: typedef WndDyn* (Edit_t)(Point2d* pThis, const EditParams& EditParams); Edit_t g_Edit_CB{ nullptr }; typedef WndDyn* (*Show_t)(const Point2d* pThis, const EditParams& EditParams); Show_t g_Show_CB{ nullptr }; // Punkt3d typedef WndDyn* (*Edit3d_t)(...
Since C++11 (which I assume you have available as you're using nullptr), you can use an alias template: template <typename T> using EditParamsCallback_t = WndDyn* (*)(T, const EditParams&); int main() { using Edit_t = EditParamsCallback_t<Point2d*>; Edit_t g_Edit_CB{nullptr}; using Show_t = EditParamsCall...
72,446,085
72,446,833
VSCode - autocomplete for loops
I used to write C code with Visual Studio, and whenever I wrote "for" and then pressed TAB, it was automatically completed to an entire for loop, i.e. for (size_t i = 0; i < length; i++) { } Is there a way to enable that in VSCode as well? Even by using some extension? Thanks!
Is there a way to enable that in VSCode as well? Yes, you can add snippets and customize them according to your needs if the corresponding snippet is not already available, as shown below for the for loop shown in your question. Step 1 Go to Files -> Preferences -> User Snippets Step 2 After clicking on the User Sni...
72,446,418
72,469,460
Flutter Xcode Error Undefined symbol: _MDFInsetsFlippedHorizontally and Undefined symbol: _MDFRectFlippedHorizontally
I am struggling with these for days. Searching for answers online but still to no avail. Details of the error: List of pod files: (I assume this is related to MDFInternationalisation?) This is my code in podfile: # platform :ios, '9.0' # CocoaPods analytics sends network stats synchronously affecting flutter build l...
After trying out multiple solutuions, this is my solution. Simply add this pod 'MDFInternationalization','~>2.0 to your podfile, nothing more. There are some solutions on the internet that require us to change post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_setti...
72,446,709
72,447,648
Accessing modelData inside nested delegates
I have a scenario where in I need to access the modelData inside a repeater which part of a listview's delegate. I am unable to differentiate between listview's modelData and Repeater's modelData. ListView { id: listViewData model: listViewData //here listViewData is QObjectListModel delegate: ColumnLa...
You can bind the outer model data to some delegate property to create a kind of alias, for example: Column { spacing: 5 Repeater { model: ["A","B","C"] delegate: Row { spacing: 5 property var storedValue: modelData Repeater { model: ["1","2","3...
72,447,160
72,454,370
ASIO: Is it defined behavior to run a completion handler in a different thread?
In the following example, the timer was associated with the io_context executor. But then, the handler is told to execute in the thread-pool. The reason is, because the handler actually executes blocking code, and I don't want to block the run function of the io_context. But the documentation states Handlers are invok...
First things first. You can run a handler anywhere you want. Whether it results in UB depends on what you do in the handler. I'll interpret your question as asking "Does the observed behaviour contradict the documented requirements/guarantees for handler invocation?" Does This Contradict Documentation? It does not. You...
72,447,454
72,514,888
Failed to receive UDP stream using OpenCV GStreamer
I am trying to transmit RGB raw data over the network via UDP and on the receiving side, I want to do some image processing on the data using OpenCV C++. Sender Pipeline gst-launch-1.0 -v k4asrc serial=$k4a_serial timestamp-mode=clock_all enable-color=true ! rgbddemux name=demux demux.src_color ! rtpvrawpay ! udpsink h...
SOLVED after several tries. Hope it helps someone else. I reinstalled everything. Built another version of OpenCV and it's working as expected. Also had to change the Pipeline a bit to add all the CAPS information. Sender Pipeline gst-launch-1.0 -v k4asrc serial=$k4a_serial timestamp-mode=clock_all enable-color=true ! ...
72,447,518
72,448,542
Print all subarrays in less than O(n^3) time complexity
To print all the subarrays (contiguous subsequences) of a given array, one requires three nested for loops. Is there a way to reduce the time complexity of O(n^3) using map in C++ STL? #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio (false); cin.tie(NULL); cout.tie(NULL); vector<int>...
If you must iterate all elements then you must iterate all elements... No further reduction possible. Reducing time complexity is all about finding ways in which you don't need to iterate all elements.
72,447,590
72,447,697
Perform different actions with predefined probability based on random value between 0 and 99
I'm working on a project where I run actions randomly with a certain probability. I basically have four actions. Action A has a probability of 40%, Action B has a probability of 40%, Action C has a probability of 15% and Action D has a probability of 5%. My approach was to generate a random number (int) between 0 and 9...
It actually depends on the source of random(int) function, you are not showing on your question, but I think your problem is more math-related than C++-related, if actually random(int) is uniform between 0 and 99 included. How many are >=59? I am quite sure there are 41, not 40, therefore you are giving a probability e...
72,447,643
72,528,311
In C++, (how) can I make a local variable available in other classes during the lifetime of this variable
I am writing a DLL that does chemical calculations. At the entry point (let's say a method called entryPoint()), I get the number of chemical components (componentCount) participating in the reaction and their input concentrations as an array with length componentCount. To define the reactions, I use a Component enum, ...
So, I came up with my own solution, in case anyone is interested: I created a LifetimeScope class, which can be used to initialize temporarily scoped Singletons and looks as follows: class LifetimeScope { public: LifetimeScope() = default; LifetimeScope(const LifetimeScope&) = delete; LifetimeScope(LifetimeScope&...
72,447,710
72,448,195
override malloc and new calls in cpp program
I want to call my custom malloc/new calls instead of standard library functions. 1. for malloc, I have this short program #include <stdio.h> #include <stdlib.h> void *__real_malloc(size_t size); void *__wrap_malloc(size_t size) { void *ptr = __real_malloc(size); printf("malloc(%ld)...
Why does g++ not work with -Wl,--wrap,malloc? g++ is for C++, and C++ ABI is different from C ABI. So you need to add extern "C" around __real_malloc and __wrap_malloc: extern "C" { void *__real_malloc(size_t size); void *__wrap_malloc(size_t size) { void *ptr = __real_malloc(size); printf("malloc(%ld) = %p\n", si...
72,447,799
72,448,115
Emplacing an instance with constant fields fails to compile (C++)
I have an example_class with two constant fields. When I try to emplace an object of that class into a std::vector, I get various errors such as "error: object of type 'example_class' cannot be assigned because its copy assignment operator is implicitly deleted". Does anyone know what is going on here? If I remove the ...
By trying to use the std::vector<T>::emplace in this case we get something like: error: use of deleted function ‘Foo& Foo::operator=(Foo&&)’ which follows from the fact that... ...if the required location (e.g. vec.begin()) has been occupied by an existing element, the inserted element is constructed at another locati...
72,448,497
72,450,520
JVMTI Invoke toString(); on an Java object from C++ code
So, I was trying to invoke the toString(); method on an object (in this case an enum). This immediately crashed my application. I am assuming that, since the toString(); method isn't declared directly in the enum but inherited from the Object class (Enum in this case) it is not able to find the method and therefore cau...
I have been experimenting a bit, and now that I found a solution it makes sense why it didn't work. Instead of trying to find the toString() method in the class directly, I passed the class found at the classpath of java/lang/Enum (or java/lang/Object for non-enum types) to the getMethodID() function. jmethodID method ...
72,448,770
72,448,850
C++ get and set item in map as value inside unordered_map?
std::unordered_map<string, tuple<int, vector<int>>> combos; I want to retrieve items inside tuple and also to increase or set their value. e.g. if(v_intersection.size()==5){ string stringval = join(v_intersection, ","); if (combos.find(stringval) == combos.end()) // if key is NOT presen...
std::get(std::tuple) is a free function that takes a tuple as parameter. So you have to call it like so: get<INDEX>(some_tuple). Knowing this, answering your question is just a matter of passing the tuple from the map to that function. I want to set int (the first parameter of tuple) to 1 std::get<0>(combos[stringval...
72,448,817
72,449,889
C# Matrix4x4 equivalent of DirectX::XMMatrixPerspectiveLH
I was trying to port some c++ code to C#, everything works except the perspective. In c++ the code looks like this, which worked without distortion. DirectX::XMMatrixTranspose( DirectX::XMMatrixRotationZ(100) * DirectX::XMMatrixRotationX(200) * DirectX::XMMatrixTranslatio...
The perspective matrix you use appear strange. I suggest you to use the more classical implementation from OpenGL documentation. Also, notice that you don't explicitly set the M44 value of your perspective matrix to 0.0f while this value is set to 1.0f for default identity matrix. This result in a wrong perspective mat...
72,449,160
72,449,192
How to pick up a random value from an enum class?
hello, Been recently into C++ (C++14 to be precise), and I'me trying to get my way with enums, still have a bit of trouble figuring things out Currently, trying to get a random value from an enum class that was constructed as such: enum class Niveau { #define NIVEAU_DEF(NOM,VALEUR) NOM = VALEUR, #include "niveau.de...
Since you have a XMacro already, you can just reuse it to create an array of the values and pick from it: const Niveau niveau_vals[] = { #define NIVEAU_DEF(NOM,VALEUR) Niveau::VALEUR, #include "niveau.def" #undef NIVEAU_DEF }; In newer versions of the language, you can make it a nice constexpr with std::array. c...
72,449,410
72,449,983
Using FRIEND_TEST to test private functions of a class in another namespace
I'm trying to use GTest's FRIEND_TEST() macro to enable testing of some private functions from another namespace. However, I can't get past some errors, though I must be missing something simple. I have Tests.cpp where I would like to test private functionality of MyClass: namespace a::b::tests { class MyTests : pu...
Turns out I had to do forward declarations like this, in MyClass.h: namespace a::b::tests { class MyTests; class MyTests_Test1_Test; } namespace a::b { class MyClass { private: FRIEND_TEST(a::b::tests::MyTests, Test1); ... }; }
72,449,667
72,458,204
How to get an image char array by using libpng?
Although I have successfully utilized stb_image/CImg/lodepng open source to get a char array, the memory usage is too huge that I can't implement it in a low power embedded system. Therefore, I try to use libpng to read a png type image, and get a char array. However, I am completely not familiar with libpng...... Anyo...
I successfully use libpng to get a char array. However, the memory usage is up to 915.1KB which is higher than stb_image !!! (Use Valgrind) Ah... Could anyone tell me some directions to optimize the memory usage? unsigned char* read_png_file(const char *filename) { FILE *fp = fopen(filename, "rb"); png_byte bi...
72,450,588
72,450,631
co_await inside catch no longer compiling with GCC12
I have a code that looks like this: auto func() -> asio::awaitable<void> { try { co_await async_operation(); } catch(boost::system::system_error const& e) { co_return co_await another_async_operation(); } } This code worked perfectly with GCC 11, but with GCC 12 it won't compile: file.cpp:3...
This is explicitly forbidden in [expr.await]/2: An await-expression shall appear only in a potentially-evaluated expression within the compound-statement of a function-body outside of a handler ([except.pre]). The error message here is pretty clear: you can't await in an exception handler. That it compiled before is ...
72,450,718
72,450,949
Store pointers to copies of the parameter pack in a tuple
I want to store pointers to copies of parameter pack arguments in a tuple. Here is the code: struct FDead {}; struct FAlive {}; struct FBossDead final : FDead {}; struct FBossAlive final : FAlive {}; template<typename... TStates> struct TContext { using FTuple = std::tuple<TStates*...>; template<typename...
You don't need a fold expression here. A regular parameter pack expansion will do the trick just fine. Also, while not strictly necessary for your example as posted, using std::forward<> when dealing with Forwarding References (which InStates is) is a good habit to get into. States = FTuple{ new TSubStates{ std::forwar...
72,450,903
72,451,102
vector<unique_ptr<Base> > using initialization list of Derived
I have a follow-up question to this one: vector<unique_ptr<A> > using initialization list I would like to achieve essentially the same goal as in the referenced question, but this time using polymorphic classes. That is, I would like to create a std::vector<std::unique_ptr<Base>> using an initialization list. #include ...
Adding extra constructor template <typename U> movable_il(U&& in): t(std::forward<U>(in)) {} fixes compilation. Demo.
72,451,130
72,451,307
Why don't we add parenthesis when writing comparator in c++?
Here is a code explaining what I mean. static bool comparator(int a, int b) { if(a > b) return false; return true; } sort(arr.begin(), arr.end(), comparator); // why don't we write comparator()
If you will write sort(arr.begin(), arr.end(), comparator()); then it means that the argument expression of the function std::sort comparator() must be evaluated. But neither arguments are supplied to the function call comparator(). So the compiler will issue an error message. On the other hand, if you will write sort...
72,451,615
72,451,785
Is function trailing return type evaluated when requires clause fails
Simple code as below or as on godbolt doesn't compile with clang but compiles fine with gcc and Visual Studio. The trailing return type decltype(foo(t)) of baz(T t) is not evaluated when SFINAE fails with clang, gcc and Visual Studio. However, the trailing return type decltype(foo(t)) of bar(T t) is still evaluated whe...
This is CWG 2369, which clang does not appear to implement yet. The example in that issue (which can now be found in [temp.deduct.general]/5) doesn't compile on clang, but does on gcc. template <class T> struct Z { typedef typename T::x xx; }; template <class T> concept C = requires { typename T::A; }; template <C T>...
72,451,826
72,452,056
C++ pass a non const string by reference with default value
So I am working on a codebase where this someFunc is called at a lot of places and I can't afford to change it by adding this new variable at all places where this function is called. And that too when that variable is not needed at all the place where someFunc is called. So I have a requirement where I need to have a ...
You can get the equivalent behavior that you are describing by using a separate overload instead of a default value: class ClassName { public: ExceptionClass someFunc(int a, float b, map<int, string> c, string &d); ExceptionClass someFunc(int a, float b, map<int, string> c) { string d = ""; return someFunc(...
72,452,428
72,452,488
c++ structured bindings: What is the standard order of destruction?
Is there any definition of the order of destruction of objects returned from a method that can be put into a structured binding statement? cppreference doesn't seem to mention destruction order, and a quick test on godbolt reveals something other than what I expected. #include <iostream> #include <tuple> struct A{ ...
Structured binding changes absolutely nothing about the language in terms of order of construction/destruction. Structured binding is a fiction, a linguistic shorthand that turns get<I>(unnamed_object) or unnamed_object.some_name into some_name. In this fiction, unnamed_object is the actual object which is generated by...
72,452,681
72,452,682
Copyable C++ coroutine with data
I have written a forward iterator that iterates over the nodes of a graph in order of a (preorder/postorder/inorder) DFS spanning tree. Since it is quite complicated compared to writing a simple DFS and calling a callback for each encountered node, I thought I could use C++20 coroutines to simplify the code of the iter...
I figured that, with the Miro Knejp "goto-hack", something resembling copyable co-routines is possible as follows (this toy example just counts "+1" "*2" until a certain value but it illustrates the point). (1) this is just a simple wrapper for the actual function template<class Func, class Data> struct CopyableCorouti...
72,453,622
72,453,783
the child class always have access to the public members of its parent, why and how it is possible?
why does a child class have access to members of a parent class? and why parent class cannot access the members of child class? I was preparing for my exams and saw this reasoning question in one of my past papers. this seems quite vague to me , I was confused what will be the proper answer to this question. it will be...
Using public inheritance, your derived class will have access to protected and public fields and methods declared in the base class. However, your base class doesn't know about your derived class at all. Inheritance only works one way. You basically extend the functionality of a class. You can think of it as putting a ...
72,453,646
72,453,704
Does delete delete every element in a vector and free the memory?
vector<int>* v = new vector<int>; for (int i = 0; i < 100; i++) { (*v).push_back(i); } delete v; Do I delete every element of the vector and free the memory? If not how do I free the memory?
An allocating new expression allocates memory, constructs a dynamic object into that memory, and returns a pointer to that object. When you pass such pointer to delete, the pointed object is destroyed and the memory is deallocated. When an instance of a class, such as a vector is destroyed, its destructor is called. Th...
72,453,747
72,453,776
how to swap arrays without copying elements
I'd like to swap two integer arrays without copying their elements : int Z1[10],Z2[10]; std::swap(Z1,Z2); // works //int *tmp;*tmp=*Z1;*Z1=*Z2;*Z2=*tmp; // doesn't work [ expressions involving Z1,Z2 ] In the third line I commented out what I tried and didn't work Is there a way to do this by swapping pointers instea...
how to swap arrays without copying elements By virtue of what swapping is, and what arrays are, it isn't possible to swap arrays without copying elements (to be precise, std::swap swaps each element and a swap is conceptually a shallow copy). What you can do is introduce a layer of indirection. Point to the arrays wi...
72,454,299
72,459,974
Why does static_cast of an enum class stored in a bit-field change the result?
Given an enum class stored in a bit-field: #include <cstdint> #include <iostream> enum class Orientation: uint8_t { NORMAL = 0, CLOCKWISE = 1, ANTICLOCKWISE = 2 }; inline Orientation operator+(const Orientation& lvalue, const Orientation& rvalue) { switch(lvalue) { case Orientat...
With G++8.4, the assembly code for Puzzle.checkPolarity() is: Puzzle::checkPolarity() const: push rbp mov rbp, rsp mov QWORD PTR [rbp-8], rdi mov rax, QWORD PTR [rbp-8] movzx eax, BYTE PTR [rax] and eax, 3 mov edx, eax mov rax,...
72,454,890
72,455,025
Assembly showing a lot of repeating code?
So I'm working on some binary to assembly to c++ code. It's for a project. When I disassemble the binary I'm getting a lot of repeating assembly code and I'm not sure what it's doing. It's almost like it's just pointing it's way down. 0x0000000000000000 <+0>: push %rbp 0x0000000000000001 <+1>: mov %r...
So the repeating code is the "lea" and "callq". The addresses suggest that you are disassembling .o file, not an executable (you should always show the command you used when asking about its output). Try objdump -dr foo.o instead -- the picture should become much clearer. P.S. GDB isn't really the right tool for look...
72,454,912
72,455,210
vector is returning a size() of 0
I am new to C++ programming and I am having trouble with the following code: #include <iostream> #include <vector> using namespace std; class Absolute { public: vector<int> nums; Absolute(vector<int> nums) { nums = nums; //<--- this size is not 0 } vector<int> getN...
In this code: Absolute(vector<int> nums) { nums = nums; } You encounter what I call "Highlander's Law" (There can be only one). In this function, nums refers to the parameter nums, not the member nums. The member nums is shadowed, hidden, by the parameter. So nums = nums; means assign the parameter to itself. The...
72,455,343
72,455,849
Unable to get a jstring from R.string.* via JNI in a native C application
I'm working on a native c/c++ app, that uses string resources via the strings.xml file. Attempting to use AAssetManager to load the "strings.xml" file, has no effect. Returns the same error I've tried looking for various other implementations, but none have worked Android API level (Project): 25 Android API level (Dev...
You're looking for it in the wrong way. The value at R.string.some_string isn't the string itself- it's an integer that references the string. To get the actual string, you need to call Context.getResources().getString(), passing in the id you want to getString. It's set up this way for resource localization. The R...
72,456,118
72,907,523
Why does clang give a warning: unterminated ‘#pragma pack (push, …)’ at end of file?
I create a main.cpp in my vscode with clangd enabled, and put the following code in it. clangd warns the first line with the warning message: warning: unterminated ‘#pragma pack (push, …)’ at end of file The whole content of main.cpp: #pragma pack(push) // warning on this line #pragma pack(1) struct A { int a; ...
This is a known bug in clangd, tracked in https://github.com/clangd/clangd/issues/1167. Please see that issue for an explanation of why this currently happens and a potential workaround.
72,456,580
72,458,056
Broadcasting Row and Column Vector in Eigen C++
I have following Python Code written in NumPy: > r = 3 > y, x = numpy.ogrid[-r : r + 1, -r : r + 1] > mask = numpy.sqrt(x**2 + y**2) > mask array([[4.24264, 3.60555, 3.16228, 3.00000, 3.16228, 3.60555, 4.24264], [3.60555, 2.82843, 2.23607, 2.00000, 2.23607, 2.82843, 3.60555], [3.16228, 2.23607, 1.41421, ...
I think the easiest approach (as in: most readable), is replicate. int r = 3; int len = 1 + 2 * r; const auto& squared_yx = Eigen::ArrayXf::LinSpaced(len, -r, r).square(); const auto& bcast = squared_yx.replicate(1, len); Eigen::MatrixXf mask = (bcast + bcast.transpose()).sqrt(); Note that what you do is num...