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
65,338,769
65,340,252
ReadProcessMemory entire process
I'm trying to read an ENTIRE process with ReadProcessMemory but for some reason no matter what, trying to read at low addresses causes the function to fail. For example, if I'm reading from a process, I can access areas of its memory without a problem. But the lower addresses of the process, like 0, can't be accessed a...
Some memory pages are intentionally set to unreadable, especially the first page, because that detects a lot of programming errors. You can determine if you are able to read the memory page in another process with VirtualQueryEx. To determine the size of the memory page use GetSystemInfo. You have to read the memory pa...
65,339,329
65,339,686
Getting some errors when trying verify the code ([-Waggressive-loop-optimizations]) (only relevant channels are overridden)
Im trying to make Balancing Robot with this code https://github.com/mahowik/BalancingWii and i saw many tutorial video on this project and same code ,but no one get this error while verify the code in Arduino IDE so i thought the problem not in the code but in something on me. i tried an old version of Arduino IDE (1.6...
This error occurs because the index chan (which runs up to RC_CHANS) is larger than the size of array rcSerial (which is 8). The section around the erroneous line checks if (chan<8, but it is commented out. I guess you can add it back and see if the code works then.
65,339,382
65,339,443
How to load characters from a text file (maze) into a data structure to operate on later?
I have a text file which contains the details of a maze. First i'd like to take the text file and load it into some sort of data structure. I first thought i'd use a 2d array as it represents a 2d maze pretty well however i'm leaning more towards a vector due to the extra funtionality provided. The reason I want to loa...
You can read the file line by line: for (std::string line, std::getline(file_stream, line);) { vector.push_back(line); } And if you want to iterate over every character, you can use for-range-loop (C++11): for (const auto& line : vector) { for (const auto one_char : line) { } }
65,339,420
65,339,513
Extra line is coming as output in c++
int main() { string n; int number_of_test_cases; cin>>number_of_test_cases; for (int i = 0; i <= number_of_test_cases; i++) { getline(cin,n); for (int p = 0; p < n.size(); p++) { if (p%2==0){ cout<<n[p]; } }cout<<" "; for (int p = 0; p < n.size(); p++) { if (p...
Use cin.ignore() after scanning the integer before using getline function. Also the condition in your for loop should be i < j.
65,339,424
65,341,234
How to add button in wxRichToolTip, wxWidgets?
I have created a tooltip using wxRichToolTip, but I am unable to figure how to customize it. Like I want to add button in the tooltip. Here is my code. wxRichToolTip tip("Caps Lock is on", "You might have made an error in your password\n" "entry because Caps Lock is turned on.\n" "\n" "P...
wxRichToolTip doesn't support buttons, you will need to implement your own popup window class if this is what you need. You may find the generic, i.e. written using wxWidgets API instead of native API, implementation of wxRichToolTip in src/generic/richtooltipg.cpp useful as an inspiration for your version.
65,339,464
65,339,959
Optimize (recompile) inherit virtual methods for each derived class
Let's say we have a "master" class with a method called "Bulk" to perform N interactions over a virtual method. This virtual method may be overridden by many classes but only once. For performance reasons we have to minimize the cost of calling/vtable resolution as much as we can. (Example: ++10Gb network packet genera...
I am not really understanding your question ;) However, I suggest to avoid virtual dispatch when you want no virtual dispatch instead of trying to optimize around the virtual table (which is an implementation detail, hence optimizations wont be portable). Maybe CRTP is an option. Just in case you want to use derivedX p...
65,340,070
65,344,796
Eclipse and OpenCV termination error + Solution
I had a problem last days with Eclipse and OpenCV that prevented the pictures from being displayed. I could compile the code, generate the binaries and exe files, everything was ok, but when running the code (which should read a picture form the desktop, process it, and finally show it) nothing happened, and I got a te...
The issue was solved by adding the bin file of both ...\mingw_w64\mingw64\bin ...\opencv\release_eclipse\install\x64\mingw\bin to the environment path of eclipse found under: Run Configuration --> Environment --> add: Name PATH Variable C:\mingw_w64\mingw64\bin;D:\opencv\release_eclipse\install\x64\mingw\bin C: and D: ...
65,340,392
65,341,377
Struct functions won't work as expected if there are more than 2 elements
I have a struct named ImAnimstate, which contains 3 float values. And i have a map that contains a widget's id and an ImAnimstate std::map <int, ImAnimstate> menuAnimations; It works perfectly fine if there is only 1 widget, but if i create more than one the startAnim and startAnimDown functions does not work properly...
The problem is here: auto animHandle = menuAnimations.at(id); That will create a copy of the ImAnimstate object. It is essentially equal to: ImAnimstate animHandle = menuAnimations.at(id); You can modify the copy as much as you want, but the original inside the map will never be modified. To solve the problem you sho...
65,340,599
65,340,747
Why does dlsym fail to find a function in a dynamically loaded library?
Following this answer to the question about compiling additional code at runtime in C or C++ I prepared this main program #include <dlfcn.h> #include <stdlib.h> #include <iostream> using namespace std; int main() { // create library system ( "/usr/bin/gcc -fPIC -shared test.cpp -o libtest.so" ); // load ...
The solution is rather simple: Use C language linkage for exported symbols. Then they won't be mangled: extern "C" void test() { std::cout << "TEST" << std::endl; }
65,340,777
65,340,874
Why does my code not display updated dates?
Okay so what this program is supposed to do is display the date in M/D/Y format and for some unknown reason it always displays 1/1/1. I have been skimming through this the past 40 mins and still can't understand where I went wrong. Please help me out. Needmorewordstopostthissssssssssssssssssssssssssssssssssssssssssssss...
In your code, the getter is not returning the class member variables rather the local variables delared. int Date::getMonth(){ return month; } int Date::getDay(){ return day; } int Date::getYear(){ return year; } Make the getters like this to return the actual member value.
65,340,784
65,341,217
Unused variable warning even when explicitly using it inside IF statement
I am trying to create (using C++17) a simple debug header that only executes some lines of code if the flag LOGGER_DEBUG_MODE is enabled. This is how my header is defined (I also tried using { x; } instead of x but the warning persists): debug.h #ifndef _HDEBUG #define _HDEBUG static bool LOGGER_DEBUG_MODE = ...
You have a header that defines a static bool LOGGER_DEBUG_MODE =true;. If you include that header in multiple C++ files then each file will gets its own copy of that bool. In your main.cpp you aren't using R_DEBUG so the copy of that bool (which presumably comes from including logger_adc.h ) is indeed unused in that fi...
65,340,829
65,342,082
Palindrome Linked-list
Here's my code. The concept is to traverse the whole linkedlist by taking two pointers fast and slow ,once slow is at the middle ,will reverse the list and compare it with the second half which is fast. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode...
First of all as you can see below your reverse function returns object of ListNode type. ListNode reverse(ListNode* head) { ListNode* prev = NULL; while (head != NULL) { ListNode* nextnode = head->next; head->next = prev; prev = head; head = nextnode; } return prev; } Ho...
65,340,999
65,341,126
Esp-32 invalid conversion from 'const char*' to 'int' [-fpermissive]
Hello I have a problem with some variable conversions and a problem is that when try to compile the code a get this error message. Why couldn't it convert? I put the wtrtemp as a String tried changing it to int and float and const char same problem. the Mqtt just prints out a number from a slider. which is sent from no...
I don't have the environment to test your case, but i highly suggest if your'e trying to convert a string to int that you use atol() since the esp32 framework supports it. int x = (int)atol("550"); So in your case: wtrtemp = (int)atol(mqttFloodDuration); // The problem is here If that doesn't solve your case(can't 100%...
65,341,224
65,341,687
Return unique_ptr member variable from proxy class with operator()
I would like to make a wrapper class (in this case a not null check, but it could be other checks). Is there any way to extract member variable through operator() that would make it possible to move out the member variable. The use case is a std::unique_ptr<> This is the use case #include <memory> struct S { int x...
The compiler understands that you want to convert to a unique_ptr& (i.e Type&) just fine. The problem arises when you assign the result of that conversion to your local unique_ptr object: since its an lvalue reference, the compiler tries to invoke the copy constructor (not the move constructor, which requires an rvalue...
65,341,409
65,344,190
uint8_t buffer to cv::Mat conversion results in distorted image
I have a Mipi camera that captures frames and stores them into the struct buffer that you can see below. Once the frame is stored I want to convert it into a cv::Mat, the thing is that the Mat ends up looking like the first pic. The var buf.index is just part of the V4L2 API, useful to understand which buffer I'm using...
the picture you post has oddly colored pixels and the patterns look like there's more information than simply 24 bits per pixel. after inspecting the data, it appears that V4L gives you four bytes per pixel, and the first byte is always 0xFF (let's call that X). further, the channel order seems to be XRGB. create a cv:...
65,341,446
65,453,044
How to set a timeout for BIO_do_connect?
I found a SSL/TLS client example here, it works well. #include <stdio.h> #include <errno.h> #include <malloc.h> #include <string.h> #include <winsock2.h> #include <ws2tcpip.h> #include <openssl/err.h> #include <openssl/pkcs12.h> #include <openssl/ssl.h> #include <openssl/conf.h> void connect(const char* host, int port...
I think you should set a timeout for handshake, not connection. in your code the connection has no problem because "select" returned non-zero value. in fact BIO_do_connect does handshake after connection is available. BIO_do_connect and BIO_do_handshake are the same in header file. # define BIO_do_connect(b) BIO...
65,341,474
65,341,638
how ro interact with a program's ui using another program to preform a brute force attack?
first of all this isn't for illegal purposes. rather for educational resons. I made a program that basically ask for a username and a password and store them, and i can insert them later in a text box ui to "login". (Im using windows) now i have a second program that is suppose to perform a brute force attack by trying...
it possible (on windows) to interact with the ui of a program using another program ? and how ? Yes, this is possible. The technology to use is called UI Automation. It will work with any application that uses a UI implemented using standard windowing systems (classic Win32, Windows Forms, WPF, WinUI). It may not wor...
65,341,873
65,341,953
I can't pass template funtion to std::apply directly but I can through lambda
Based on: How do I expand a tuple into variadic template function's arguments? #include <string> #include <iostream> #include <tuple> template <typename... Args> void print_all(const Args &... args) { ((std::cout << " " << args), ...) << std::endl; } int main() { // Create a tuple auto values = s...
Behind the scences, this lambda expression [](auto &&... args) { print_all(args...); } is roughly of type: struct [unnamed] { template <typename ...Args> void operator()(Args&&...args) { ... }; }; It is a type with a templated operator(), ie overload resolution and template argument dedcution only take p...
65,342,305
65,342,368
Why does trying to print enum class in c++ give an error?
I want to print u that has km as unit enum class Unit { km, m, cm }; int main() { Unit u = Unit::km; std::cout<<u; return 0; } Why do i get an error? error: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘Unit’)
Your Unit enum is a scoped enumeration, enum class, these types of enums don't allow implicit casting. You'll have to expliticly cast if you want it to work with cout: std::cout << static_cast<int>(u);
65,342,386
65,342,595
Got a problem in C++ Code with Compile Error
I found Compile Error. Actually, It works. but I submitted this code to the site for assignment. and a site warned me that you have a problem which says "no match for ‘operator=’ (operand types are ‘Product’ and ‘’)" How could I solve this error? and where should I fix code? #include <iostream> using namespace std; st...
Invalid initialization of structures. You have to initialize, at the time of its declaration. Product A = { {"strawberry", "melon", "watermelon"}, {300, 500, 1000}}; Product B = { {"strawberry", "melon", "watermelon"}, {450, 450, 900 }}; Product C = { {"strawberry", "melon", "watermelon"}, {200, 150, 700 }}; ...
65,342,681
65,343,186
It is possible to run cmd's commands using C++ in QT app?
I am making a QT mobile app (Sailfish Os, it's made with Linux) and I need to run some processes with commands which could be run only with command line/terminal. Can I do this using QT/C++ code or I am talking about something impossible? :)
Yes it's possible, you can run Linux commands in Qt app by using QProcess. This is a small example: QProcess *system_command = new QProcess(); system_command->start("/bin/bash"); system_command->waitForFinished(500); system_command->write("ls -a\n");
65,342,697
65,343,441
segmentation fault with large number of shared_ptr
this I is my .h file: class Node { public: static void disp(const std::vector<int> &v); static size_t Node_no; Node(const std::vector<int> & initial_state); ~Node(); std::shared_ptr<std::vector<int>> val; std::shared_ptr<Node> up; std::shared_ptr<...
I think I know why this issue happens. Each futher element owns the previous element via shared_ptr. So when being deleted the first element's destructor calls the second element's destructor, then second element's destructor calls third element's destructor and so on until your stack is overflowed. To fix this you sho...
65,342,914
65,355,753
Why opencv videowriter is so slow?
Hi stackoverflow community, I have a tricky problem and I need your help to understand what is going on here. My program captures frames from a video grabber card (Blackmagic) which just works fine so far, at the same time I display the captured images with opencv (cv::imshow) which works good as well (But pretty cpu w...
-------- old - look up answer on bottom -------- Thank @Micka for the many advises, I found the right thing on the way. Using cudacodec::VideoWriter is not that easy, after compiling I was not able to use it because of this error, and even if I can make it run, the deployment PC does not have a nvidia GPU. Since I am g...
65,343,270
65,355,112
Converting Matlab code to C++ with Matlab Coder - Cell problem
I'm trying to convert a function to C++ in Matlab Coder.. There is a cell variable and while building mex it gives an error. R=cell(1,n); for i=1:wi for j=1:hi if(cin(i,j)>0) k=cin(i,j); for x=i-2*rx+1:i+2*rx-1 for y=j-2*ry+1:j+2*...
For code generation, you have to define (i.e. assign) all cell array elements prior to their use. Here R{k} is used prior to being assigned. Namely, the R{k} on the RHS of that assignment reads that element prior to it having been assigned. If you intend the elements to be empty matrices, [], then you can declare R lik...
65,343,354
65,343,854
Is there a way to set console dimensions and font size using window.h
At the start of the program I want to set width and height of window, as well as font size. I can do this manually in settings but I would like to do it in code. I wont need to resize window after its dimensions are set. This doesn't have to be in windows.h, but I'd prefer it that way.
Yes. I recommend taking a look at the win32 console API docs. In particular you can use SetCurrentConsoleFontEx to change the font, and a combination of SetConsoleScreenBufferSize and SetConsoleWindowInfo to change the console size. Make sure to read the Remarks section of SetConsoleWindowInfo for why the screen buffer...
65,343,895
65,355,310
Qt QML Access a QObject by a String
I have a Model which is exposed to the qml context property and it contains a List of Lists. These Lists are created dynamically and are then exposed to the qml context as well. Model: #include <QtCore> #include <QQmlContext> class Model : public QObject { Q_OBJECT public: Model(QQmlContext* rootContext) { ...
As minimal requirement you will have to implement a function that returns the DatedValueList on your Model class: Q_INVOKABLE DatedValueList getList(const QString& name) { return ... }; But this immediately poses a small challenge, since your data structure does not allow lookup and thus should iterate the whole dataL...
65,344,205
65,344,950
InterlockedAdd64 can't be found after adding _AFXDLL macro and clr support
I added _AFXDLL macro and got the following two errors: error C2039: 'InterlockedAdd64': is not a member of '`global namespace'' error C3861: 'InterlockedAdd64': identifier not found What is the reason and how to work around the issue? I ran into the issue while trying to add c++/clr support for DLL which uses MFC.
Looks like I'm out of luck if I want to use clr support: MSDN: _MANAGED Defined as 1 when the /clr compiler option is set. Otherwise, undefined. From winnt.h: #if !defined(_MANAGED) #if (_MSC_VER >= 1600) ... FORCEINLINE LONG64 _InterlockedAdd64 ( _Inout_ _Interlocked_operand_ LONG64 volatile *Addend, _In_...
65,344,251
65,379,446
Embedding a Python interpreter in a multi-threaded C++ program with pybind11
I'm trying to use pybind11 in order to make a 3rd party C++ library call a Python method. The library is multithreaded, and each thread creates a Python object, and then does numerous calls to the object's methods. My problem is that the call to py::gil_scoped_acquire acquire; deadlocks. A minimal code which reproduces...
I managed to resolve the issue by releasing the GIL in the main thread, before starting the worker threads (added py::gil_scoped_release release;). For anybody who is interested, the following now works (also added cleaning up Python objects): #include <pybind11/embed.h> #include <iostream> #include <thread> #include...
65,344,486
65,345,396
A C++ program that inputs two 3*3 matrice and display the sum and product of the matrices
It's a c++ program that takes input for 3*3 matrices and displays the sum and product of those matrices. Now I have improved the program and it's working as expected, so is there anything that can be improved in this program. #include <stdio.h> //function prototypes To get the input for an array. void getarr(int *x);...
The is a common error for uninitialized pointers. You declared int * d; earlier in the program but you never give it a memory that d should point to. And you need to initialize that memory. You can add the following line inside main but before any use of d, d = new int[9]; memset(d, 0, 9);
65,344,533
65,344,752
Does overriding a function instantiate the base function? (getting error)
I would like to write a converter. I would prefer a base class that already handles the trivial cases where InputType can be directly converter to OutputType, say float to double. However, in this shortened example, I get an error: error C2440: 'static_cast' : cannot convert from 'const Eigen::Vector2d' to 'std::tuple...
Virtual methods are instantiated in the same time than the class, so it should be correct. You might provide 2 versions: template <typename InputType, typename OutputType, typename Enabler = void> class DefaultConverter { public: virtual ~DefaultConverter() = default; virtual void set(const InputType& input) =...
65,344,562
65,344,624
How do I implement a C++ header file that doesn't contain a class name?
EDIT: Thanks! I'm coming from Java, so it turns out I was just unfamiliar with what free functions are and how they work. I appreciate everyone's answers. For an assignment, I was given a C++ header file (.h) with a bunch of empty functions that I need to implement in a separate .cpp file without altering the original ...
C++ is not as object-oriented as Java or C# and allows free functions - ones that exists outside of any class. It seems that your header declares exactly that. Use simply returnType functionName() //defines a function in current namespace, global or other { ...implementation... }
65,345,202
65,345,297
Portaudio.dll won't link properly in VS
I'm using C++ on visual studio 2019 and having issues trying to link my project to PortAudio. I'm getting the error 'portaudio_x64.dll was not found. Reinstalling the program may fix this problem'. I have linked to portaudio.lib in Properties->Configuration properties->linker->Input->Additional dependencies. I have al...
A DLL used by an EXE needs to be in the same directory as the EXE runs from (your current working directory), or on the system PATH (which includes places like C:\Windows\System32\). Someone here suggested that I copy the actual dll file into the same folder as my solution. This works when I run the program with Crtl+...
65,345,619
65,345,914
Is there a way to add a pre created class to a vector?
First off, I'm new to c++, currently learning it online. I greatly appreciate any help... I have a vector of classes set up for vehicles, however it should also contain derived classes for vehicles of different types (car, truck, van). My class is set up to have functions to gather user input and assign that to differe...
My class is set up to have functions to gather user input and assign that to different variables, I do not use the constructor for this. Is that wrong? A constructor shouldn't do lots of things, and never prompt for user input… but, at the same time, it should not be possible to have a "half-ready" object at any poin...
65,346,293
65,347,073
Is there a way to allow this in C++ Visual Studio 2019 (Community Edition)?
(sorry if this is a noob question) Is there any way to allow fixed size C++ arrays in Visual Studio 2019 Community Edition (i.e int arr[n] where n is the size I want) Thanks in advance :D
No. Variable sized arrays are not part of the C++ standard, and Visual Studio does not implement them. Use std::vector instead. If you've done measurements that prove that this vector allocation+deallocation is a major slowdown in your app (which I've never seen happen, ever), then consider using a stack-based buffer...
65,346,353
65,571,019
Can I compile a dynamic lib on Linux and link on Windows?
I run Linux (specifically Ubuntu 20.04), and would like to know if there is a way to produce a dynamic library that could be linked against on a Windows machine. I am using GNU make and a mingw cross-compiler to attempt to do this. Here is the simple makefile I have made for testing purposes: CXX := x86_64-w64-mingw32-...
I eventually got it. The command that worked was: g++ -o alt.exe testapp.o libexample.a. I am not entirely sure why this works when what I tried before did not, but it does work as expected now. Interestingly, it still works even if I do not specify __declspec(dllimport) anywhere. I am also not sure why this works, but...
65,346,454
65,347,043
How does declaration, definition and initialization work? I've stated how I understand it and would like to get corrected
I've learned about declaration, definition and initialization. I seem to understand but still not so confident about it. So I assume that declaration is putting (as well as declaring) a date type or a function (or something else perhaps I don't know) in the code and in most cases it's going to be a definition too. Basi...
Yes, in simple terms you are correct. The standard draft devotes a page or so to declarations and definitions in par. 6.1. I liked how it described declarations (emphasis by me): A declaration (Clause 10) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations. T...
65,346,574
65,347,014
The code after conversion does not execute a given action
I was given a task to convert a certain code from C++ to ASM based on AT&T syntax, so I started with simple examples and encountered the first problem. code from which I started the exercise void func() { int num = 1; std::cout << "before: " << num << std::endl; num = num << 3; std::cout << "after: " << num << ...
The code you are writing is very implementation specific. In your case the code likely doesn't work because you are using ebp which is a 32-bit addressing register, while you are running on a 64-bit machine, which uses rbp. HOWEVER you are approaching this incorrectly. Either you write pure assembly, or you use the cor...
65,346,667
65,348,931
QTimer single shot, passing lambda with exception in capture
I'm using Qt 5.15.0. I have a try-catch block as follows: try { //some code here } catch(std::exception& e) { QTimer::singleShot(0,[e](){ throw e;}); } I get a warning treated as an error C4702: QtCore\qobjectdefs_impl.h(146): warning C4702: unreachable code. Any idea what's going wrong? Removing the e from the ...
This is basically noise and you can ignore that warning. It comes from how Qt wraps your functor. The code around the error location looks as follows: template <typename, typename, typename, typename> struct FunctorCall; template <int... II, typename... SignalArgs, typename R, typename Function> struct FunctorCall<Inde...
65,346,700
65,348,305
Converting carray to initializer_list for istream
I need to read array elements from the stream, and I have std::initializer_list<double> as constructor. I couldn't find anything related to this. Is it possible to read carray elements from input stream? I have to variables in Vector class I defined: double* data and size_t rows_ My code is as following; Constructor Ve...
The class std::initializer_list<T> is a rather special beast. It essentially exposes a sequence of T values somehow sitting on the internal stack in a form which can be iterated. The only way to create such an entity is to actually have the values directly sitting in an std::initializer_list<T>. There is no way to crea...
65,346,975
65,353,740
Parameter help string loses last character in Function Wizard (C++ XLL)
I have a slightly odd (though not terminal) issue when registering my XLL functions. I use the xlfRegister call, with the list of arguments as per usual, but have two issues: The function description and parameter help strings each have a full-stop (".") appended; I seem to lose the last (maybe two last) character(s) ...
Aha ... I found this in the list of known SDK issues: “Argument Description String Truncation in the Function Wizard The pxArgumentHelp1 parameter and all subsequent parameters of the xlfRegister function are optional strings that correspond to the arguments of the XLL function. The Function Wizard displays these to pr...
65,347,079
65,347,180
Passing any function with any number of arguments to another function
I am trying to create a C++ function that takes any function with any number of arguments and pass it to std::thread to start a thread with it. #include <iostream> #include <thread> #define __PRETTY_FUNCTION__ __FUNCSIG__ void runFunctionInThread(void(*f)()) { std::thread t(f); t.join(); } void runFunctionInThread(vo...
Use a variadic template with perfect forwarding of its parameters, eg: #include <iostream> #include <thread> #define __PRETTY_FUNCTION__ __FUNCSIG__ template<class Function, class... Args> void runFunctionInThread(Function f, Args&&... args) { std::thread t(f, std::forward<Args>(args)...); t.detach(); } voi...
65,347,479
65,349,621
How to turn a string into int with more than 1 digit in c++?
This is my code for (unsigned int i = 0; i < form.size(); i++) if (isdigit(form[i])) { value=form[i] - '0'; operand.push(value) //this is a stack } but it only works when you have an int of 1 digit, lets say the form string has 1, it works just fine, but when the string gets...
for (int i = 0, temp = 0; i <= form.size(); i++) { if (i == form.size() || !isdigit(form[i])) { operand.push(temp); temp = 0; } temp = (temp * 10) + form[i] - '0'; }
65,347,599
65,347,722
Passing any class member function with any number of arguments to a function outside the class
Remy posted a great solution to pass any function with any number of arguments to std::thread, here. I was wondering how it could be used for class member functions. #include <iostream> #include <thread> #include <mutex> #define __PRETTY_FUNCTION__ __FUNCSIG__ std::mutex my_mutex; template<class Function, class... A...
If you want to call a member function you'll need to pass the object to std::thread too: void manager() { //... runFunctionInThread(f1, this); runFunctionInThread(f2, this, 2); runFunctionInThread(f3, this, 3, 3); } Note: I noticed that you detach your threads. You then need to manually make sure that ...
65,347,797
65,348,617
Not sure about the use of pointers C++
I'm new to C++. I have problem with the code below. The last function object.f() in main function should return 120, but it returns 100 and I don't know why. SOLVED method g of class B should take reference parameter. This is the header file class A { string p; float b = 0; public: A(string &&p, int b=0); i...
In c++, class instances are not passed by reference by default. Therefore, bool ATM::acceptCard(DebitCard acard, const string &pin) this function takes a copy of DebitCard and stores the address of this copy. Next call to ATM::deposit will use a pointer that doesn't point to a valid object. To make this code work, ATM...
65,348,085
65,348,160
How do I define a class template with specfic format of taking template arguments? e.g.: Fn(Args...)
template<class Fn, class ...Args> class func_class<Fn(Args...)> // Do not know what to do here { typedef typename result_of<Fn(Args...)>::type mytype; std::function<mytype(Args...)> func_; std::tuple<Args...> tuple1; public: func_class(Fn&& func_in, Args&& ...args) { ...
template<class Sig> struct bob; template<class R, class...Args> struct bob<R(Args...)>{ //... }; specialization. Uses of bob that fail to pattern match will give compile-time errors. As a note, using R(Args...) syntax when R is not a return value and Args... are not arguments will lead to unexpected quirks, because ...
65,348,174
65,348,359
C - Get External IP Address
I need to get my public IP address through C/C++ calls. I know as an alternative I can get from external links like "http://whatismyip.akamai.com" I wrote a sample to get external IP address. But my program is not returning external IP address. I am getting internal IP address. Am I missing anything here? If it is not ...
"External IP" is a property of the network; not a property of the computer that is connected to the network. Thus, there is no function that you could call to get such information from the standard library or the operating system, as the system doesn't know the information. I wrote a sample to get external IP address....
65,348,319
65,348,805
How would I write numpy.tensordot in c++?
I'm trying to replicate numpy.tensordot in c++. The example in the numpy documentation shows a nested loop that I can get to work, but what if instead of c = np.tensordot(a,b, axes=([1,0],[0,1])) I want to do: c = np.tensordot(a,b, axes=([1,2],[0,1])) What would that new nested loop look like in python? And is there...
I find rewriting to np.einsum first is helpful as the resulting for loop code looks quite similar conceptually: a = np.random.rand(16, 8, 2) b = np.random.rand(8, 2, 1) c = np.tensordot(a, b, axes=([1,2],[0,1])) # same thing written with einsum c_ein = np.einsum("ijk,jko->io", a, b) # same thing done with for loop...
65,348,571
65,348,735
How can I replace multiple characters with just one (C++)?
We have a char. We need to replace all ab characters from our char with the letter c. Example we have : abracadabra the output will be : cracadcra I tried to use replace() function from C++, but no success. #include <iostream> #include <cstring> using namespace std; int main() { string test; cin>>test; fo...
Problem: That is not the syntax of std::string::replace. Solution: As is mentioned here the syntax is std::string::replace(size_t pos, size_t len, const string& str). Do test.replace(i, 2, "c" ) instead of test.replace(test[i],'c'). Or use regular expressions as dtell pointed. Adittional information: using namespace...
65,348,602
65,364,163
OpenMP - accessing individual file by individual thread
I have 4 cores == 4 threads (omp_get_max_threads()) so I created 4 sections (OMP sections) to break that one huge file into 4 sub-partitions so then to feed them to 4 different threads and do the further processing in each thread (other approaches were there but I wanted to try this). In each section I opened same larg...
The culprit is that word_length_counter is private and not properly initialised. For each private variable, a thread-private copy is created and "... initialized, or has an undefined initial value, as if it had been locally declared without an initializer" (from the OpenMP specification, section 2.21.3). It happens so ...
65,348,851
65,349,000
Increasing hex value with given data
I need to compare given text data with checkSumCalculator method and I try to send the data with command method. I find and changed the code according to my own needs. But I dont understand some parts. How can 0x00 hex char will be increase with given data? and how/what is the point of comparing check_data with 0xFF? H...
checkSumCalculator starts by adding together all the values of the buffer in data. Because the type of data is unsigned char, this sum is done modulo 0x100 (256), 1 more than the maximum value an unsigned char can handle (0xFF = 255); the value is said to "wrap around" ((unsigned char) (0xFF + 1) = 256) is again 0). Th...
65,349,514
65,349,918
OpenCV access current and previous frame
I need the current and previous frame for some calculations in OpenCV C++. Here is my code so far: vector <cv::Mat> frames; // Current frame Mat M = current_frame; Mat F; // previous frame // set Previous Frame if (frames.empty()) { F = M; frames.push_back(M); cout << "e...
Are you sure you are not missing a loop somewhere in that snippet? If I try something like this: //create a dummy vector of mats: std::vector<cv::Mat> sourceMats; sourceMats.push_back( cv::Mat(1, 4, CV_32F, {1, 1, 1, 1}) ); sourceMats.push_back( cv::Mat(1, 4, CV_32F, {2, 2, 2, 2}) ); sourceMats.push_back( cv::Mat(1, 4,...
65,349,551
65,384,102
DRM + GBM OpenGL rendering flickering R-PI 4
I am using GBM, DRM and EGL to render my scene to a HDMI display on my R-PI 4B. No X server is installed, and the R-PI boots into text mode before launching my application. First my problem: I notice a lot of flickering throughout all of my rendering. So far I do not render much, I render a buch of text elements and a ...
As a matter of fact it apparently was not related to my code and an R-PI/driver issue. Nevertheless the following change in /boot/config.txt did the trick: # dtoverlay=vc4-fkms-v3d dtoverlay=vc4-kms-v3d-pi4 The commented line (with fkms) was before and the other line was after. I assume for it to work you also need to...
65,349,598
65,349,658
unordered_map MSVC invalidation guarantee
At https://learn.microsoft.com/en-us/cpp/standard-library/unordered-map-class?view=msvc-160 MS states: "inserting an element invalidates no iterators" But the book "The C++ Standard Library" by Nicolai Josuttis and https://en.cppreference.com/w/cpp/container/unordered_map both state that insert may invalidate iterato...
Yes, each compiler vendor must at the minimum comply with the guarantees of the standard, however they are free to offer stronger guarantees if they so choose. For example, all compilers worth their salt guaranteed return value optimization (RVO) long before the standard mandated it.
65,349,713
65,350,028
Why does the while loop not break?
This program takes the name of the course, grade and the number of units of a course to calculate the grade point average. I want the program to exit the while loop after the user enters the letter q and display the phrase outside the loop. #include <iostream> using namespace std; int main() { char name[20]; fl...
Problem: You're comparing a char with an int variable called q. That won't break the loop when the user enters 'q', it will break the loop when the player enters the character that corresponds to the value that the q variable stores (in your case it is probably 0 in ASCII that is '\0'). Additionally, you're accessing ...
65,349,790
65,349,940
idiomatic way of changing container elements while iterating over the container
Is the following way of manipulating a string or a container idiomatic? string s = "hello"; for (auto &p : s) { p = somefunction(p); // somefunction without side effects } This implies iterating over a range while changing the contained elements. The container is not modified in its layout so the iterators should ...
Idioms can change over time, so here's a C++20 version that might very well become idiomatic in the not too distant future. std::ranges::transform(s, s.begin(), someFunction); Here's a demo.
65,349,815
65,353,608
How do I compare text lines in 2 files between 2 specific characters in a C++ program
I have this program I am writing that cleans up a xml file and adds new lines to a settings section from a txt file. Part of it I have a section labeled // Part in my code. It is during or after that section, either is fine, I would like to compare the lines to make sure they are not duplicated but ignore their settin...
A note about XML first: XML allows formatting which doesn't necessarily change the meaning of its contents. Beside of indentation, an element might be written in one line or spread over multiple lines. It's even allowed to write the whole XML file in one line (assuming there are no newlines in the element's contents li...
65,349,875
65,384,705
Where can I find GLIBCXX_3.4.29?
I updated my GCC compiler from the GIT repo to version 11. Now my test code (GoogleTest/GoogleMock) is complaining about GLIBCXX_3.4.29 not being found. This is not a duplicate please reopen The answers posted in: Understanding the gcc version and the GLIBC, GLIBCXX versions in more detail (2 answers) doesn't answer th...
After building GCC and installing the binaries, the softlink /usr/lib/x86_64-linux-gnu/libstdc++.so.6 wasn't updated to the latest version. Mine was still pointing to a previous version as mentioned in the comments above. Under GCC build directory I found the GLIBCXX_3.4.29 build directory and copied the library to /us...
65,350,197
65,352,603
Unit testing custom STL-compatible containers and iterators
I've just implemented a custom iterator type for a custom container. The container models the C++17 ReversibleContainer, and its iterators (both const and non-const) model LegacyRandomAccessIterator. My question is; is there some sort of built-in thing in std that I can use to test if both the container and its iterato...
No there us not. In fact proving a type satisfies all requirements of being an iterator cannot be done statically in C++. You can test statically if the types are correct, and that operators and the like exist. But ths semantics cannot be proven in the general case (I think both practically and theoretically due to Ric...
65,350,218
65,350,606
How to make test case for my queue code written in c?
how can I develop a test case(running all functions correct way in main)? READ: because of the some reasons I cant post my code here giving me errors so I put image below and the code can be viewed from the following link. LINK IMAGE LINK OF THE CODE I want to see the uses of insert and remove both removing and insert...
In insert, you have: if (q->rear = 5) { This [unconditionally] assigns the value of 5 to q->rear You want a comparison: if (q->rear == 5) { Note that remove is a standard function, so, when compiling, you get a conflict. I've renamed remove to dequeue [and insert to enqueue]. Using loops can generate test code (e.g....
65,350,226
65,350,363
How to remove only the title of console in a C program?
How can I remove only the title of the console in C or C++? Remove that: HWND hwnd = GetConsoleWindow(); DWORD style = GetWindowLong(hwnd, GWL_STYLE); style &= ~WS_THICKFRAME; SetWindowLong(hwnd, GWL_STYLE, style); I tried that, but it doesn't work.
You can use the function SetWindowText, like this: SetWindowText( GetConsoleWindow(), TEXT("") ); This will set the title of the window to an empty string. If you want to remove the entire title bar, then you can use the following code: DWORD style = GetWindowLong( GetConsoleWindow(), GWL_STYLE ); style &= ~WS_CAPTION...
65,350,310
65,350,335
C++ LNK2001 Error on trying to use External Variable
I'm trying to create a utility class, that I can use thorough my program like logging, debugging and etc. In Java, I know I can make it as by declaring the variables and functions static, as I read more how to do it in C++, I should use extern, surrounded by namespace to don't populate too much the files. Upon trying t...
extern means that you define your variables elsewhere. In your case, you must include the following in lib.cpp: namespace Lib { Application *app; Graphics *graphics; } That said, your design is questionable: In Java, I know I can make it as by declaring the variables and functions static You can do the same ...
65,351,035
65,351,156
Type Cast Truncation from HANDLE to ULONG C++
I am getting the warning (treated as error): Type Cast Pointer Truncation from HANDLE to ULONG When I try to compile, I understand that the type has a different length as I am compiling ARM64 rather than ARM, therefore I need to change the type or static_cast it, however I receive errors such as "expected (" when cha...
The HANDLE type is used to point to an opaque structure. It usually stores an index value, but in the winnt.h header file, it is defined as a pointer-length type. typedef void *HANDLE; So the correct approach is to treat the process id as a pointer-length type as well. I know you don't like HANDLE, so you can use ULON...
65,351,080
65,351,164
c++ jump to eventhandler
I'm struggling with a GUI application in C++. Clicking buttons activates routines, which may take some time. The window is then unresponsive. I would like it to keep listening and reactive. I heard about ISR, which seems unsuitable because I don't want to continue where I left, but rather forget about the aborted proce...
The exact solution is going to be very dependent on what you're trying to do, and what (toolkit, etc) you're trying to do it with. The quick (to give, not to do) answer is to use a separate thread for your work. You have one thread for your GUI stuff, and when the user hits a button you send a message to your worker th...
65,351,216
65,352,867
Edit and Continue in VS2019
I've just updated a major C++ project from VS2010 to VS2019, and I'm having problems getting Edit and Continue to work like it used to, specifically in relation to the 'Require source files to exactly match the original version' setting (which I will refer to as the 'require match' setting, because it's shorter). I'm u...
Not quite understand your specific situation and operation, because there are not some pictures and code to explain the issue in detail. But this function which I used could break into the changed code during debugging with require match option. You should move your cursor back to the changed code and then Debug the be...
65,351,413
65,351,464
Why can we say the complexity of hashmap is O(1)
I've been using hashmap for a long time and I always believe that its complexity is O(1). I know that the key of hashmap is the hash function, which can map a key to a value. If the hash function is well designed, the collision can be kept at an acceptable level. Today I read a hash function as below, which hashes stri...
First off, a hashmap doesn't have complexity. Inserting into a hashmap does. Reading from a hashmap does. Operations have time complexity, object do not. Objects can have memory complexity, but that's not what we're talking about here. Secondly, a hashmap doesn't always have O(1) even for reads. It has O(1) averag...
65,352,520
65,353,881
Transparent icon has white background in Visual Studio C++ executable
In my Visual Studio 2019 C++ project created as Empty Project (C++, Windows, Console), I added an Icon resource and it is being displayed as the icon of the executable since it is the only icon in the project. The image is in *.ico format and has a transparent background. When it is displayed as the icon of the executa...
The problem was with the Windows thumbnail cache. Initially I had used a fully-opaque image, and when I used the same image but with a transparent background, Windows Explorer was showing the old cached one. I cleared the thumbnail cache via Disk Cleanup.
65,352,662
65,352,727
char* return type acting strange
I am using visual studio. The following code will print nonsense in the console. #include <iostream> namespace tools { char* slice_to(const char arr[],char term) { char tulem[1000]; char(*tul)[1000] = &tulem; int i = -1; do{ i++; ...
You're trying to cout a local variable that is out-of-scope once the slice_to returns. As you're returning a ptr, no copy of the underlying data is being done - it's a pointer to memory that is no longer valid. As it's on the stack, it may not be overwritten (hence you're able to access the values under the address) bu...
65,352,668
65,352,688
How can C++ destructor distinguish these difference?
For an object, its destructor is called when it goes out of scope. Here's my program: #include <iostream> using namespace std; class A { public: A() {} ~A() { cout << "A's destructor called!" << endl; } }; class B { public: B() = delete; B(int x_) {} ~B() { cout << "B's destructor called!" << endl; } }; ...
Change this void func_a() { A a(); } to this void func_a() { A a; } In your code a is a function declaration, not an object. Put a cout << statement in the constructor too. You will see that the constructor for A isn't called either.
65,352,975
65,353,573
A Server Class Taking Any Function To Run in Thread With Passing a Server-Generated Value
I am trying to write a server class with a method that takes a function as an argument and pass in a value (generated inside the server class) to the function for being run inside a thread. The following is just an example to illustrate what I am trying to do. My goal is to have the Server::runFunctionInThread general ...
Before we got your problem, why you don't define the Server, A and B constructors ? So, your problem is with functions argument. You just sent a function address to your Server: s.runFunctionInThread(&A::FA, this); ... s.runFunctionInThread(&B::FB, this); ... s.runFunctionInThread(&FC, 3); And use it wrongly: std::thr...
65,353,356
65,353,398
How to ofstream and then ifstream a 2D string array in same program in c++. Here is the code which I wrote. I am a starter
#include <iostream> #include<fstream> using namespace std; int main() { int a; cout<<"enter key "; cin>>a; if(a==1) { string info[0][1]; cout<<"enter your name "; getline(cin, info[0][0]); cout<<"enter father's "; getline(cin, info[0][1]); ofstream ...
This is not legal C++ (because arrays of size zero are not legal). string info[0][1]; cout<<"enter your name "; getline(cin, info[0][0]); cout<<"enter father's "; getline(cin, info[0][1]); ofstream file("info.txt"); for(int i=0;i<=1;i++) { file<<info[0][i]<<" "; } All yo...
65,353,466
65,353,780
Disable Warnings when compiling ARM64 C++? Visual Studio 2019
I am working in the kernel space of a project (building in ARM64), and am unable to disable specific warnings for my project. The warning is being treated as an error and will not allow me to compile my project, so you can imagine it is very annoying. The warning is Error code C4244: '=' conversion from 'ULONG_PTR' to ...
Based on the comments in your last question, the warning should appear at the location where the get_process_id_by_name function is called, not inside the get_process_id_by_name function. Because now there is no conversion of ULONG_PTR to ULONG inside the function. This is the documentation for #pragma warning. And her...
65,353,579
65,353,782
Can someone explain me why is that the output, C++ recursive function
I don't understand why after running this code int n; int f(int x) { int n; if (x > 0) { if (x % 2 == 0) { cout << x % 10; n = 1 + f(x / 10); } else { n = 1 + f(x / 10); cout << x % 10; } return ...
Before C++17 order of argument evaluation is unspecified. This means compiler can either run f(8174) (and therefore all of its std::cout << ... statements) before std::cout << ' ' or after that. The fix is rather simple, you need to split your cout into two statements: int main() { std::cout << ' '; std::cout <...
65,353,809
65,353,922
expected ‘,’ or ‘...’ before string constant
Why const std::string str="__$HOOK_FUNC_FOR_LUA_KEY@__"; is ok whereas the compiler complains when compiling const std::string str("__$HOOK_FUNC_FOR_LUA_KEY@__");? NOTE: str is a member variable of a C++ class. Demo code: class Demo { private: const std::string str("__$HOOK_FUNC_FOR_LUA_KEY@__"); } Here are the the er...
You can't have function-like inittialization inline in classes. You must use curly-braces {} or "assignment" like syntax with =. It's a way to go around the problem of detecting if you're declaring a function or a variable. And as you're dealing with std::string which has an std::initializer_list constructor (which wil...
65,354,080
65,354,397
How to access a variable in a method of a different class in c++
How to access a variable in a method in a different class for example in this code. #include <iostream> using namespace std; class Student { public: void Addition() { int c=17; } }; int main() { } How can i access variable c in Addition method in class Student without returning the value. Than...
You can use a setter and getter in your class, then use them to achieve what you want in the main private: int c; public: void setIntC(int intC) { c = intC; } int getIntC() const { return c; }
65,354,621
65,355,326
Why do I get automatic input in my interactive container application
I have a super simple cpp program that reads with std::getline(std::cin, ...) and std::cin >> myint and prints to cout. When I containerize that application and run it with ENTRYPOINT the application is getting input from somewhere to STDINso it just runs to completion and my container stops. If I put my getline and co...
It turns out it was very simple. If not running with -i, stdin is not attached and as soon as I read something I get EOF. So the program just runs through and quits. The answer is to run with the container with -tid, that is, keep stdin open, allocate pseudo-TTY and detach. That way the application is kept open and I c...
65,354,875
65,354,946
Why can't I change the value of a multidimensional char array in C++?
I'm making a TicTacToe game in C++ after watching Coding Train make it in his video using JavaScript. I'm not new to programming but I'm new to C++. The problem arose when I tried to change a 2D char variable. #include <iostream> #include <string> #include <vector> constexpr unsigned int board_x = 3, board_y = 3; cons...
You seem to assume that static_cast<int>('1') is 1. That is not the case. Characters are encoded by integer values and regardless of the encoding that your system uses, the value that is used to represent the character '1' is not 1. In the ubiquitous ASCII encoding, '1' is represented by the value 49. The index 49-1 i....
65,354,932
65,355,938
Boost shared memory map allocator errors
I am trying to create a shared memory manager map in boost, along with a synchronization class for the map. I previously did something roughly the same with vectors and it worked fine. I get the error mentioned in the title while using maps. Am I doing this all wrong? Code in this repo Synchronized class: #include <ios...
Changing allocator_type to the value pair and defining a comparator for std::array<char, ACCESS_SIZE> solved the issue. typedef pair<const access_name, T> value_type; typedef allocator<value_type, managed_shared_memory::segment_manager> allocator_type; struct cmp_str { bool operator()(access_name a, access_nam...
65,354,979
65,355,444
Disable printf using freopen stdout while keeping std::cout functioning
I have a piece of code that takes an ostream as input, which can be std::cout or a std::sstream and outputs to it. void myFunction(std::ostream out) { out << "output"; } At the same time I want to disable the use of printf to any third party library, so that they do not interfere with my output in case out == std:...
Im pretty sure this is not possible (at least using standard c/c++/posix). This is because printf is using STDOUT directly - the lower level. Once you redirect STDOUT it is "game over" so to speak (again: unless you go beyond standard). You can do the opposite if you want to - that is redirect just std::cout without re...
65,355,261
65,355,404
threaded for loop reaching values it's not supposed to reach
I'm messing around with multithreading in c++ and here is my code: #include <iostream> #include <vector> #include <string> #include <thread> void read(int i); bool isThreadEnabled; std::thread threads[100]; int main() { isThreadEnabled = true; // I change this to compare the threaded vs non threaded method i...
This line: std::cout << i << std::endl; is actually equivalent to std::cout << i; std::cout << std::endl; And thus while thread safe (meaning there's no undefined behaviour), the order of execution is undefined. Given two threads the following execution is possible: T20: std::cout << 20 T32: std::cout << 32 T20: std:...
65,355,487
65,356,086
How to fill a 2D through input and then read back as output in a C++. Here is the code which I wrote. I gives wrong output.I am a beginner
#include <iostream> #include<fstream> using namespace std; int main() { int a = 1; if (a == 1) { int a[1][1]; for (int i = 0; i <= 1; i++) { for (int j = 0; j <= 1; j++) { cin >> a[i][j]; } } cout << endl; for (int k = 0; k <= ...
Try this int main() { int arr[2][2]; // declares a 2x2 array cout << "Enter integers : " << endl; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { cin >> arr[i][j]; //inserts at the index i and j in the array } } cout << "Display array : " << endl; for (int i...
65,355,623
65,355,962
Call function with another function as argument within class
I have tried to build code which passes a function to be used within another function. Below is the code I tried, and it works OUTSIDE the function (so if I delete everything related to class Foo, it works), but I have no idea how to get this to work within the class itself. How can I pass one function within the class...
Concerning int64_t runLoop() { return loop_class("(1 + 2)", Foo::part1_math_class); } Foo::part1_math_class() has the matching signature for the std::function<int64(std::string)> when called with the correct object. In this case, this would be the pointer to the intended object. Hence, it must be "...
65,355,799
65,356,305
Is a static variable created using a lambda thread-safe?
A& instA() { static A a = []{ return A(); }(); return a; } instA() returns a single static a; is this function multithread safe?
As mentioned in a comment, a simpler code that achieves the same is: A& instA() { static A a; return a; } Since C++11, this is thread-safe. No mutex needed inside this function. a will be created only once and different threads can get a reference to it. However, don't make the mistake of believing the above s...
65,355,858
65,356,561
Does this function returns a proper R-value reference or does it returns a copy?
Quaternion&& GetInverse() const { return Quaternion( GetConjugate() / GetSquaredMagnitude() ); } I wanna know what will be returned, and if it is more efficient to indeed return an Rvalue, or to simply return a copy. Or maybe I am completely wrong and there simply is no copy here. Any information will be greatly...
Quaternion&& is an r-value reference, but it is still a reference. In your code example you're returning a reference to a temporary object that will be destoroyed after GetInverse() returns and the reference will dangle. It is not an optimization, it is undefined behaviour. Modern compilers are able to detect such erro...
65,356,122
68,987,955
List doesn't recognize subcommand transform: Error in Cmake
i am using this to cross compile with raspberry pi, but i stuck in the step ../qt-everywhere-src-6.0.0/configure -opengl es2 -device linux-rasp-pi3-g++ -device-option CROSS_COMPILE=arm-linux-gnueabihf- -sysroot /opt/qt5pi/sysroot -prefix /usr/local/qt5pi -opensource -confirm-license -skip qtscript -nomake examples -mak...
cmake version in ubuntu 18.04 is 3.10 TRANSFORM is new in cmake since 3.12 System requirements to build qt6 : CMake (>= 3.16, >= 3.18.4 for Ninja Multi-Config, >= 3.21.1 for static Qt builds in Qt 6.2+) So, you need at least version 3.16 of cmake
65,356,524
65,357,102
erase duplicate elements keeping order
I would like to eliminate duplicate elements from a vector while keeping the vector in the current order. Below I have a proposed implementation. First, is this safe? Second, is there a better way to do it, either more efficiently or better from a "using C++ algorithms and not reinventing the wheel" perspective. #incl...
One of many ways this can be accomplished it to use std::unordered_set to keep track of duplicates and std::stable_partition to partition the duplicates from the lone values while preserving the order of the items: #include <iostream> #include <vector> #include <algorithm> #include <unordered_set> int main() { std...
65,356,548
65,386,900
Call C++ function inside VS watch or immediate window
Question is fairly simple: Is there a way to call a C++ function from watch window of visual studio, when that function is declared in File1.hpp, defined in File1.cpp and the debugger is currently stopped with a breakpoint in AnotherFile.cpp? File1.hpp int &getValue(); File1.cpp int &getValue() { static int value ...
I suggest that you could use Immediate in Debug->Windows->Immediate. Then, when you debug int x=0, you could input getValue() in Immediate Window. And you will see the console output value 0.
65,357,149
65,357,317
Bool member variable in class is set to True when uninitialized
Updates: The reason I was getting true is because anything that is other than 0 would be considered true which obviously makes sense to how unlikely it would have been for me to get false when uninitialized. I have read a post similar to my question on StackOverflow, it talked about that it is good practise to initiali...
While bool conceptually contains only one bit of information, the requirements of the C++ standard mean that a bool object must take up at least eight bits. There's three main ways that a compiler might represent bool at a bitwise level: All bits zeroed for false; all bits one'd for true (0x00 versus 0xFF) All bits ze...
65,357,220
65,357,593
Partial template specialisation
I'm trying to specialise the constructor of the following templated class enum class A { a1, a2 }; enum class B { b1, b2 }; template<typename A, typename B> class test { public: test(A a, B b) {} }; How would I specialise the constructor to take a particular value of B, such as B::b1? I've not tried this before, ...
the second parameter of template test only accepts a type (like B), instead of a value (B::b1). test<A, B::b1> is always ill-formed whatever you do to specialize test. however, you can build a mapping from a value to a type, such as: enum class A { a1, a2 }; enum class B { b1, b2 }; template<typename A, typename B> cl...
65,357,225
65,393,754
Use numeric sequence as default agument in Rcpp (Armadillo) function
I need this for a bigger project but I think this minimal reprex explains it best. I have the following function in R: test <- function(x = 2^(1:9)) { x } test() #> [1] 2 4 8 16 32 64 128 256 512 This is working fine. However, I want to translate this to Rcpp using Rcpp Armadillo. I tried this using the f...
I would like to add a solution in addition to Dirks answer. This is the CPP code. // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> using namespace arma; // [[Rcpp::export]] vec test_cpp(Rcpp::NumericVector x = Rcpp::NumericVector::create()) { if (x.size() == 0) { x = exp2(linspace(1, 9, 9...
65,357,244
65,357,280
+ operator overloading error even though it is overloaded
pan.h #pragma once #include "vector.h" namespace math_ { void worldToScreen(const Vec2& world, Vec2& screen, const Vec2& offset); } pan.cpp #include "pan.h" namespace math_{ void worldToScreen(const Vec2& world, Vec2& screen, const Vec2& offset) { screen = world + offset; } } ve...
Your overload is not marked const, but you are calling it from a const Vec2&: struct Vec2 { Vec2(float x_, float y_); float x = 0.0f; float y = 0.0f; Vec2 operator +(const Vec2& other) const; Vec2 operator -(const Vec2& other) const; // ^^^^^ }; Vec2 Vec2::operat...
65,357,271
65,359,013
How to add chrono::year_month_day to chrono::sys_seconds
Am holding duration's in a year_month_day. Is there a simple way to add the year_month_day duration to a time_point like sys_seconds? sys_seconds date1 = {}; sys_seconds dat2 = {}; year_month_day calDuration; date1 = date2 + calDuration; //error: no match for ‘operator+’
This is chrono catching logic bugs for you at compile-time. Adding date2 + calDuration is akin to adding tomorrow + today. It just doesn't make sense. And that's why it is a compile-time error. What you may mean is that you have durations years, months and days. This is not the same as the similarly named types yea...
65,357,296
65,357,472
How do i pass a predicate function as a template parameter?
I have a simple predicate: class less_than { int x; public: less_than(int i): x(i) { } bool operator()(int i) const { return i < x; } }; I have a container which looks like this: my_containers<std::list<int>, less_than, int> myCont(list_1, list_2, less_than(11)); The first parameter says wh...
your constructor demands the default constructor of each member. use member initializer list instead. my_containers(Type& tar_1, Type& tar_2, Predicate felt) :ItemList_1(tar_1), ItemList_2(tar_2), predIcate(felt){} refer to: https://en.cppreference.com/w/cpp/language/constructor.
65,357,381
65,357,399
Passing pointer on vector's elements into map
The following function must find a sportsman in the vector allSportsmen by his full name and birthdate and then find some sport by its name and add this sportsman and this sport from vectors to map participants where key is the sportsman and the values are sports he does vector<Sportsman> allSportsmen; vector<Sport> ...
If you want pointers, you'd have to take the address of your dereferenced iterators s = &(*x); sport = &(*y); I would warn you, however, that this is a fragile design if you mutate your vectors allSportsmen or allSports (e.g. push_back, emplace_back, resize, etc) that causes a reallocation, you'll likely invalidate yo...
65,357,491
65,357,715
Reverse a string C++
I'm new to programming. I've learned how to reverse a string today. I've tried to use string instead of char but terminal gives an error. string name = { "george" }; int nChar = sizeof(name) - 1; string *pName = &name; string *pNameLast = &name + nChar - 1; while(pName < pNameLast) { string save = *pName; *pNa...
Here is an example of using std::reverse_interator. This is better a better way of doing it. Rather than doing it yourself. #include <iostream> #include <string> #include <iterator> int main() { std::string s = "George"; std::reverse_iterator<std::string::iterator> r = s.rbegin(); std::string rev(r, s.ren...
65,357,978
65,358,486
How to solve dependencies inclusion order issues?
I am trying to recompile a project that has two dependencies : Qt and X11. X11 define the following symbols in the global namespace : // Xlib.h #define Bool int #define Status int #define True 1 #define False 0 // X.h #define None 0L However, those symbols (and maybe more) are also used in Qt (in enums, for instance)...
You have to handle with evil MACROs, you might wrap the X11 library into something like // X11wrapper.h #ifndef X11Wrapper_H #define X11Wrapper_H #include <X11/Xlib.h> #undef None constexpr auto None = 0L; #endif and use that wrapper header instead of official one.
65,358,148
65,358,311
Is A::B::B::B::B...B::f() right ? Why could i do that?
I don't know how to explain this: namespace A { struct B { static void f() { } }; } int main() { A::B::B::B::B::B::B::B::B::B::B::f(); } Why could i do : A::B::B::B::B::B::B::B::B::B::B::f(); I don't understand it why it's happening.
It is due to injected-class-name inside class B, B refers to class B, as B::B. so A::B::B refers to class B. and so on.
65,358,191
65,358,445
How to use %f and %lf properly while outputting floating-point number?
I got puzzled when I was trying to solve the problem POJ1269-Intersecting Lines. Here is the link: http://poj.org/problem?id=1269 Here is my final AC code: #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; int main(){ int n; d...
I defined X and Y as double float point number, so I think I should use "%.2lf" Depends on language version. The C standard library functions inherited by C++03 and older are from C89 in which using %lf format specifier results in undefined behaviour. Since C++11 which inherits the C99 standard, the use of %lf is all...
65,358,527
65,358,745
Is unpacking variadic using array(or initializer_list) trick optimize-safe?
Since C++14 cannot use fold expression, in order to make a function that calls bar on each variadics, one have to use function overloading. template<typename Arg> void foo(Arg arg) { bar(arg); } template<typename Arg, typename ...Args> void foo(Arg arg, Args... args) { bar(arg); foo(args...); } But using comma ...
So I'm worried that the compiler removes dummy(since it's unused and actually initialized only by literals), and resulting to not calling bar. Compiler might remove dummy but cannot remove bar calls if they have side effects (as for the recursive version). So you are safe. Or just declaring dummy as volatile" That ...
65,359,108
65,359,147
openGL single channel texture always samples 0
I'm trying to render font on screen using freetype. For that, I implemented single channel texture but it always samples 0. cpp unsigned char *blankData = new unsigned char[8 * 8]; for(int i = 0; i < 8 * 8; i++){ blankData[i] = 126; } glActiveTexture(GL_TEXTURE0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GLuin...
If you are not generating mipmaps (with glGenerateMipmap) it is important to set GL_TEXTURE_MIN_FILTER. Since the default filter is GL_NEAREST_MIPMAP_LINEAR, the texture would be "Mipmap Incomplete" if you do not change the minimize function to GL_NEAREST or GL_LINEAR. glBindTexture(GL_TEXTURE_2D, m_texture2D); glTexPa...
65,359,354
65,365,578
Separate compile and linking actions with Bazel
I would like to know if there is a way to execute compiling and linking actions with Bazel in separate steps. If i execute the command bazel build -s //main:hello-world all the bazel SUBCOMMANDS are printed. I am aware that is possible to execute these subcommands from command line, but I would like to know how to use...
Not sure what exactly you are after, but essentially, you can write a custom rule you pass cc_* target as a source into and try to pick its actions apart only getting outputs of the ones you are interest in, e.g.: def _impl(ctx): outs = [] for src in ctx.attr.srcs: if hasattr(src, "actions"): ...