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
68,198,279
68,198,430
Code is showing showing wrong output in 'fractional knapsack' problem even when answer is properly typecasted
I am solving question called fractional knapsack on geeks for geeks but I don't know why it is giving wrong output for a particular test case. I am not able to find any error in it. // { Driver Code Starts #include <bits/stdc++.h> using namespace std; struct Item{ int value; int weight; }; // } Driver Code ...
You forgot casts in your comparison function: static bool compare(Item i1,Item i2) { double v1=i1.value/i1.weight; double v2=i2.value/i2.weight; return v1>v2; } should be static bool compare(Item i1,Item i2) { double v1=(double)i1.value/(double)i1.weight; double v2=(double)i2.value/(double)i2....
68,199,249
68,199,250
How To Make A Hexacopter With Ardupilot In AirSim?
I am using AirSim, and I need a hexacopter with Ardupilot based firmware. Documentation exists on how to do this with PX4, but not Ardupilot. How would I go about making this happen?
Open your project in Visual Studio, navigate to Plugins/AirSim/AirLib/include/vehicles/multirotor/firmwares/arducopter/ArduCopterParams.hpp Find the setupParams() method, and replace setupFrameGenericQuad(params); with setupFrameGenericHex(params); And set your Ardupilot FRAME param to hexacopter (this can be done in Q...
68,199,709
68,199,881
How do I correctly link against lua libraries on Linux?
I looked at Cannot link with Lua library on Linux, but the OP's problem there was they were using the wrong function name. As I will demonstrate below, I am confident I am using the correct function names. I want to successfully link the C++ code below against lua to create a binary: // compile_lua.cpp #include <iostr...
Your code is C++ but the Lua library exports a C API. Put the Lua includes inside extern "C" {...} or include lua.hpp instead. Also, you need to put -llua at the end of the command line: g++ compile_lua.cpp -llua
68,199,755
68,200,010
What does it mean that function parameter packs are always pack expansions, so their declared types must include at least one parameter pack?
In this snippet template<typename... Types> void f(Types ... args); Types is the template parameter pack and args is a function parameter pack. Concerning the two technical terms, C++ Templates - The Complete Guide 2nd Edition reads Unlike template parameter packs, function parameter packs are always pack expansions,...
It says that a function parameter pack can only be created using another parameter pack, rather than from scratch. What is the example of non-at least one, i.e. zero in the context of that sentence? E.g. int ...params is illegal, because it doesn't contain any existing packs.
68,199,932
68,203,644
QT retrieve custom widget from layout
I have a scroll area with a layout that has 8 of the same custom widgets that have been added to it. This custom widget has a getter function that will return a value. My question is how to get back that original custom widget so I can call the getter function to retrieve the data it stores? I have added the custom wid...
Usually it's not the best structure for your code, any layout change might break your implementation. For example this solution will not work if you will have multiple calcRow widgets. To make it better, you can pass required parameters which you want use inside getRowData as a parameters of testSignal signal. Or just ...
68,200,149
68,202,152
what is the complexity of iterating an unordered_map
What is the complexity of iterating through an unordered_map implemented using hashing with chaining? Specifically does this involve traversing all the buckets, in which case complexity is O(Buckets + NElements) vs. ideal, e.g. O(NElements)
What is the complexity of iterating through an unordered_map? O(N) where N is the number of elements stored. The most relevant part of the Standard: All the categories of iterators require only those functions that are realizable for a given category in constant time (amortized). Therefore, requirement tables for t...
68,200,286
68,200,760
How to fix undefined behaviour with considerably small changes in code
In the core of our project we have following code: template<typename T> T& get_factory_instance(bool reset = false) { static boost::scoped_ptr<T> factory_instance; if (reset) { factory_instance.reset(); return *(T*)0; } if (!factory_instance) { factory_instance.reset(new T()); } ...
I understand that this is legacy code and you want to have no changes on the calls if possible. Further I assume all calls to the function are either fields_t& fields = get_factory_instance<fields_t>(); or get_factory_instance<fields_t>(true); In other words, you never call it via fields_t& fields = get_factory_insta...
68,200,324
68,282,415
Coupling memory pool allocator to various memory pools hosting the allocated instances
There is an stateless memory pool allocator class: template<typename T> class pool_allocator { public: using value_type = T; using pointer = value_type *; /* Default constructor */ constexpr pool_allocator( void ) noexcept = default; /* Converting constructor used for rebinding */ template<typ...
Here is the solution I used - to implement the traits class which holds the information about the pool size: template<typename T> class memory_pool { public: using traits = memory_pool_traits<T>; using element_type = typename traits::element_type; using pointer = element_type *; static constexpr size_t...
68,200,618
68,213,966
Technical background to the C++ fmt::print vs. fmt::format_to naming?
Why is it fmt::format_to(OutputIt, ...) and not fmt::print(OutputIt, ...)?? I'm currently familiarizing myself with {fmt}, a / the modern C++ formatting library. While browsing the API, I found the naming a bit disjoint, but given my little-to-no experience with the library (and my interest in API design), I would lik...
While it would be possible to name format_to print, the former is closer conceptually to format than to print. format_to is a generalization of format that writes output via an output iterator instead of std::string. Therefore the naming reflects that. print without a stream argument on the other hand writes to stdout ...
68,200,797
68,209,703
Emscripten 2.0.8 to 2.0.24 caused breaking change
With Emscripten 2.0.8 I could build the wasm with following command emcc Test.cc -O3 -std=c++14 -I "F:\OpenCV4.5.2\include" "F:\OpenCV4.5.2\lib\libopencv_core.a" "F:\OpenCV4.5.2\lib\libopencv_calib3d.a" "F:\OpenCV4.5.2\lib\libopencv_features2d.a" "F:\OpenCV4.5.2\lib\libopencv_flann.a" "F:\OpenCV4.5.2\lib\libopencv_imgp...
The error message mentions a symbol missing from libopencv_core.a. The first thing to try would be recompiling everything (including all the dependencies) with the same compiler, in case the new one is not backwards compatible with the old one.
68,200,823
68,201,169
QVector find QPushButton by their name using Qt
I have a function which create QPushButtons void MainWindow::createButton(QFrame *parent, int x, int y, int w, int h, QString txt) { QPushButton* button = new QPushButton(parent); button->setGeometry(x,y,w,h); button->setText(txt); button->setObjectName("pushButton_" + txt); vecButtons.push_back(but...
even though you can find an object by its name like doing: QPushButton *button = parentWidget->findChild<QPushButton *>("pushButton_" + txt); the hasrd thing with this approach is that you need to keep a record of how the buttons are named... it would be better if you do as suggested in the comments, connect in the cr...
68,200,901
68,202,001
How to write program to generate the following pattern?
You can use recursion, loops, vectors or strings doesn't matter. Given an input N will generate N lines of the pattern. 1 2 1 2 3 1 3 1 2 3 2 3 4 1 4 1 2 4 1 3 4 1 2 3 4 2 4 2 3 4 3 4 5 Edit: I figured out how to do it doing a pre-calculation. It is possible to do it iteratively one step at a time? void per(vector<i...
There is an iterative solution that involves, at iteration i, going through the previously added patterns that start with j, where j goes from 1 to i-1, and adding i. Here's some Java code to illustrate: static List<String> pattern(int n) { List<String> res = new ArrayList<>(); for(int i=1; i<n; i++) {...
68,201,307
68,201,483
C++ trying to cast address to void* and assign to function pointer (so that my bootloader can jump to actual app)
I am writing a bootloader for an STM32, where I need to jump from bootloader to the real app. In C this works, because I can cast an address to a void pointer and assign that to a function pointer, and call the function pointer as follows: void jump_to_firmware(uint32_t address) { uint32_t reset_handler_add = *((vo...
The same code will compile in C and C++. You simple has to cast to the correct cast (in C++ you cant assign a void * to non void * pointer. It is much more strict than in C. void jump_to_firmware(uint32_t address) { uint32_t reset_handler_add = *((volatile uint32_t *)(address + 4)); void (*app_reset_handler)(vo...
68,201,487
68,202,730
Pass array of structs from C++ to GO
I'm trying to get an array of tensorflow box predictions from C++ to golang, but I'm not able to do it no matter what I do. I have a GO program that calls a function that does tensorflow detections in C++ using cgo. This all works and I'm able to get the predictions in C++. The problem is to transfer these predictions ...
Assuming your C function returns the array as PredictResult* and assuming you know the length of the returned array (in the example below I assume 10, but you can replace it by whatever works), this approach should work: // #include <stdio.h> // #include <stdlib.h> // // typedef struct PredictResult { // float Loc[...
68,201,518
68,201,760
C++ Reading memory from a string
I was trying to read a memory from explorer.exe. With a program process hacker I found that on the address 0xfa07f8 this string is stored: \??\C:\Program Files\Process Hacker 2\ProcessHacker.exe When I try to read the string of this address, I get only the first character of the string back. The '\' char. How can I rea...
You are reading wide characters from the process memory. MessageBoxA is for displaying "narrow" characters. To display wide characters, use MessageBoxW.
68,202,240
68,202,914
asio::async_connect vs asio::connect. Is asio::connect a non-blocking sync?
I'm using the asio 1.18.1 standalone version (no boost) and I wonder about the difference between asio::connect and asio::async_connect. I can tell myself why I need async for my server, because the point of async is being able to deal with a lot of data on a lot of different connections at the same time. But when it c...
I'm using the asio 1.18.1 standalone version (no boost) and I wonder about the difference between asio::connect and asio::async_connect. asio::connect attempts to connect a socket at the point of call and will block until connection is established. In other words, if it takes eg 20 seconds to resolve a DNS address, i...
68,202,502
68,202,720
Python file in C++ interface
My team and I were assigned different tasks. Some of my team implemented the interface with other parts using C++ language. On the other hand, I was assigned to implement speech recognition. When I did my research, I found that most of the speech recognition was in python, so I successfully used the speech recognition ...
You can embed python in the C++ application. Here is an example lesson and python documentation. I have done this where I wanted a user to be able to customize a solver. In that case I had the user write a python function then my app loads and runs it from C++. The only real roadblock I ran into in the past was makin...
68,202,848
68,203,623
How To Check bits in C++?
In C++ I wrote: bool ret_is_syscall = (ret_inst_data & 0x00000000000000FF) == 0x000000000000050f; but clion says it's always wrong, why? I am trying to check if last 4 are 0x050f
If you want to check that the least-significant 2 bytes of ret_inst_data have exactly the value 0x050F, then you need to use a mask of 0xFFFF: bool ret_is_syscall = (ret_inst_data & 0xFFFF) == 0x050F; As for why your original comparison is incorrect, let's look at just the least-significant two bytes of the numbers i...
68,203,384
68,208,960
When initializing a struct in a loop, why is the address always the same?
In c++17, I want to initialize a struct for 10 times and push the ptr which refer to them into a stack. And my code is like this below. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; stack<TreeNode*> s; for (int i = 0; i <= 9; i++) { ...
C++ constructs TreeNode node on every iteration of the loop. But it also deconstructs node by calling the (implicit) destructor at the end of each loop. That means the memory becomes available for reuse. And since the example is simple enough, that memory is indeed reused on every loop iteration. If you use new without...
68,203,510
68,203,722
Writing binary in python and read in c++
writing binary in python. # curr_feat is **numpy array** # curr_feat's shape is **(64,)** # curr_feat dtype is **float64** """ array([1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 0., 1., 0., 1., 1., 1., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., ...
Your fread doesn't look right. Try this: fread(tmp.data(),sizeof(double),maxDim,fp); This assumes that tmp is std::vector<double> and you've already resized it to maxDim. Trying to read into a vector that is not of sufficient size would be undefined behavior.
68,203,640
68,205,014
non-constexpr object usable in static_assert
I'll lead with the example #include <array> // Just in case std::array has superpowers... template <typename T, unsigned n> struct dummy { constexpr unsigned size() const noexcept { return n; } unsigned badsize() const noexcept { return n; } }; void fun() { std::array<int, 8> arr{...
There really isn’t any good reason this is allowed: it’s just that passing the address of the (non-constexpr) local variables as this to a member function is not considered in the rules for constant expressions. It’s even permitted to use this in the function called, but you can’t use any of the (non-static) member va...
68,203,759
68,213,572
Can I Use Macros To Convert std::tring To Corresponding Enum?
I am trying to return an enum based on a string value (the string is from a json file, if it matters) Basically, where in code I would write enumName::MyName, I want to be able to have something like std::string name = "MyName"; return enumName::name; // this gets converted to enumName::MyName Obviously that's incorre...
At last, I found a solution using the magic_enum library that was mentioned in a question linked by Jerry. I don't understand exactly how/why it works yet, but it's clean and does the job.
68,204,155
68,205,097
How to use QScopedPointer in lambda function?
I created a widget object using QScopedPointer utility and used it in a lambda connect function. As a result, it generated a compile time error. QScopedPointer<QMessageBox> errBox(new QMessageBox()); errBox->setText("some text"); QObject::connect(errBox,&QMessageBox::buttonClicked,this,[=](QAbstractButton *but...
The problem is not in the lambda. The problem is that, like std::unique_ptr, QScopedPointer does not cast automatically to a pointer, so your compiler probably complains about not finding a QObject::connect taking a QScopedPointer. Try: QObject::connect(errBox.get(), ...
68,204,452
68,205,361
a value of type "void" cannot be assigned to an entity of type "int" in CPP
So I'm trying to solve this question that was asked for me, And I'm very close on finding it by running the code, but I cannot because I get this C++ error message: a value of type "void" cannot be assigned to an entity of type "int" Let Q be an instance of an ADT per Row. Q.enqueue (x) adds an element x in a row. Q.de...
The compilation error is caused by the fact that pop does not return anything – you need to use front first, then pop. However, this is not what you're supposed to do; you are supposed to solve this by thinking and understanding how a queue works. Start with the first task: "Demonstrate the execution of this code by sh...
68,204,532
68,204,597
Function signature for potentially failed unique_ptr move?
Say I am writing a enqueue() function that takes in a unique_ptr, but I only want to claim its ownership when enqueue returns success. If the queue is full I want to leave the unique_ptr intact (user can retry with the same item later) bool enqueue(std::unique_ptr&& item){ if(!vector.full()){ vector.emplace(std::...
You could return a unique_ptr from your function. If it failed return the original. If it succeeded return an empty unique_ptr. Then you could call it like: #include <iostream> #include <memory> #include <vector> int counter = 10; template <typename T> std::unique_ptr<T> enqueue(std::unique_ptr<T> p) { if (--counte...
68,204,937
68,580,290
Potential bug in std::filesystem::remove_all with clang++
DO NOT TRY THIS AT HOME I am having a weird issue with std::filesystem::remove_all. I have written a program that writes N files to disk in a single directory and then deletes all the files afterward (there is a good reason for this). However, when I use std::filesystem::remove_all I get errors like this: filesystem er...
NOTE: This is not a solution to underlying and operating system problems, but a way to avoid it in C++. The change we need to make to the original code is "minimal". All changes is made to the try block try { std::filesystem::remove_all(base_path); } catch(const std::exception& e) { fmt::print("{}\n", ...
68,205,287
70,290,742
How to start using google tests on a Yocto(Open Embedded) System
I'm doing a project for ARM64 devices and am using Linux Embedded as the OS. I am trying to using Google Tests but when running bitbake, it is failing. Heres the error: | CMake Error at /#####/tmp-glibc/work/#####-oe-linux/project_name/1.0-r0/recipe-sysroot-native/usr/share/cmake-3.16/Modules/GoogleTestAddTests.cmake:4...
Already asked on https://unix.stackexchange.com/questions/656529/how-to-start-using-google-tests-on-a-yoctoopen-embedded-system This was a cross compiler issue as stated in the comments
68,205,494
68,207,493
Customizing QCompleter
I'm making a window that has a search(used QLineEdit). In every key pressing, there should be a completer for displaying results as a table. I want to use QCompleter but it only shows results just like a QComboBox. Now I'm going to customize QCompleter. It seems hard to me. What could you suggest?
You can set widget to completer using QCompleter::setPopup(). see completer example
68,205,633
68,215,255
When Cross Compiling (Linux to Windows) The Vulkan Loader There Are Many Undefined References to Vulkan Objects
When using the mingw-32 cmake the code from https://github.com/KhronosGroup/Vulkan-Loader fails to compile this is the cmake command I am using:x86_64-w64-mingw32-cmake -DVULKAN_HEADERS_INSTALL_DIR=/usr/x86_64-w64-mingw32/ -DVulkanRegistry_DIR=/usr/x86_64-w64-mingw32/share/vulkan/registry/ -DUSE_MASM=OFF .. Which Outpu...
The problem was that I had a MASM assembler. Which caused it to attempt an assembly thing that it failed to do.
68,205,811
68,205,890
Universal reference in constructor with type deduction
How one can use universal reverence in constructor in a templated class with type deduction. I tried all the options and nothing worked. Consider example: #include <vector> template<class T> struct A { A(T&& a) { } }; template<class T> struct B { B(T& a) { } }; template<class T> struct C { template<clas...
If you really want to use a universal reference, you have to go with struct C, because in A you actually declare a rvalue reference, not a forwarding (universal) reference. You can fix the deduction of C with a user defined deduction guide template <typename T> C(T&&) -> C<std::remove_cvref_t<T>>; Example Note that de...
68,206,310
68,207,570
How to center a QLine
How does one center a vertical QLine in the center of my horizontal QLine to form a cross. My current implementation does not center the vertical line appropriately. void crossWidget::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.setPen(QPen(Qt::black, Qt::SolidLine)); QLine originLine; ...
To draw a cross you need the middle point of the canvas geometry... your horizontal line (red one) will split your canvas into 2 identical shapes, 1 above the other.. so you need the middle point in the y axis. analog to this, your vertical line (blue one) will split the canvas in t identical pieces, so you need the mi...
68,206,495
68,207,793
How to embed a static library in a shared library (Linux)?
I have a static library which I do not have the source code, and need its symbols to be called dynamically from the LuaJIT FFI. As it is static, I can't load it dynamically, so I'm trying to embed it in a shared library and then load the shared library at runtime. Problem is that exported symbols of the static library ...
You can use the --whole-archive option to achieve this as seen here and in the docs: --whole-archive: For each archive mentioned on the command line after the --whole-archive option, include every object file in the archive in the link, rather than searching the archive for the required object files. This is normally ...
68,206,756
68,206,869
Correct use of template with a class member function
the concept of templates is quite difficult to grasp quickly. I need a class member function to iterate over vector of any objects and print them all out. Can I do this with using templates? I.e.: void SomeClass::printAll(std::vector< any type here> array) { for (auto & o : array) { std::cout << o <<...
Trying to grasp any non-trivial topic quickly is difficult. Just don't do it, but go slowly. That also means not trying to understand more than one thing at a time. I don't know why that function has to be member of a class. Make it a free function: template <typename T> void printAll(const std::vector<T>& vect) { ...
68,206,813
68,207,000
How to use a C header.h in multiple C++ files without getting multiple definition error?
I want to use a function that from the "func.h" file in the Wireshark open source project. I need to use the funct() function in multiple .cpp files, but I get the a multiple definition error. func.h: #ifndef func_h #define func_h #include<string> void *funct(char *cName) { std::stri...
You have two options: You move the implementation of the function in a separate .c/.cpp file, leaving in the header file only the declaration. Then you compile this source file, and link it with the rest of the program. Example: func.h #ifndef func_h #define func_h #include<string> void *funct(char *cName); #endif ...
68,207,383
68,209,593
opencv program compiled, but it does not execute ( c++ )
I found a below program in c++ on internet, #include <opencv2/opencv.hpp> using namespace cv; int main(void) { // Read image in GrayScale mode Mat image = imread("emily.jpg", 0); // Save grayscale image imwrite("emilyGray.jpg", image); // To display the image imshow("Grayscale Image", image)...
Actually I did not set the path to opencv dlls after I built opencv using mingw32-make. After setting C:\opencv\build\bin to PATH variable of environment variables I could see the output. Regards
68,207,763
68,207,783
Indexing std::vector<bool> works with true values, but does not work with false values
I want to run a simple program in C++ in which there are two vectors - one is a std::vector<int> and the other is a std::vector<bool> of equal length. The value of the boolean vector at an index decides whether the value of the integer vector will be printed or not. Here is a copy of the program I am trying to run: #in...
The line vector<bool> b(true, arr.size()); will create a vector, with 1 element, of value arr.size(). Thus, the loop will get out of bounds. It's crucial to remember that when we construct a container this way, we say: "How much of what". In this case: "We need arr.size() elements with value true": vector<bool> b(arr.s...
68,207,805
68,207,869
Can not I increase iter2 after erase the object iter2 pointed out previously?
the runtime error happens at the below line. Could you explain why the error happens? Can not I increase iter2 after erase the object iter2 pointed out previously? iter2++; //// error happened Best regards, #include<iostream> #include<vector> using namespace std; int main(void) { vector <string> v; v.push_...
Erase function has return value - iterator pointing to the next object in the container. So just use it like this: iter2=erase(iter2); Now you can increment it all you want.
68,208,240
68,208,810
Pointer to incomplete class type "SDL_SysWMmsg" is not allowed
I try to get the hwnd handler from SDL focus event I cannot compile this part with visual studio 2019 it says pointer to incomplete class type "SDL_SysWMmsg" is not allowed around pMsg-> if (e.type == SDL_SYSWMEVENT) { SDL_SysWMmsg* pMsg = e.syswm.msg; if (pMsg && pMsg->msg == WM_SETFOCUS) ...
You need to include that header. Currently the compiler only knows, that SDL_SysWMmsg is a struct, and it is perfectly fine, when used as a pointer to a structure, because every pointer is just an address to the memory in the same format for all types (read more). If you need to know the layout of the structure, then y...
68,208,797
68,208,892
How to iterate over a tuple of elemenets that have the same base class
Iterating over a tuple is a common question in the C++ world and I know the various ways it can be done - usually with recursion and variadic templates. The reason is that a tuple usually holds different element types and the only way to correctly handle every type is to have a specific overload that matches this type...
You might just using std::apply: std::apply([](auto&...args){ (args.call_base_method(), ...); }, tuple); Else to answer your question, you might do something like: template <std::size_t... Is, typename tuple_type> my_class_base& at_impl(std::index_sequence<Is...>, tuple_type& tuple, size_t n) { my_class_base* base...
68,209,462
68,209,489
Why is my overloaded subscript operator for rvalue not called
I have looked up and down stack overflow and keep finding the same examples which I think I have implemented. I am trying to implement an associative array. I know there is std::map but I'd like to do the implementation myself for better control and better understanding. I have overloaded the subscript operator for lva...
The issue in question Turns out, you're asking the wrong question. You're having a logic problem, which in this particular case has nothing to do with ref-qualification of the member function. In your code, I can see no trace of any use where the AssocArray is being an rvalue (on which we want to call operator[]). To h...
68,209,652
68,210,337
How to make custom input cin-like function?
While being simple to write, the downside of the cin function is slow when compared to others like scanf or getchar. Now, I have my own quick input function to replace, but are rather troublesome to write: void read(signed long long &var){ var = 0; register char neg = getchar(), c; while(neg != '-...
While being simple to write, the downside of the cin function is slow when compared to others like scanf or getchar Are you really sure? Did you benchmark it? And what are your requirements? C++ streams are very feature rich which comes at a cost... Now, I have my own quick input function to replace... I did not be...
68,210,001
68,210,377
Character encoding not consistent (Win32 API)
I am developing a Win32 desktop application with C++ where the target-language is Swedish. As a result of that I rely on Unicode to properly format and display any given string. However, I encountered a very peculiar issue where strings consisting of non-english characters (such as å, ä, ö) work in one part of the code...
The problem is indeed, as the title states, "Character encoding not consistent". And to be precise, that's the character encoding of Window.cpp compared to the character encoding of Application.cpp. I suspect the environment is Visual Studio, which can handle files in multiple encodings. But for source code that contai...
68,210,877
68,211,001
Why is there no realloc equivalent to the new/delete family?
As the title says, I know there is no equivalent to C's realloc in the new/delete family of operators. I have already found this question that lightly touches on the subject but it doesn't really answer the "why". My questions are: Why is it a bad idea to be able to realloc objects? Why is it a bad idea for an object ...
Realloc has two behaviors, one of them is not acceptable in the C++ object model. Realloc can increase the size of a piece of storage, or it can allocate new storage and copy everything from the old storage into the new. The thing is, C++ doesn't think of objects as just bags of bits. They're living, breathing types th...
68,211,094
68,211,201
I want to write to a file by using ofstream but it gives me nothing
I have created three directories with _mkdir(), and I want to create a text file in the last one, but it gives me nothing. Here is the code: #include "stdafx.h" #include <direct.h> #include <fstream> #include <iostream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int t; st...
You create a file in the working directory instead of the last created directory. Replace file.open("filetest.txt", ios::out||ios::in); with path = path + "\\filetest.txt"; file.open(path.c_str(), ios::out|ios::in);
68,211,106
68,211,468
I want to know how lua_call works
I'm trying to use lua in C++. Here's my code. int main() { lua_State* L = lua_open(); luaL_openlibs(L); luaL_loadfile(L, "test.lua"); lua_call(L, 0, 0);//First lua_call, just it Runs .lua script lua_getglobal(L, "funcFromLua"); int a = 10; lua_pushinteger(L, a); lua_call(L, 1, 0);//Se...
Your comments in the code are correct. The first lua_call executes the contents of the loaded script, test.lua. This defines a global variable funcFromLua. The second lua_call calls funcFromLua with a set to 10.
68,211,433
68,211,612
Structure data changes when using constructor in C++
The first code works as expected. I am trying to work with double pointers inside structures. #include "bits/stdc++.h" using namespace std; struct Node{ int data; Node *left; Node* right; Node(int val) { data = val; left = right = NULL; } }; struct Triplet{ Node** node; in...
In your non-constructor version, t.node holds the address of root. t.node = &root; In your constructor version, t.node holds the address of temp, which is indeed a temporary. It becomes a dangling pointer once temp no longer exists. node = &temp; In order to match your non-constructor version, your constructor needs...
68,212,028
68,212,436
A class for rational number (p/q) with overloading + and << operator
I wanted to add two rational numbers and display them in the form of p/q using overloading the operators + and <<. I'm using friend function, because the function for addition and display are taking multiple and different types of parameters. Inside the addition function I'm performing a normal addition of fractions, l...
This Rational R3(); declares a function called R3 that returns a Rational and takes no parameters. It does not define R3 to be a default constructed Rational. Change the line to any of the below Rational R3; Rational R3{}; auto R3 = Rational(); auto R3 = Rational{};
68,212,323
68,212,571
implementing an iterator (something like from STL) for my own custom vector template class in C++
I have a my own container from GeeksforGeeks website I got from there code of container in below. I like to create an iterator class and capability of which will enable me to use for loop and function like begin and end in my container and for loop will be like something MyClassForIterator iter; for(iter=mycontainer_it...
Yes, totally possible in C++ just define a nested iterator class in your vector. Here I define a forward iterator, for your case you might want to pick a different category: template <typename T> class vectorClass { T* arr; int capacity; int current; public: struct iterator { // You need ...
68,212,807
68,213,301
Operator adding a constant int to a variable
I have a class called Mark and I want to create an operator to add a const to a variable. In this case, I have a const int mark variable in the class, and I want to make it so that val += mark will add the const mark to the val. This is what I have tried. Mark& Mark::operator+=(const Mark& m_mark) { if (*th...
The problem is when compiler wants to compile this expression: m_mark >= 0. Here compiler should compare the function parameter m_mark of type Mark with the int 0. There is no overloaded operator >= for this comparison. So compiler tries to use its built-in operator. To do so, it should cast m_mark to a built-in type. ...
68,212,855
68,213,906
Storing data in map<string, vector<std::pair<string, string>>> c++98
I have file named Bird.lst. I am trying to read its contents and store the data in a map<string, vector<pair<string, string>>>. The idea is to store the bird's name in the string and its attribute values in the vector. Also, there are some attributes that I don't need (vaccinated, babies, sale). While inserting into th...
When you are parsing a value string into an attribute_pair, you are looking for specific attributes to ignore, and if you find one then you don't parse the value, but you are still inserting the empty attribute_pair into the attributes vector. That is where the empty lines in your output are coming from. Change this: ...
68,212,906
68,212,976
Is it possible to make a static library from a header only file through visual studio?
By following some tutorials, I was successfully able to make a static library through visual studio , but it only works if there is a corresponding .cpp file for the .h file. Take these two files for example .h void print(); .cpp void print() { std::cout << "printing from lib"; } I went I to project->properties->...
You can force the compiler to run on a header file, but for your own sanity and those of future maintenance developers, just put a .cpp file with the single line #include "library.h" Note that libraries distributed in header files usually do so because of templates and will not make a useful static library.
68,213,012
68,213,013
What is if consteval needed for?
C++23 is going to introduce if consteval. Where is this going to be used and how does it differ from constexpr if?
if consteval detects if a constexpr function is called in a constant expression context. The proposal motivates its introduction for the case where one intends to call a consteval function from a constexpr function. To understand what that means we consider the following example. Let's assume we have a consteval functi...
68,214,962
68,215,116
Assign TicTacToe player position to a bitboard representation
I have 2 separate boards for 2 players: X and O. Now I'd like to make sure if an entered position (int x, int y) is valid but I've got no idea of how should I convert it to bitboard representation and compare it with given board states and it's doing me head in. Also wrote a helper function to see the board states bin(...
Well you can treat your bitstring as a flattened 2d array. To convert a 2d index into a 1d one you can simply do x * width + y So to set the matching position in the board you can do int move = 1 << (x * 3 + y) since a TicTacToe board is 3 wide and 3 tall. You can then check if there already is an X or O at that posi...
68,215,052
68,215,189
C++ enum behaviour with loops
I am trying this code int n,k; enum Throws {R, P, S}; int userInput; for(int i=0;i<3;i++) { cin>>userInput; cout<<(Throws)userInput; } why does this code not take R as input and provide 0 as output and wait for the next input rather gives 000 as output for any of the values expected output: input-R ...
I am not completely sure if that is what you want, but the following lets the user enter a character, then assigns corresponding enum value to a variable and then prints again the corresponding character. None of this is for free, if you want to have such mapping you need to implement it yourself: #include <unordered_m...
68,215,377
68,215,456
What is Wrong With my Code?, How can i improve it any further?
The problem is that my program does not give accurate average for numbers with more than 9 digits. Can somebody point out what am I doing wrong and how do I fix that? Is there anything I can do to improve the code any further? The code is #include <iostream> using namespace std; int main(){ cout << " ...
Your NUM1 and NUM2 are of type int. int variables have a maximum value, on most systems it is 2147483647. When NUM1 = 1111111111 and NUM2 = 1111111111, then NUM1 + NUM2 will be bigger than the the maximum value 2147483647. This is called overflow. Technically in c++ this is undefined behaviour, but on most systems it...
68,215,484
68,215,567
How to append a string to a argv
I want to remove a file, the name of which is given as an argument to the program; but, as the filetype will remain constant (.bat), I want it to be automatically given by the program (e.g. running deletefile.exe script will delete "script.bat" (which is in the same directory)). I have seen this question, but the solut...
The right-hand side of your file_to_remove = argv[2]+".bat"; statement is attempting to concatenate two char* strings using the + operator; you can't do this, and at least one of the operands must be made into a std::string. You can do this by constructing a temporary std:string, like this: file_to_remove = string(argv...
68,215,645
68,215,747
Unable to draw rectangle over webcam video OpenCV C++
Im trying to create a rectangle ROI over webcam video. But this code is crashing #include "opencv2/opencv.hpp" #include <iostream> #include <bits/stdc++.h> using namespace std; using namespace cv; int main(){ VideoCapture cap(0); if(!cap.isOpened()){ cout << "Error opening video stream or file" << endl; ...
the core issue is (-215:Assertion failed) !fixedSize() || ((Mat*)obj)->size.operator()() == Size(_cols, _rows) in function 'create' (the gstreamer line is just a warning) this error comes from that line (it's not obvious but copyto involves a Mat::create call): frame.copyTo(frame(Roi)); copyTo gets the destinatio...
68,215,653
68,215,791
Makefile pattern rules on multiple subdirectories
So I have a GNU Makefile to compile all .cpp files from my Game directory and its subdirectories into .o files in build/obj folder (no subdirectories in that one). My problem is that only the first file in the list is compiled, I know the problem is that I need a build pattern, but I can't think of a way to implement t...
This is wrong: $(OBJ_FILES): $(OBJ_DIR)/%.o: $(SRC_FILES) It says, each object file depends on ALL the source files. The SRC_FILES variable expands to the same list of files every time, so for every object file the list of prerequisites is the same, so every time you compile it you use $< which expands to the first p...
68,215,913
68,216,093
Using a parameter pack to generate objects
I am looking to create an object that can instantiate a class on command. The reason why I want to do it like this, is because I have to create instances of an object, that all have the same initial parameters read from a file, but I want to load those parameters only once. My solution is using lambdas, but it feels ve...
Is there a better way, by storing Args... data somehow, and then using the stored parameter pack later on? Not sure about better, but you can store the arguments in a std::tuple and then use std::make_from_tuple to construct the object each time. That would look like #include <functional> #include <tuple> template ...
68,216,630
68,216,850
C++/CMake installable libraries with conflicting .so names
I am having issues with conflicting names of libraries in installed c++ packages on a linux system. Both packages are built into installable apt packages using cpack. There are two packages being installed (A and B). Do note that although I have control over these packages and so I can change the CMake and whatnot, the...
Linux dynamic library resolution is purely by the name of the needed library. All of the search paths are checked until a matching file name is found, so you can't have a duplicate .so filename. However, it's really only the library filename that has to be unique. You can keep the CMake namespace names for all intern...
68,217,380
68,217,964
When turning a char with multiple characters into a string with stringstream, spaces dissapear
This is the part of a code code: time_t now = time(0); char* date_and_time = ctime(&now); cout << date_and_time << endl; string date_and_time_string; stringstream ss; ss << noskipws << date_and_time; ss >> noskipws >> date_and_time_string; cout << date_and_time_string << endl; I cant understand how date_and_time is a ...
I cant understand how date_and_time is a char when it has multiple characters It is not a single char, it is a char* pointer to a null-terminated array of chars. when I want to get it to a string, it just stops when spaces come. Because that is how operator>> works. It stops reading on whitespace or EOF, whichever ...
68,217,401
68,217,467
c++ list not resizing after set difference
Consider the following code: #include <algorithm> #include <iostream> #include <list> int main() { std::list<int> v = {1, 3, 4}; std::cout << v.size() << std::endl; v.resize(0); std::cout << v.size() << std::endl; } after compiling the output, as expected, is 3 0 Now I add a set difference. #include ...
This is because it is undefined behavior. The last parameter to std::set_difference is an output iterator. You are passing in v.begin(). This returns a pointer to the beginning of an empty list. In order for your intended code to work as advertised, the *iter++ operation of the output iterator must add new values to th...
68,217,547
68,218,112
Reading the data in the file in a certain way
i have some txt file . content of this file like that ID: 01 REQ: 22 12 34 RES: 62 12 34 69 51 6D 69 6E 65 i want just 2. row but without REQ: part(22 12 34) ifstream file("simulation.txt"); int counter=1; if (file.is_open()) { string line; while (getline(file, line)) { // cout << line << endl; ...
So you have stated that you can get the line you want. So from here, we can simplify the problem to just this: std::string line = "REQ: 22 12 34"; std::string only_the_bit_i_want = ???; There are lots of ways, we can approach this. Here is one. Do you know that the line will always have "REQ: " at the front? If so tha...
68,217,699
68,218,247
SQL Select with conditional data for next row
I want to retrieve some close stock data and compare it with the two dates I choose. For example, If I want to see the change in a stock price from 1/1/20 and 1/1/21, I would like it to go through all the stocks listed and return to me a comparison of the prices on those two days. The comparison is the change in close,...
When you want to combine 2 rows of input into 1 row of output, you can do this with a join: SELECT sdfrom.Code, sdfrom.DateInSeconds as FromDate, sdfrom.Close as FromClose, sdto.DateInSeconds as ToDate, sdto.Close as ToClose FROM StockData sdfrom INNER JOIN StockData sdto ON (sdfrom.Code = sdto....
68,218,117
68,218,280
Simplest and most efficient way to turn raw bytes in an unsigned int to a string
In C++ what is the simplest and most efficient way to turn the raw bytes in an unsigned int to a string (to read for example by ASCII codification)? An uint64_t contains 8 bytes, I would like to interpret these bytes as (char*), append the termination flag ('\0'), and convert to string. This way I can store the "raw" d...
I'll leave my original answer down below, but the most efficient solution appears to be also the simplest (proposed by @Remy Lebeau down below): std::string string(reinterpret_cast<const char *>(&value), sizeof(value)); If you're using C++17, you can also use std::string_view and avoid a copy and heap allocation altog...
68,218,227
68,218,277
Ncurses is mysteriously using all my CPU for no reason
I'm trying to write a program like nethack with ncurses. The program works fine, draws me a box and everything perfectly while not eating up much of my CPU. After I added the while(true) loop, it doesn't draw my box and it eats up 100% of my CPU when I move my "character". #include <iostream> #include <curses.h> int ma...
nodelay(stdscr, TRUE); Let's take a look at what the curses manual page says about this: nodelay The nodelay option causes getch to be a non-blocking call. If no input is ready, getch returns ERR. If disabled (bf is FALSE), getch waits until a key is pressed. If that wasn't clear: in nodelay mode getch...
68,218,370
68,218,410
Is there a data structure that allows storing more than two elements?
So, what I am searching for would maybe look like this (without the xxx): const xxx<std::string, std::string, void (*)(std::string)> commands = { {"exit", "Exit Program", f1}, {"test", "Start Test", f2}, {"help, h", "Help Screen", f3} }; As far as I know, lists, vectors, maps, etc. can't do that. Is there anythi...
At a basic level, you can use std::tuple: std::tuple<std::string, std::string, std::function<void(std::string)> command which can hold any number of types. If you want more than one, use a std::vector<std::tuple<...>>: using Command = std::tuple<std::string, std::string, std::function<void(std::string)>>; using Command...
68,218,539
68,230,048
Creating Numerical Recipes random number generator in Python
I would like to generate random numbers from the U[0,1] distribution. I am trying to recreate the random number generator from Numerical Recipes Chapter 7.1. Unfortunately, my C++ is not particularly strong and so I am having some issues following the code! I was wondering if someone could help clarify my understandin...
Thank you to Scheff's Cat, all super helpful answers. I've knocked up something that seems like it's working in Python but I've also taken your advice and gone slightly less adventurous with my random number generation for the time being.
68,218,731
68,220,025
Ncurses mvwaddch() isn't working before getch()
When I run this code, the two for() loops that draws the box isn't drawn. I've tested with gdb and it shows that the program does execute that two loops but somehow it isn't appearing. If the while(true) loop is removed, the box gets drawn. So, why? #include <iostream> #include <curses.h> int main(){ std::pair<int,...
The issue is you have used getch() instead of wgetch(win). Another thing to be mindful of is the size of the window you declare, which can cause a similar error.
68,219,060
68,219,284
Why splitting a line separated by spaces with stream in C++ runs infinitely?
Before, when I was writing C++, I often used getch() for validation. However, now I am turning into competitive programming, I cannot use getch(); I had to use cin or getline. Thus, today, I replicated an instance of splitting a string using stringstream: #include <string> #include <iostream> #include <sstream> #includ...
The reading operator >> does not change the underlying string. It uses an inner position of a next char to read. int main() { int n; std::istringstream in; // could also use in("1 2") in.str("1 2"); in >> n; std::cout << "after reading the first int from \"1 2\", the int is " << n <...
68,219,357
68,219,520
Intializing class member variables in constructor
I recently started working on C++, I observed one strange behaviour while initializing the member variables through the initializer list. //Demo.h #ifndef DEMO #define DEMO #include <iostream> class Demo { public: Demo(); explicit Demo(int x); }; #endif //Demo.cpp #include "Demo.h" Demo::Demo() { std::co...
You do not initialize a data member when you just declare it in the body of the class. Actually you do not create anything at all when you write a definition for the class, it is just a blueprint for creation of future instances of the class. Later, when you make an object of the class type, the object is created by me...
68,219,389
68,219,592
Calculating JMP instruction's address for trampoline hook
I am trying to calculate the relative address offset from one instruction to another. I understand the basic calculation, and why I have to -5 (to cater for size of jmp and instruction size) (Calculating JMP instruction's address) The question is, what if I want to jump not to start of a code but some specific instruct...
This works because len equals exactly the number of bytes of instructions (5) that precede the desired one, which I presume was the whole point (you want to copy the instructions that will be jumped over, and maybe modify them later on?). The jump instruction starts at gateway+len, and so EIP at the jump will be gatewa...
68,219,862
68,231,610
Codelite IDE not opening on windows 10
Installed the latest version of Code lite IDE-15.0.04. Was working till yesterday but now not opening. No error or messages flashing. Simply not opening. Tried troubleshooting as well. OS - Windows 10
The main reason that this happens is due to unclean shutdown and corrupted configuration files. To easiest solution is to delete the user settings folder. Note that Uninstalling CodeLite does not help, since the user settings are kept. So: Close CodeLite Delete the folder %appdata%\CodeLite Start CodeLite This should...
68,220,298
68,220,371
When I have to call base class in event methods in QT?
I have myWidget class. His base class is QWidget. I would like to have in myWidget class, event methods like keyPressEvent(QKeyEvent *event),paintEvent(QPaintEvent *event) or mousePressEvent(QMouseEvent *event). I don't know when I have to call base class and when I don't have to call base class in this methods. When I...
That will depend on whether the base class implements any logic in those methods, for example if you override the keyPressEvent method of a QLineEdit and you don't invoke QLineEdit::keyPressEvent(event) then you won't get the default behavior, the same for paintEvent from other widgets. In conclusion, you must invoke t...
68,220,404
68,221,041
How to disable -Wvexing-parse for one line in clang?
Clang enables -Wvexing-parse by default, which is a good thing. Sometimes, however, I would like to declare a function (f()) within a scope of another function (g()) as g() is the only function that needs to be aware of f(). Is there a way to tell clang "I do mean to declare a function" via a comment on a particular li...
Something along the lines of #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wvexing-parse" const char *f(); #pragma clang diagnostic pop std::cout << f() << std::endl; Should do what you want. But it's actually not necessary to disable the warning if you declare your function f() properly as a fu...
68,220,696
68,257,863
How to change the background color of CIPAddressCtrl?
I tried to change the background color and text color of the IP Address Control in MFC. Once, I have changed the text color and background color, but the points between the Edit controls are not displayed. My code is as follows: BEGIN_MESSAGE_MAP(KIPAddressCtrl, CIPAddressCtrl) ON_WM_CTLCOLOR() ON_WM_PAINT() EN...
The reason why the separators disappear is because of the FillSolidRect call in the KIPAddressCtrl::OnPaint() handler, overwriting anything the default implementation had done. Coloring the IP Address Control the way you want isn't supported. While the embedded Edit Controls request a color from their parent (the IP Ad...
68,220,759
68,222,844
find() vs binary_search() in STL
Which function is more efficient in searching an element in vector find() or binary_search() ?
The simple answer is: std::find for unsorted data and std::binary_search for sorted data. But I think there's much more to this: Both methods take a range [start, end) with n elements and and a value x that is to be found as input. But note the important difference that std::binary_search only returns a bool that tells...
68,221,024
68,221,126
Why must I provide 'operator ==' when 'operator <=>' is enough?
#include <compare> struct A { int n; auto operator<=>(A const& other) const { if (n < other.n) { return std::strong_ordering::less; } else if (n > other.n) { return std::strong_ordering::greater; } else { r...
Why must I provide operator== when operator<=> is enough? Well, mainly because it's not enough :-) Equality and ordering are different buckets when it comes time for C++ to rewrite your statements: Equality Ordering Primary == <=> Secondary != <, >, <=, >= Primary operators have the ability to be rever...
68,221,186
68,221,254
Why is qCDebug() macro defined in the way it is?
The qCDebug() macro has a simple declaration, but what are the benefits of using the "degenerate for-loop" instead of a simple and straightforward if? #define qCDebug(category, ...) \ for (bool qt_category_enabled = category().isDebugEnabled(); qt_category_enabled; qt_category_enabled = false) \ ...
Look at the example. if (condition) qCDebug(...); else exit(0); If for-loop is used, the expanded code behaves as expected. if (condition) for (...; category().isDebugEnabled(); ...) QMessageLogger(...); else exit(0); In case of if-condition else-branch is always attached to the nearest if, and you get th...
68,221,315
68,221,910
C++, How to Ensure Aligned Memory Using mmap()?
I am currently allocating memory using mmap like this: void *void_new_block = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); Now I want to improve performance on 64 bit cpus thus I need my block to reside between addresses which are multiplication of 8 For that I need 2 things: To en...
mmap always allocates entire pages. If addr is NULL, then the kernel chooses the (page-aligned) address at which to create the mapping [...] If addr is not NULL, then [...] on Linux, the kernel will pick a nearby page boundary (on systems other than Linux, it still has to pick a page boundary, but it might not be nea...
68,221,523
68,221,609
How to Convert Void* into size_t?
I have the following function: size_t calc_allign(size_t num) { return ((num + 7) & (-8)) - num; } And want to use it like this: int start_allign = calc_align (sbrk(0)); But I am getting error: error: no matching function for call to 'calc_align' candidate function not viable: cannot convert argument of incomplet...
How may I convert void* ie a pointer to number? You can reinterpret_cast a pointer type to std::uintptr_t (or the signed equivalent). You can then further convert to another integer type such as std::size_t and that conversion can be implicit. In theory, the latter conversion may be lossy on systems where std::size_t...
68,221,982
68,222,528
For loop not terminating once condition is met using pthread
I was writing a piece of multithreaded code when I found that a for loop was not terminating. The starting code was approximately like this: for(int i = V-1-tid; i >= 0; i-=NTHREADS){ */ stuff */ } V and NTHREADS are constants and tid is the thread id passed using pthread_create. I then removed everything from the l...
The code has undefined behavior - a function has return type void * but does not return anything. The compiler gets confused and generates an endless loop. Make sure to enable and listen to compiler warnings, they tell you that: 1.cpp: In function ‘void* foo(void*)’: 1.cpp:7:1: warning: no return statement in function ...
68,222,152
68,557,689
How do I use Spy++ on this menu that keeps disappearing if I click outside of it?
I want to log the messages of this menu using Spy++. Usually, if I want to log the messages of a window, I would use Spy++ and drag the "Find Window" tool over it. But in this case, if I drag the tool over this menu, the menu disappears because I clicked outside it. Is there any workaround to this? A little more info...
Actually I figured it out myself. You can just log messages of the parent window with the logging options set to also log messages of child windows.
68,222,338
68,222,445
How would I reproduce the functionality of the Windows winusb driver on Linux? Do I even need to?
I need to implement an application on Linux that drives a USB connected device (a medical instrument). The application will be written in C++ (2011 standard). The current application is written for Windows 10 in C# and uses the standard Winusb driver enumerated for the device. I have a complete protocol specification f...
Alternatively, is there a Linux library (or driver) that provides more or less the same functionality as winusb for Linux? One way is using directly the generic kernel API for USB (see the Asynchronous I/O parts to get the interrupts): https://www.kernel.org/doc/html/v4.15/driver-api/usb/usb.html This is the strict L...
68,222,499
68,222,567
Why do I get a compile-time error when trying to return values from a mock?
I'm just starting to use gMock (gTest 1.11.0). The call expectations work correctly, but when I try to indicate the value which needs to be returned during a call to a mock, I encounter a compile-time error that I don't understand. Here's the relevant piece of code: #include <gmock/gmock.h> #include <gtest/gtest.h> #in...
You may need to specify using ::testing::Return;
68,224,037
68,224,555
Binding a std::function to a member function in c++?
I'm working with Open3D library using the following function: bool open3d::visualization::DrawGeometriesWithAnimationCallback ( const std::vector< std::shared_ptr< const geometry::Geometry >> & geometry_ptrs, std::function< bool(Visualizer *)> callback_func, const std::string & window_name = "Open3D", int ...
Turns out you need to use std::placeholders in your std::bind function. The following code works: std::function<bool(open3d::visualization::Visualizer*)> f = std::bind(&MeshHandler::UpdateMesh, dispatcher.m_MeshHandler, std::placeholders::_1); open3d::visualization::DrawGeometriesWithAnimationCallback({ dispatcher.m_Me...
68,224,475
68,253,732
How to display Find dialog in a WebView2 control?
I have got an old C++ MFC app upgraded to use the WebView2 web browser control, based on Edge. Otherwise I have got it working fine, one of the remaining issues is opening the Find dialog in it via the main MFC app Edit-Find menu item or via Ctrl+F (which is also intercepted by MFC framework). What I have now is: m_web...
AFAIK, WebView2 currently has no support for you invoking or otherwise controlling the find in page dialog. You can also refer to this thread. There is a similar thread in GitHub and the official hasn't given a solution. You can use Ctrl+F keystroke directly in WebView2 control or provide feedback about this issue on W...
68,224,506
68,224,680
Initialise vector size within a map
In my header file, I have a map field: std::map<std::string, std::vector<double>> priceSMA; I know the length of the vector, which is 50. How do I go about setting the size of this vector? If the field was a vector on it's own, It's simple to set the size. But since it's nested within a map I'm lost. The below throws ...
This: priceSMA = std::map<std::string, std::vector<double>(50)>(); is not correct, because the size of a vector is not part of its type, but for the map, the second template parameter is the type of mapped_value. On a related note, you don't need to explicitly call the default construtor. The map is already default co...
68,224,700
68,224,801
Pointers Reassignment
cpp newbie here If I initiate a two pointers, like int* a = new int(1); int* b = new int(2); and I want to give the pointer a a new value, shoud I delete its current value before? In other words, what is more correct, doing int* a = new int(1); int* b = new int(2); a = b; or int* a = new int(1); int* b = new int(2); ...
Colloquial speech is a little misleading here. We say "delete the pointer" but more correct would be to say "delete the object pointed to by the pointer". Think of the int and the int* as two seperate entities (they really are). You can reassign to the pointer as much as you want, thats no problem for the pointer. But ...
68,224,743
68,226,436
Why is my swig generated tcl code missing methods at runtime?
I am using swig 4.0.2 to generate a package for tcl use. The source .i file contains lots of classes and the generated _wrap.cpp file contains the all the classes with their methods as I would expect and everything compiles ok with no warnings. However, for at least 1 class, when I come to call a method on a instance f...
The problem is caused by copy and paste code. A second swig package exists in the Project I'm working on. It redeclares the same class interface but with some methods missing! If I sync up the declarations then everything works. This leaves the question of how the original code with unsynced swig interfaces (that was g...
68,225,219
68,225,614
POST request with C++ curl
I try POST JSON on my Server, but it doesn't work. When I do post server is empty and doesn't have a file. How do POST correctly? CURL *curl; string data; CURLcode res; std::ifstream myfile; myfile.open("test_4.json"); string content( (istreambuf_iterator<char>(myfile) ), (istreamb...
libcurl is c, not c++. It expects char*, not std::string. Also from https://curl.se/libcurl/c/CURLOPT_POSTFIELDS.html: The data pointed to is NOT copied by the library: as a consequence, it must be preserved by the calling application until the associated transfer finishes. This behavior can be changed (so libcurl doe...
68,225,394
68,225,461
operator== marked 'override', but does not override
I am have an issue while overriding the base class operator==. Here is the code. #include <iostream> #include <vector> using namespace std; template <typename T> class IClient { virtual const std::vector<T>& getID() = 0; virtual bool isEqual(const std::vector<T>& anotherID) = 0; virtual bool operator==(const IC...
SeviceClient and IClient are different types. So, bool SeviceClient::operator==(const SeviceClient&) hasn't base declaration.
68,225,770
68,225,874
sorting vector of pair using lambda predicate crashing with memory corruption
I am trying to sort a vector of pair but it is crashing if I provide a lambda. #include <stdio.h> #include <vector> #include <math.h> #include <iostream> #include <algorithm> using namespace std; vector <int> findClosestElements (vector <int>&arr, int k, int x) { vector <pair<int, int>>temp; int j = 0; for (cons...
Your lambda does the comparison in wrong way. You need to fix it to conform to strict weak ordering, e.g. returning a.second < b.second only when a.first == b.first: sort (temp.begin (), temp.end (),[&](const auto & a, const auto & b) { return (a.first < b.first ? true : (a.first > b.first ? false : (a.second < b.sec...
68,225,849
68,226,256
C++ Malloc Doesn't call mmap or brk?
On ubuntu 18.04 I wrote the following c program and ran it with an input of 100 #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { int x; scanf("%d", &x); usleep(1); void *tmp = malloc(x); usleep(1); free(tmp); return 0; } The output in terminal was: (with strace) stra...
Isn't this strange? No. why malloc didn't use brk or mmap for the allocation of memory (between the 2 calls for nanosleep()). Scenario 1: You enabled optimisation, and the optimiser sees that omitting the call to malloc is not observable, and thus it was never called. Scernario 2: malloc was called, but it presumab...
68,225,858
68,226,350
A non static member reference must be relative to a specific object c++
I'm trying to test a boolean condition but for some reason, it won't even let me call the function in my window class. I have tried creating an object and inheriting the functions and still getting the same message. it will let me do if(Attach::attachProc) This always returns true when it's meant to return false in the...
You are trying to use methods inside the window procedure. The problem is that the window procedure is a free function, meaning that it has no this object, but only a HWND handle. You must first identify the Window object for which the window procedure is called. A common way is to use SetWindowLongPtr to store a point...
68,225,883
68,226,449
How to retrieve an index within a lambda for a concatenated range?
I have the following code: #include <range/v3/all.hpp> #include <deque> #include <iostream> auto main() -> int { using namespace ranges; namespace views = ranges::views; auto v1 = std::deque<double>({ 123.080, 123.110, 123.105, 123.090, 123.095 }); auto v2 = std::deque<double>({ 123.100, 123.120, 123....
Global index seems the wrong way. I would do something like: auto is_extrema = [](auto r3){ return r3[0] < r3[1] && r3[1] > r3[2] || r3[0] > r3[1] && r3[1] < r3[2]; }; auto pv = vc | views::sliding(3) | views::filter(is_extrema); Demo
68,226,019
68,270,172
One-liner for explicit instantiation of fixed set of types
I have a fixed set of four types A, B, C and D, and a large amount of class and function templates that work with these types. To reduce compile times, I would like to put the definition of these templates into .cpp files and explicitly instantiate the templates for this fixed set of types. However, the explicit instan...
For now, until someone finds a better solution, the following works well enough: #define INSTANTIATE_FOR_ALL_TYPES(TYPE) template class SomeClass<TYPE>; #include "instantiator.hpp" with the contents of instantiator.hpp being /* lack of a header guard is intentional */ INSTANTIATE_FOR_ALL_TYPES(A) INSTANTIATE_FOR_ALL_T...
68,226,360
68,226,594
inserting variable names into functions
I don't know what this is called, but I need to insert a variable name into a function. How do I reduce the following code? I've get the skeleton of the function written, but don't know how to make it work. void function(int x, int y, char name) { ((x <= ([name]_x + [name]button_w)) && (x > [name]button_x) ...
You can't do that; variable names only exist in source code and are not data. Define a suitable data type and pass instances of that type to the function. struct Button { int x; int y; int w; int h; }; bool inside(int x, int y, const Button& button) { return x <= button.x + button.w && x > button.x...
68,226,461
68,226,613
sort a string array using string length with std::vector in cpp
I have a function in cpp that i want to use to sort an array of strings according to the individual length of each string, i tried to compare the length of an element at a particular index with the length of the element residing in the next index. If the length of the next index is lower than the length of the string i...
Here you go. #include <iostream> #include <vector> #include <algorithm> #include <string> void printVec(std::vector<std::string>& vec) { for(auto&& v:vec) { std::cout<<v<<std::endl; } } int main() { std::vector<std::string> vec {"abc","ab","a","abcd"}; printVec(vec); std::sort(vec.begin(), v...
68,226,770
68,230,713
Clang-Tidy : readability-function-cognitive-complexity.DescribeBasicIncrements value has no effect
While running clang-tidy on an example code provided at https://clang.llvm.org/extra/clang-tidy/checks/readability-function-cognitive-complexity.html refer function3. with the below command clang-tidy.exe Example.cpp -config="{Checks: '-*,readability-*',CheckOptions: [{key: readability-function-cognitive-complexity.Thr...
This is the source of your problem: Additional info: clang version 12.0 DescribeBasicIncrements option was introduced in this commit which was not part of clang 12.0 Install the latest clang version and it should work as intended.