question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
72,991,514
72,991,712
runtime error: addition of unsigned offset/UndefinedBehaviorSanitizer: undefined-behavior
I am not able to find where is my vector going out of bound. This is solution of leetcode question 695. Error: Line 1034: Char 34: runtime error: addition of unsigned offset to 0x610000000040 overflowed to 0x610000000028 (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-...
I expect if(x<n && y<m && grid[x][y]==1 && !vis[x][y]) { should be if (x>=0 && y>=0 && x<n && y<m && grid[x][y]==1 && !vis[x][y]) { Notice in the error addition of unsigned offset to 0x610000000040 overflowed to 0x610000000028. In other words the unsigned offset is negative (when regarded as a signed quantity). Alway...
72,991,965
72,993,204
C++20 concept fails to compile when template class object instantiated with value
Please refer to the following C++20 code: template<bool op> class Person { const bool own_pet; public: Person() : own_pet(op) {} consteval bool OwnPet() const { return own_pet; } consteval bool OwnPetC() const { return true; } void PatPet() const {} }; template<typename T> concept MustOwnPet = req...
The problem is that the parameter named obj is not a constant expression. Thus it cannot be used in an evaluated context where a constant expression is required. For example, we cannot use obj as a template nontype parameter(TNP) as TNP must be compile time constant which obj is not. Which compiler is correct? This s...
72,992,551
72,992,714
Inaccuracy in code which returns the next permutation of an array
I was solving a question on leetcode with the description: The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation o...
Your issue is that the break statement in second loop is outside the if block. if (nums[i] > nums[index]) { j = i; } break; // <--------- this should be inside if Putting it inside, gives the correct result. if (nums[i] > nums[index]) { j = i; break; } Demo: https://godbolt.org/z/147We9c4q
72,992,713
72,996,020
Adding searcher in package.searchers with lua c api?
Issue I want require in lua to be able to find module in a game assets archive using Physfs. After some searche, i must add a c function to the package.searchers table ? I tried to do so, but sadly i can't manage to. I'm new to lua and embeding lua, so it is definitly not helping. One thing i don't get is, the package ...
I guess i have to post and answere to mark this post as solved. First things, package table was not global because i was loading libraries wrong. i need to use luaL_requiref as mentioned by Egor Skriptunoff or directly luaL_openlibs. Then after that, because it is now global, i can just do something like that for exemp...
72,992,732
73,139,976
Pass pointer of a non static member function to another non static member object
NOTE: In this context, the term "ISR" is not really addressing ISR vectors. There are a lot of tricks in the drivers. One of them is handling with the interrupts generated by the radio tranceiver chip. SX1276_LoRaRadio driver has a thread that checks the actual interrupt source. This is because all these things are wor...
As @Wutz stated in his third comment, the correct way is using mbed::Callback. Here is my new constructor: ProtoTelecom::ProtoTelecom(LoRaRadio *Radio, c_TC_Manager *tcm) : manageCommands() { this->Radio = Radio; this->tcm = tcm; //Inizialize the radio newRadioEvents.tx_done = mbed::Callback<void()>(th...
72,992,809
72,997,115
CEF - how to get a variable from JS to С++
Please help me, I've been suffering for two weeks, I can't understand if it's possible in CEF to get the value of a variable from the JS code to a C++ variable? For example: I am executing js code in a browser window using the method CefFrame::ExecuteJavaScript: (*frame).GetMainFrame()).ExecuteJavaScript("const elem = ...
You might have noticed, if you type rect.x in the console in the developer tools, it echoes the variable value. It should have hinted you, how to retrieve variable values. CefRefPtr<CefV8Context> v8_context = frame->GetMainFrame()->GetV8Context(); if (v8_context.get() && v8_context->Enter()) { CefRefPtr<CefV8Value> r...
72,992,990
72,996,355
Possible causes for icc (2019) with -O3 -march=native on Xeon Gold 6126 producing slower exe than -O3 -xCORE-AVX512?
The purpose of the question is to ask about possible causes regarding the program's behaviour as a function of icc 2019's compilation flags, considering two phenomena and the information provided in the notes below. A program can run three types of simulations, let's name them S1, S2 and S3. Compiled (and ran) on Intel...
An acceptable possible explanation was outlined in the comments, it read: Tiny differences in tuning choices for code-gen might result in alignment differences that end up mattering more. Especially How can I mitigate the impact of the Intel jcc erratum on gcc? on Skylake-family CPUs if -march=native or -xCORE-AVX512 ...
72,993,218
72,993,401
C++ iterator for map derived class
I have a class that internally has an instance of map: template<typename K, typename V> class my_map { private: std::map<K, V> mmap; Internally to the class I need to create an iterator for templated types, how can I do this?
To avoid confusion with typename keyword. I suggest to do the following template<typename K, typename V> class my_map { private: std::map<K, V> mmap; public: typedef typename std::map<K, V>::iterator iterator; typedef typename std::map<K, V>::const_iterator const_iterator; iterator begin() {return mmap...
72,993,691
73,177,082
Disagreement between GCC and clang about "typename" keyword
I was compiling the following code and GCC seems to accept the following code. #include <map> template<typename K, typename V> class my_map { private: std::map<K, V> mmap; public: typedef std::map<K, V>::iterator iterator; typedef std::map<K, V>::const_iterator const_iterator; iterator begin() {return...
asking about different behaviors of compilers. It seems that Clang has not implemented this C++20 feature yet. This can be seen from compiler support documentation. This means clang is not standard compliant. C++20 feature Paper(s) GCC Clang MSVC Apple Clang Allow lambda-capture [=, this] P0409R2 8 6 19.22* 1...
72,993,739
72,994,105
How to pass reference value to a std::function from one class to another class
I have the following scenario. File Box.h #pragma once #include <functional> class Box { public: Box() :m_data(45) {} void set_callback(std::function<int(int, int& c)> cb) { f = cb; } auto get_box_dimension(void) { return f(4,m_data); ...
std::bind is rather old-fashioned and quirky. Most uses are simpler with a lambda expression. Specifically you tripped over this detail (see cppreference): If some of the arguments that are supplied in the call to g() are not matched by any placeholders stored in g, the unused arguments are evaluated and discarded. I...
72,993,742
72,993,840
Don't print space after last value with iterator
I'm having a problem with a beginner concept in competitive programming extra space in print may cause wrong answer judgment I want to iterate through a container like map or set but last value should not have a space #include <iostream> #include <set> using namespace std; int main() { set<int> st = {1,2,3}; ...
The standard class templates std::set and std::map do not have random access iterators. So this expression x!=st.end()-2 is invalid. If you compiler supports C++ 20 then you may write for example set<int> st = {1,2,3}; for( size_t i = 0; auto x : st){ if ( i++ != 0 ) std::cout << ' '; cout << x ; } Or you cou...
72,993,789
72,993,850
What memory adress are we referencing to when we use a const reference to an rvalue
Consider the follwoing code: int main() { const int& number=10; cout << number << endl << &number << endl; return 0; } As output I get: 10 0x62ff08 As far as I know "10" is an rvalue without memory adress, so where does the memory adress come from?
When you wrote: //------------------vv---->10 is a prvalue and temporary materialization will result in an xvalue const int& number = 10; temporary materialization happens as can be seen from temporary materilization: Temporary materialization occurs in the following situations: when binding a reference to a prvalue...
72,994,189
72,994,414
Strange C++ delete[] statement in MS C++
On some very old code base, we have this kind of statement: delete [i+4] v; Where v is indeed an array and i is an integer. This code is in VS2010 but still compiles in VS2019. Working demo What's the meaning of this? Is it, or was it something specific to Microsoft C++?
delete [i+4] v; where v is pointing to a dynamic array that was created using new is not valid in C++. This seems to be a msvc bug which has been submitted here.
72,994,320
72,994,790
Building CMake project with Boost libraries on GitHub Actions gives error "Could NOT find Boost"
I'm trying to build my CMake project on GitHub Actions workflow. Everything is working locally on Ubuntu 22.04 LTS and building a Docker image, but not when using the same OS on GitHub Actions. The error is the following: CMake Error at /usr/local/share/cmake-3.23/Modules/FindPackageHandleStandardArgs.cmake:230 (messag...
github.com will give you a fresh runner for every job. See here https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#using-a-github-hosted-runner for details. Thus it is not possible to prepare the machine in one job and use it in a later job. You should move the installation of th...
72,994,701
72,995,350
How to convert a vector of parent pointers to another in c++?
How to convert two parent pointers in c++? This is the code. // base class class B { public: virtual ~B() {}; // other code }; class A { public: virtual ~A() {}; // other code }; // child class class C1 : public A, B { public: virtual ~C1() {}; // other code }; class C2...
Your code has typos. Missing public in inheritance of B when defining C<x> breaks stuff. After this is fixed sidecast does the job as it should: dynamic_cast conversion - cppreference.com b) Otherwise, if expression points/refers to a public base of the most derived object, and, simultaneously, the most derived object...
72,994,895
73,045,940
constructing completely private and anonymous static singleton
I was trying to think of a way how to deal with C libraries that expect you to globally initialize them and I came up with this: namespace { class curl_guard { public: curl_guard() { puts("curl_guard constructor"); // TODO: curl_global_init } ~curl_guard() { puts("curl_guard...
The real solution was pretty simple - the code can't be separate and needs to be in one of compilation units that are used by the user of the library. libcurl needs to be initialized globally, and initialization is NOT thread safe, because libraries it depends on also cannot be initialized in thread-safe manner, so it ...
72,994,952
72,999,085
Convert Gdiplus::Region to ID2D1Geometry* for clipping
I am trying to migrate my graphics interface project from Gdiplus to Direct2D. Currently, I have a code that calculates clipping area for an rendering object: Graphics g(hdc); Region regC = Rect(x, y, cx + padding[2] + padding[0], cy + padding[3] + padding[1]); RecursRegPos(this->parent, &regC); RecursRegClip(this->par...
I rewrote the solution completely, it seems to be working: // zclip is ID2D1PathGeometry* inline void Render(ID2D1HwndRenderTarget *target) { ID2D1RoundedRectangleGeometry* mask = nullptr; ID2D1Layer* clip = nullptr; if(ONE_OF_PARENTS_CLIPS_THIS || THIS_HAS_BORDER_RADIU...
72,995,554
73,019,268
How to use cppcheck-suppress command to elimnate the error about "a parameter should be passed by reference"
In function "writeFile" below it has the following signature: writeFile(std::string fileId, std::string otherVariable){} when I run it, an error: Function parameter 'aFileId' should be passed by const reference. [passedByValue] is recieved. However I don't want to pass it by const reference because the function is g...
You have to activate inline suppressions in general when calling cppcheck. Add the command line option --inline-suppr.
72,995,769
72,995,950
Using Boost Python 3.10 and C++ Classes
I'm really confused with initialzing C++ classes when usign boost::python. When compiling the follwing code with CMake I get no error, warning or something else at all: #include <boost/python.hpp> #include <iostream> class Test { public: Test(int x); ~Test(); }; void greet() { Test test(10); std::cout...
Just use a constructor and destructor like: #include <boost/python.hpp> #include <iostream> class Test { public: Test(int x) {}; // Change ~Test() {}; // Change }; void greet() { Test test(10); std::cout << "Test" << std::endl; } BOOST_PYTHON_MODULE(libTestName) { Py_Initialize(); using namesp...
72,995,844
72,997,881
c++ 17 std::filesystem can not run on other (windows 10) computer
I have a program, compiled using MinGW on and for windows 10, I want this program to run on other peoples computers, even if they do not have MinGW or any c++ compilers installed. Normally, this is easy. I just include the exe file and the dll files for any third party libraries, and it does indeed work ... unless I us...
Did you check that the libstdc++-6.dll Is available or the relevant libraries are statically included static linked libs
72,995,849
72,996,088
Statically build and linking with CMake
I'm trying to wrap my head around statically linking c++ applications using CMake. I have built libcurl statically: ./buildconf ./configure --disable-shared --with-openssl make -j$(nproc) make install Which produces a static /usr/local/lib/libcurl.a: $ ldd /usr/local/lib/libcurl.a not a dynamic executable My ...
For libraries, like CURL, that have first-class CMake package support, you should use it. Here is how I linked to CURL statically. First, we download and build CURL: $ git clone git@github.com:curl/curl.git $ cmake -G Ninja -S curl/ -B _build/curl -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=NO $ cmake --build _build...
72,996,011
72,996,692
C++ program gives up when reading large binary file
I'm using a file from the MNIST website as an example; specifically, t10k-images-idx3-ubyte.gz. To reproduce my problem, download that file and unzip it, and you should get a file named t10k-images.idx3-ubyte, which is the file we're reading from. My problem is that when I try to read bytes from this file in one big bl...
Concerning OPs code to open the binary file: std::ifstream inputStream {path}; It should be: std::ifstream inputStream(path, std::ios::binary); It's a common trap on Windows: A file stream should be opened with std::ios::binary to read or write binary files. cppreference.com has a nice explanation concerning this top...
72,996,356
72,996,937
How to find the Postion of all matching substrings in a QStringList
i am looking for a way to find the cell position of all matching substrings in a QStringList. The List is filled form a txt file looking like that: 10:36:50,590/2002/1800 10:36:50,621/2002/1801 10:36:50,652/2002/1802 10:36:50,684/2002/1803 10:36:50,715/2002/1803 10:36:50,746/2002/1803 10:36:50,777/2002/1803/0/0/T...
You cannot use indexOf for this because it would only return you one index, and it seems that you are looking for multiple. I would read the file line by line, check each line if it contains what you are looking for, and take note of that, effectively this pseudo code: initialise a counter to zero. initialise a positio...
72,996,800
72,996,897
how can i initialize a bi-dimensional vector in a class in C++?
I need to define its size in runtime, so I need a vector. I tried the following, but I get a compiling error: error: 'V' is not a type #include<iostream> #include<vector> class graph { private: int V; std::vector<int> row(V); std::vector<std::vector<int>> matrix(V,row); public: graph(int v): V(v) {} ...
The compiler considers these lines: std::vector<int> row(V); std::vector<std::vector<int>> matrix(V,row); as member function declarations with parameters that have unknown types and omitted names. It seems what you need is to use the constructor's member initializer list instead, like the following: class graph { priv...
72,996,984
72,997,030
what is this syntax mean is c++ "class_name: class_ptr_1(nullptr), class_ptr_2(nullptr) {}"
I am not able to understand the syntax of class_name: class_ptr_1(nullptr), class_ptr_2(nullptr) {}
It seems you mean class_name() : class_ptr_1(nullptr), class_ptr_2(nullptr) {} ^^^ It is a constructor definition with a mem-initializer list. That is the class data members class_ptr_1 and class_ptr_2 are initialized in the mem-initializer list. Here is an example #include <iostream> #include <string> stru...
72,997,015
72,997,561
Calling-convention for the 'this' parameter on Linux x64
I have a scenario where I need to call a function from LLDB (but it could be any C++ API) on Linux x64, from an app written in a different language. For that reason, I need to properly understand the calling-convention and how the arguments are passed. I am trying to call SBDebugger::GetCommandInterpreter, defined as: ...
I figured it out. I was focusing on the arguments but the trick was the return value. Quoting the System V calling convention: A struct, class or union object can be returned from a function in registers only if it is sufficiently small and not too complex. If the object is too complex or doesn't fit into the appropri...
72,998,188
72,998,722
getting N values from getline(cin) for different data types
I have created a program, which requires user to define at least 2 arguments(3rd is optional). Arguments are: Command(string type) Date(custom type/class) Event(string type) - Optional. I have come up with the following idea: int main() { Database db /*my custom class */ string command; vector<string> arg...
But unfortunately, Date date = arguments[1]; doesn't work. Correct, because arguments[1] is a std::string, but Date does not have a constructor that accepts a std::string. So add one, eg: class Date { public: Date() { setDate(0, 1, 1); }; Date(int new_year, int new_month, int new_day) { ...
72,998,231
73,000,113
How are object properties accessed internally?
In reference to this question: How are variable names stored in memory in C? It is explained that in C, the compiler replaces variable names from code with actual memory addresses. Let's take C++. I wonder how object properties are accessed in that context? obj.prop So obj gets replaced by the actual memory address. D...
For simple cases and hiding the language lawyer hat: obj.prop is *(&obj + &Obj::prop). The the second part is a member pointer, which is basically the offset of the property inside the object. The compiler can replace that with an absolute address if it knows the address of the obj at compile time. Assuming it has an o...
72,998,527
72,998,784
Resolving circular dependency between concept and constrained template function
I am trying to learn more about concepts. I ran into some problems with circular dependencies between concepts and constrained template functions, and I've reproduced these errors in a simple example. I have a concept, Printable, that I want to be satisfied if and only if operator<< is defined on a type. I also have a...
To my surprise, std::vector<int> is not considered Printable, even though operator<< works on it. It doesn't. Not really anyway. When you say std::cout << x; works what you really mean is that you can write that expression from wherever and that works - "from wherever" including in the definition of Printable. And in...
72,998,544
72,998,609
What is the difference between alignof(i) and alignof(decltype(i))?
#include <iostream> alignas(16) int i; int main() { std::cout << alignof(i) << std::endl; // output: 16 and warning std::cout << alignof(decltype(i)) << std::endl; // output: 4 } What does alignof(i) and alignof(decltype(i)) do? I would have expected alignof(i) not to compile and alignof(decltype(i)) to ret...
alignof(i) is the alignment of the i variable, which is explicitly being set to 16, regardless of its type. alignof(decltype(i)), aka alignof(int), is the natural alignment (sizeof(int), ie 4 in this case) for all int variables that are not otherwise aligned.
72,999,271
72,999,497
CEF - how to call callback c++ form JS-code
How can I call a C++ function using JavaScript? For example, I am executing js code in a browser window using the method CefFrame::ExecuteJavaScript like this: (*frame).GetMainFrame()).ExecuteJavaScript("const elem = document.getElementsByClassName("my_class")[0];const rect = elem.getBoundingClientRect(); alert(rect.x ...
It can be done in two ways. They are almost equal: you can create several native functions at once with CefRegisterExtension, and you can create a single native function with CefV8Value::CreateFunction. The example bellow is just a sketch, nowhere can test it, small issues are possible, but the idea is clear: class MyA...
72,999,708
72,999,808
Passing a vector pointer and looping it to change its value
I'm trying to pass a vector to a function, loop over it, and modify the values before sending it back, but I'm having a very hard time with the pointer and reference to make it work: I understand that itr is a pointer. I'm confused about resource on the for loop. I believe it to be a reference, but I keep getting the e...
For starters the first parameter of the function changeResourceValue is declared with the qualifier const void changeResourceValue(const vector<asset>* resources, asset value){ It means that you may not change elements of the vector pointed to by the pointer resources. So you need at least to remove the qualifier con...
72,999,850
72,999,926
C++ Is it safe to change an exported DLL function from int to BOOL?
I'm dealing with a legacy DLL that has may things that started from DOS C code back in the day where there was no concept of a boolean. But the DLL is still in active development and still evolving. Many of the older exported methods have signatures like: _declspec(dllexport) int IsConditionTrue(); By the appeara...
BOOL is declared as typedef int BOOL;, so I would think that there should be no difference to the compiler or to already-compiled consumers of exported function, right? Yes, typedef is just syntactic sugar and has no impact on the resulting ABI. That said, BOOL does not make the code any safer for the end user, it ca...
73,000,107
73,000,189
What does the XXXXXX in an sprintf format argument of "/tmp/%s-XXXXXX" mean?
In the following code, it seems XXXXXX asks to generate random characters to replace it. What does XXXXXX mean here? Is this some special reserved symbol in sprintf? sprintf(tempName, "/tmp/%s-XXXXXX", filename.c_str());
More context would help, but judging from the array name tempName, this sprintf call is probably composing a template for use with mktemp(), mkstemp(), mkdtemp() or a similar function. The Xs do not have any particular meaning for sprintf, but are interpreted by the next function called with tempName. These POSIX funct...
73,000,611
73,000,633
Shared variables in two threads
I'm writing a ros node with two threads to support client dynamic reconfiguration in C++. One thread is responsible for subscribing to a topic /error which is float, taking the sum of value sum_of_error, and incrementing batch_size. Another thread is responsible for taking the average of the value if batch_size reaches...
while (batch_size < BATCH) { } The apparent intent of this is to wait until another execution thread increments batch_size until it reaches BATCH. However because this access to batch_size is not synchronized, at all, this results in undefined behavior. Other execution threads synchronize modifications to batc...
73,000,648
73,044,227
read multiple root tree file one by one
I am a beginner, This is related to assignment work. For one root tree file (here pp1.root), I can use the below code. If I am having 10 root files and I need to read each file one by one to get the statistical parameters. void pbtrue() { TFile *f = new TFile("pp1.root"); TTree *T1 = (TTree*)f->Get("T1"); int Tch...
Now I can do this using std::string and std::to_string to form filename and use its c_str method to get pointer to underlying character array (C-style string) to pass it to TFile constructor if it doesn't accept std::string: // ... for (int i = 1; i <= 100; ++i) { string filename = "pp"+to_string(i)+".root"; TF...
73,000,778
73,000,861
Get object type without template parameters
I need to be able to have any object that takes a single bool as a template parameter, and obtain the type of that object without the bool, so I can then create a similarly typed object but of a different bool. This is what I came up with, but it does not compile. How can I achieve this aim please? template<template<...
A little ugly, but this works: template<bool NewBool, template<bool> typename ClassName, bool TheBool> ClassName<NewBool> FT(const ClassName<TheBool>&); template<bool X> struct T {}; int main() { T<true> t; decltype(FT<false>(t)) f; } Online Demo
73,001,485
73,003,513
C++ compiler reordering read and write across thread start
I have a piece of multithreaded that I'm not sure is not liable to a data race because of compiler reordering. Here is a minimal example: int main() { int x = 0; x = 5; auto t = std::thread([&x]() { ++x; }); t.join(); return 0; } Is the assignment of x = 5 guaranteed to be before the thread start?...
Short answer: The code will work as expected. No reordering will take place Long answer: Compile time reordering Let's consider what's going on. You put a variable in automatic storage (x) You create an object that holds a reference to this variable (the lambda) You pass that object to an external function (the thread...
73,001,544
73,001,675
How do I get a value from a class table in C++
Basically, I have a class in C++ class Commands { public: void help(); void userid(); void getCmd(std::string cmd) { } }; void Commands::help() { WriteLine("\n \ --------------------------------\n \ [ userid, id ]: Get's the UserID of your player\n \ [ placeid, game ]: Get's the game ID\n \ ...
Use std::map or std::unordered_map to map std::strings to std::function that represent the functions to be called, then overload operator[] to provide easy access to the map without exposing the map. #include <string> #include <map> #include <functional> #include <iostream> class Commands { // added: a map of stri...
73,001,623
73,001,671
Storing parameters as key value pairs in a text file and should be able to perform operations on the values
I'm trying to write a code in C++ which basically stores key value pairs in a file separated by a space. The condition is that if the key is already present, it should just update the value(increment by 1) and write that updated value to the text file. And if the key is not already present, it should write the entire k...
So the code is a bit confused with some debugging stuff mixed in. But if you look at what you've written you are missing a couple of pieces. You convert the string to an integer value = stoi(str); so you can increment it. But you never convert the integer back to a string, instead you do this line[pos+1] = value+1; whi...
73,001,864
73,002,048
How to write string stream to ofstream?
I am trying to write a stringstream into a file but it not working. int main() { std::stringstream stream; stream << "Hello world"; cout << stream.rdbuf()<<endl;//prints fine std::ofstream p{ "hi.txt" }; p << stream.rdbuf();//nothing is writtten p.close(); std::ifstream ip{ "hi.txt" }; ...
Internally, the stringstream maintain a read pointer/offset into its data buffer. When you read something from the stream, it reads from the current offset and then increments it. So, cout << stream.rdbuf() reads the entire stream's data, leaving the read pointer/offset at the end of the stream. Thus, there is nothing ...
73,001,893
73,001,921
How to sort object's array with function pointer and template?
Here is my test code: template<typename T> void sort(Result* n_obj, int n, bool (*cmp)(T d,T f)){ for(int i = 0; i<n-1; i++){ for(int j = i+1; j<n; j++){ if((*cmp)(d,f)){ swap(n_obj[i],n_obj[j]); } } } } Here is my problem - I get this output: In function...
You can not use the generic function arguments of the function pointer as arguments. That makes no sense. You need to specify them: template<typename T> void sort(Result* n_obj, int n, bool (*cmp)(T,T), T d, T f){ for(int i = 0; i<n-1; i++){ for(int j = i+1; j<n; j++){ if(cmp(d,f)){ ...
73,002,024
73,002,055
Hotel Bookings Possible C++
Hotel Bookings Possible C++ from InterviewBit website. I've been working on it and I couldnt find a solution for it. The question is: A hotel manager has to process N advance bookings of rooms for the next season. His hotel has C rooms. Bookings contain an arrival date and a departure date. He wants to find out whether...
You're processing departures before arrivals. In the sample test case, someone stays from days 1~2. That means, the room is occupied on day 2; and is only vacated on day 3. For some departure date x, you should process it on x+1 as that's when the guest leaves. So, you can simply update this loop: for(int i=0;i<n;i++){...
73,002,349
73,009,133
add_subdirectory not working with custom source macro
I'm pretty new to CMake, and have just gotten into setting it up. I've gone ahead and implemented a simple opengl boilerplate, whose tree is like this CMakeLists.txt include glad KHR src glad glad.c CMakeLists.txt main.cpp CMakeLists.txt lib .gitignore .gitmodules CMakePresets.json README.md My Root CMak...
So, I seem to have finally fixed my problem. Here's how I did it. SO, as @fabian pointed out, PARENT_SCOPE only refers to the immediately above scope. NOT the top-level scope. To fix this what I did was to add set (sources ${sources} PARENT_SCOPE) to each and every CMakeLists.txt file. Although this is a hacky workarou...
73,002,840
73,003,266
Internal storage requirements of C++ UnorderedAssociativeContainer
I've been reading about C++ containers and iterators. For my question, I think the following observations are relevant: UnorderedAssociativeContainer is a Container. value_type is std::pair<const Key, T>. iterator is LegacyForwardIterator and dereferencing it returns container's value_type. Does this imply that any U...
Technically, no. The implementation of the standard library is not constrained by the language standard (in fact, it is impossible to implement the full standard library without relying on compiler extensions). An implementation could rely on some exceedingly unusual processor functionality to tightly pack the elements...
73,003,115
73,005,013
Is storing initializer_lists undefined behaviour?
This question is a follow up to How come std::initializer_list is allowed to not specify size AND be stack allocated at the same time? The short answer was that calling a function with brace-enclosed list foo({2, 3, 4, 5, 6}); conceptually creates a temporary array in the stackspace before the call and then passes the ...
First of all, copying a std::initializer_list does not copy the underlying objects. (cppreference) and container some_container = { 1, true, 5, { {"itemA", 2}, {"itemB", true}}}; actually compiles to something like container some_container = { // initializer_list<ref> ref{1}, ref{true}, rer{5}, ref{ // ...
73,003,136
73,003,172
How to solve this strange bug? (c++)
#include <iostream> #include <vector> int main() { std::string human = ""; std::vector <char> translate; std::cout << "Enter English words or sentences to tranlate it into Whale's language.\n"; std::cin >> human; for (int a = 0; a < human.size(); a++){ if (human[a] == 'a' || human[a] == 'i' || human[a]...
Reading from an ifstream into a string will break on whitespaces, hence cin >> human only reads what's effectively the first word. Change this: std::cin >> human; To this: std::getline(cin, human); While we're here, let's cleanup the code: #include <iostream> #include <unordered_set> #include <string> int main() { ...
73,003,597
73,003,698
Assigning multiple elements of array in one statement(after initialization)
std::string mstring[5]; mstring[0] = "veena"; mstring[1] = "guitar"; mstring[2] = "sitar"; mstring[3] = "sarod"; mstring[4] = "mandolin"; I want to assign the array like above. I don't want to do it at initialization but assign later. Is there a way to combine 5 statements i...
You can do that by using std::array<std::string, 5> instead of the raw array. For example #include <iostream> #include <string> #include <array> int main() { std::array<std::string, 5> mstring; mstring = { "veena", "guitar", "sitar", "sarod", "mandolin" }; for ( const auto &s : mstring ) { ...
73,004,256
73,016,588
UWP.C++ How to toggle Adaptive Brightness from BackgroudTask
now i have PointerTo.BrightnessOverride from MyBackgroudTask aaa_bo = BrightnessOverride::GetDefaultForSystem();// OK VStudio & Phone I can Set Brightness from BackgroundTask.exe, but How can i toggle Adaptive Brightness ON / OFF ? I created class NullObject, but still compile error aa_OBJ_BO->SaveForSystemAsync(Null...
You could take a look at BrightnessOverride.SaveForSystemAsync(BrightnessOverride) Method. The method mentioned that if a NULL object is passed in, the system turns on auto-brightness. So you might need to call this method with a null value to turn on the auto-brightness.
73,004,374
73,004,430
Writing and reading data to binary file using fstream
I need to create a binary file and store inside it 10 numbers, and after that go one by one element of file and replace it with it's opposite number. #include <iostream> #include <fstream> int main() { std::fstream file("numbers.dat", std::ios::app | std::ios::in|std::ios::out|std::ios::binary); for (double i = 1; ...
Your mode is wrong in two ways. Firstly std::ios::app | std::ios::binary does not allow you to read from the file, and secondly it means that all writes will be at the end of the file irrespective of the current position. The -1 file position that you see means the seekg call has failed, presumably because you tried to...
73,004,754
73,005,819
How to get a string within "\n" in c++?
Suppose I'm having- string s="Hello Hi Hey\n""Bye Bye good night"; Now,I want to get the string within "\n" ,i.e I want to get "Hello Hi Hey" How can i do so? I've thinking of stringstream, but it's not possible as "Hello Hi Hey" itself contains space.
Now,I want to get the string within "\n" ,i.e I want to get "Hello Hi Hey" How can i do so? I've thinking of stringstream, but it's not possible as "Hello Hi Hey" itself contains space. Just instantiate a std::istringstream and use std::getline() to read the separate lines into strings: string hellohihey; string b...
73,005,897
73,005,920
implementing a linked list and it doesn't produce output
I am implementing a linked list but it doesn't display any output. implementing a linked list with 4 elements and making fuction insert and insertathead and display. #include <bits/stdc++.h> using namespace std; // class node to make node element. class node { public: int data; node *next; node{ } ...
First you want to move insert, insertAtHead and display out of the Node class. These are list functions have have no need of special access to Node. Also you should initialise head to NULL (representing the empty list). This means changing main like this node *head = NULL; insert(head, 1); insert(head, 2); insert(head,...
73,006,563
73,012,136
How to add extra data to a tree item?
I'm trying to add extra data to a wx Tree Item using wxTreeItemData, but I cannot construct a wxTreeItemData object, because the constructor doesn't have any parameters. Here is my sample code: wxTreeCtrl treeCtrl = new wxTreeCtrl(parentWindow); treeCtrl->AddRoot("Root"); treeCtrl->AppendItem(root, "item", -1,-1, "some...
You indeed need to derive your class from wxTreeItemData, as you've done, and you need to cast the returned value of GetItemData() to the correct value, i.e. write DataItem *data = static_cast<DataItem*>(treeCtrl->GetItemData(item)); This is safe as long as you only pass actual DataItem objects (and not something else...
73,006,977
73,007,520
How to close a QDialog that uses a different ui file in Qt?
I've been trying to close a QDialog that uses a separate ui file. The dialog is used in a slot of a different class (TaskManager). Sorry for the question but I couldn't find a workaround anywhere. I'm creating a ToDo App as a University project (first year, first time using C++ and Qt): as the user clicks on the "Add T...
connect(ok, &QPushButton::clicked, this, dialog.close()); - your connect is wrong, you don't pass a pointer to a member function as forth parameter but the return value of dialog.close(). Also the context is wrong -> connect(ok, &QPushButton::clicked, &dialog, QQDialog::close). btw: Your whole approach on how to create...
73,007,067
73,007,123
Return function pointer based on input type parameter C++
I have a class for managing function pointers. I want to use a template or something to call the function stored in the class via the [] operator. For example, I can do functions[malloc](0x123), which calls malloc via a pointer to the malloc function stored in the class. This is what I have: #include <cstdlib> #include...
Works well with if constexpr #include <cstdlib> #include <type_traits> class DelayedFunctions { decltype(&std::malloc) malloc = std::malloc; decltype(&std::free) free = std::free; public: template <typename T> constexpr T operator[](T) { if constexpr (std::is_same_v<T, decltype(&std::malloc...
73,007,186
73,007,259
Threads calling function in another class
I am trying to understand the multithreading in c++. I am trying to call a function in another class using two threads as shown below: vmgr.h class VMGR{ public: int helloFunction(int x); }; vmgr.cpp #include"vmgr.h" #include<iostream> int VMGR::helloFunction(int x){ std::cout<< "Hello World="<< x << s...
The constructor of std::thread uses std::invoke passing copies of the constructor parameters. std::invoke can, among other alternatives, be called with member function pointers. This requires syntax different to the one used in the question: std::thread t1( &VMGR::helloFunction, // member function pointer vm, ...
73,007,388
73,007,453
How can I set a c++ variable to permanently be the sum of two others?
I want to permanently set one variable to be the sum of two other integer variables in c++, such that the value of the sum variable will change as either or both of the original two variables change: #include <iostream> int main() { int myInt = 3; int myInt2 = 5; int mySum = myInt + myInt2; // Something ...
You cannot achieve this with the exact same syntax you're suggesting, but you can create a type containing 2 references to int that behaves reasonably similar to an int resulting in the desired behaviour: class Sum { public: Sum(const int& s1, const int& s2) noexcept : m_s1(s1), m_s2(s2) {} operato...
73,007,468
73,007,577
Is a unique_ptr with custom deleter never invoked when initialized with nullptr
In scenarios where you interface with C libraries which manage the creation/deletion of pointers, I saw a recent buggy code where a struct was managed by a unique_ptr before the pointer was actually pointing to a valid memory location, so the raw ptr was nullptr before it was passed on to a C API. An example in code to...
[...] what actually happens, is the destructor never invoked because it is UB to change the memory location of unique_ptr's managed raw ptr? You never change the pointer managed by the std::unique_ptr to anything other than null and that's why the delete_foo is never invoked, not even with null as parameter. There's ...
73,007,806
73,007,967
Why won't the pixels I try to draw into VGA memory show up?
I'm working on a little operating system, and I'm running into issues drawing pixels. It seems that no matter what I do, I am unable to get anything to appear. I'm trying to follow along with an article by OSDev Wiki, but so far all that works for me is text outputting. Here's my assembly bootloader code: [org 0x7c00]...
The assembly code sets mode 0x03 (80x25 Text), you have even commented it as such. Nowhere does it appear that you are setting mode 0x13 (320x200 256 colour). Your code is writing to both the text and graphics frame buffer. Only the text framebuffer will be rendered in text mode. You cannot render both text and graphic...
73,007,915
73,008,231
Recompiling does not reflect changes
I am attempting to make a simple change to the bitcoin core codebase locally but my changes are not reflected after recompilation. Below are the steps to reproduce the issue: Clone the bitcoin source code: git clone https://github.com/bitcoin/bitcoin.git cd bitcoin Edit: src/rpc/rawtransaction.cpp and change something...
The reason was that I had to kill and restart bitcoind because that's where the change actually was (not bitcoin-cli, as I previously thought. Duh!)
73,007,919
73,008,573
imgui is not rendering with a D3D9 Hook
ok so basically I am trying to inject a DLL into a game for an external menu for debugging and my hook works completely fine, i can render a normal square fine to the screen but when i try to render imgui, some games DirectX just dies and some others nothing renders at all. The issue makes no sense because I've tried e...
Ok so I solved the issue already, but just incase anyone else needs help I have found a few fixes as to why it would crash/not render. First one being EnumWindow(), if you are using EnumWindows() to get your target processes HWND then that is likely one or your entire issue, For internal cheats, Use GetForegroundWindow...
73,008,323
73,184,958
Assert instead of throw
How can I set the error handling to assert instead of throw? I'd like it to debug break without attaching the debugger. Currently, I'm patching the source, adding __debugbreak() to assertions_impl.h in precondition_fail(). To be a bit more specific. There are a handful of global error handling functions. Their behavio...
The behavior on assertion failure can be controlled, as documented here. If I am reading correctly, you want #include <CGAL/assertions_behaviour.h> int main(){ CGAL::set_error_behaviour(CGAL::ABORT); } or if that's not quite what you need, you can use CGAL::set_error_handler to provide your own handler.
73,008,424
73,008,537
Enable constructor iff two member functions are present in the passed template type
With this code: struct MyStructure { MyStructure(char* d, int size) {} template <typename T> MyStructure(T&& rhs) : MyStructure(rhs.data(), rhs.size()) {} }; How can I only enable the second constructor to be present if the data and size functions are present in whatever object is passed in?
Here is what Sam Varshavchik meant, which should work with C++11: struct MyStructure { MyStructure(char* d, int size) {} template <typename T, decltype(static_cast<char*>(std::declval<T &&>().data())) = nullptr, decltype(static_cast<int>(std::declval<T &&>().size())) = 0 > MyStructure(T&& rhs) : ...
73,008,749
73,008,945
Why does the compiler issue a template recursion error?
I'm currently trying to deduce a std::tuple type from several std::vectors that are passed as parameters. My code works fine using gcc, but the compilation fails with Visual Studio Professional 2019 with the message "fatal error C1202: recursive type or function dependency context too complex". It has been mentioned fo...
MSVC has some conformance issues when running in /permissive mode and "The Microsoft C++ compiler doesn't currently support binding nondependent names when initially parsing a template. This doesn't conform to section 14.6.3 of the C++ 11 ISO specification. This can cause overloads declared after the template (but befo...
73,008,921
73,008,959
Obtain integer from collection of possible types at compile time?
The following code does not compile, because I don't know if what I want to do is possible, but it does show what I would like. I build, at compile time (if possible!), a collection of types and integer values; this is then used at compile time in the assignment operator which looks at the type that has been passed an...
Here's a basic blueprint that, with some cosmetic tweaks, can be slotted into your MyStructure: #include <string> #include <iostream> template<typename T> struct type_map; template<> struct type_map<int> { static constexpr int value=1; }; template<> struct type_map<char> { static constexpr int value=2; }; t...
73,009,104
73,009,131
SFINAE template specialization matching rule
I'm learning about SFINE with class/struct template specialization and I'm a bit confused by the matching rule in a nuanced example. #include <iostream> template <typename T, typename = void> struct Foo{ void foo(T t) { std::cout << "general"; } }; template <typename T> struct Foo<T, typename std:...
Re-focus your eyeballs a few lines higher, to this part: template <typename T, typename = void> struct Foo{ This means that when this template gets invoked here: Foo<int>().foo(3); This ends up invoking the following template: Foo<int, void>. After all, that's what the 2nd template parameter is, by default. The 2nd t...
73,009,176
73,009,321
Warning: null destination pointer [-Wformat-overflow=] with GCC 11.2.1
Here is my code: #include <iostream> #include <cstdio> int main() { char *str = new char[64] ; std::sprintf(str, "msg: %s", "hello world") ; std::cout << str << std::endl ; delete [] str ; return 0 ; } With GCC 11.2.1, using the following command: g++ -O -fsanitize=undefined -Wformat-overflow te...
This seems like a bug/false-positive warning from the g++ compiler. The message is trying to warn you that using a pointer variable as the destination for the sprintf function could fail if that pointer is null (or points to a buffer of insufficient size). It is 'trivial' to suppress this warning: simply add a check th...
73,009,623
73,009,725
Inserting multiples values into text file from user input
I have this project where I need to insert multiples integers into text file by taking user input with certain range of that input in loop void append_text_multiple() { std::string file_name; std::cin >> file_name; std::ofstream getfile; getfile.open(("C:\\users\\USER\\Documents\\located_file\\...
There are several issues in your code: Your for loop does total_line+1 iterations, instead of total_line. The loop should be for(int j=0; j<total_line; j++) (< instead of <=). You close the output file immediatly after writing the first value. Therefore the later writes are not performed. You should close it after all...
73,009,682
73,009,730
Why dynamic_cast from reference causes a segmentation fault?
I have an expr_t base class, from which ident_t is derived. I wrote some to_string overloads to display differently between expr_t and ident_t: #include <iostream> #include <string> struct expr_t { virtual ~expr_t() {} }; struct ident_t : public expr_t { std::string name; ident_t(std::string name) : name(name)...
The problem is that at the point of the call return to_string(*id) the compiler doesn't have a declaration for the second overload std::string to_string(ident_t& v). Thus the same first version will be recursively called eventually resulting in a seg fault. To solve this you can either move the second overload's defin...
73,009,957
73,010,002
Is it possible to have a function-try-block per member initialiser?
During the member initialisation of a class with multiple members, it seems desirable to be able to catch an exception generated by any specific member initialiser, to wrap in additional context for rethrowing, but the syntax of a function-try-block doesn't appear to accomodate that. #include <stdexcept> #include <stri...
Is it possible to have a function-try-block per member initialiser? No, that is not possible. Sidebar: it seems like you're overusing and/or overthinking exceptions. Most people don't write much exception-handling code, because most programs are fine with just terminating if an exception is thrown, in most places. ...
73,010,151
73,010,336
Why it takes me a long time to compile this simple C++ code
When I try to compile C++ code like this, it takes me 71s: #include<bits/stdc++.h> struct S{int v=1;}a[1<<25]; int main(){ return 0; } However, when I change the 1 to 0, it compiles in just 1s: #include<bits/stdc++.h> struct S{int v=0;}a[1<<25]; int main(){ return 0; } I know I can use something like S(){v=1;...
In your original case with struct S{int v=1;}a[1<<25];, a's initialization is a constant expression. Therefore the compiler needs to evaluate the value of the whole array at compile-time and store the result in the executable. (Generally in the .data segment.) The constant evaluation and keeping track of the stored val...
73,010,411
73,011,489
CUDA customized atomicCAS for floating point types (like double)
atomicCAS allows using integral types of various lengths (according to specs word sizes of 16/32/64 bit). It works fine for integral types like int, unsigned long long,... I want to use atomic operations for non integral types of same length. My naive thought is to simply type-cast the data to an integral type of same ...
As @Homer512 pointed out, atomicCAS is implemented for global and shared memory, as it makes no sense in non concurrent scenarios (like thread local variables used in the example above) to use atomic operations (at least I can't think of any). Following vectorized example works instead. const unsigned int idx = (blockI...
73,010,535
73,010,671
How to make plot from file WinAPI
We have txt file with numbers: 60 0 120 4 180 20 60 -28 180 28 30 -28 30 28 30 -28 60 0 I need a plot with first column in horizontal coordinate line and the second column in vertical coordinate line like on this picture. But now I have smth like this std::ifstream omega_file("test.txt"); MoveToEx(hdc, 0, 0, NULL); //...
You will need to draw two lines (horizontal, then vertical) instead of one per one coordinate. Also note that LineTo() sets the current position, so MoveToEx() to the same coordinate is redundant. Try this: std::ifstream omega_file("test.txt"); MoveToEx(hdc, 0, 0, NULL); // start point int currentY = 0; double T_new =...
73,010,742
73,010,823
Hello guys, ask a question about the address of C++
Why are mySwap02 and mySwap03 addresses different? #include<iostream> using namespace std; //1. Passing Directly void mySwap01(int a, int b) { cout << "mySwap01's address a:" << &a << endl; cout << "mySwap01's address b:" << &b << endl; int temp = a; a = b; b = temp; } //2. Passing by Pointer voi...
Let's take a look at what mySwap03 is doing. Note that I've translated some of the Chinese here; I've submitted the edits, but they have yet to be approved, at least for now. (Edit: My edits have been approved.) void mySwap03(int& a, int& b) { cout << "mySwap03's address a:" << &a << endl; cout << "mySwap03's a...
73,010,922
73,011,131
Generate nested for loops using C preprocessor
I want to generate nested for-loops instead of using recursion using the C preprocessor. The depth of this loop structure is bounded. An example nested for-loop with depth 3 is as below: for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < p; k++) { // do_computation() } } }...
having #define MAKE_N_LOOP() would have been great! First generate MAKE_LOOP_# macros overloads for every count of arguments. Then write a MAKE_LOOP macro overloaded on number of arguments that redirects to each overload. #include <stdio.h> #define MAKE_LOOP_2(i, mi) for(int i = 0; i < mi; ++i) #define MAKE_LOOP_4...
73,011,448
73,011,689
Invalid read on a vector with size initialized by a variable using assert()
The simple function I've written catches a segfault on the test asserts that return 0 (false). #include <vector> #include <cassert> using namespace std; // checks whether the elements of a vector are some permutation of range [1..vector.size()] int isPermutation(vector<int> &&A) { int res = 1; int vecSize = A....
There is a bug in if (B[it - 1] != 0 || it > vecSize) If it is larger than the size of the vector you first try to access an invalid element which causes UB. You should switch this to if (it > vecSize || B[it - 1] != 0) so that you are sure that you only evaluate B[...] when the index is valid. (In addition you may w...
73,011,722
73,014,415
Why are port numbers stored as strings?
The question is: Why can't I pass port numbers to DNS resolution functions as 16-bit unsigned ints to prevent std::string to unsigned short conversions? Background: I am looking at the Networking TS and the boost.asio implementation of the function tcp::ip::resolver::resolve. The function takes as input the web address...
Because it is a thin wrapper around the POSIX getaddrinfo(3), which takes a const char* service. Since a string has to be created to pass to getadddrinfo() anyways, there's not actually much benefit to having additional overloads that take uint16_t port numbers. Using resolve(web_address, std::to_string(integer_port_nu...
73,011,795
73,217,895
How to multiply two images with different encoding
I have two textures map, one albedo and another ambient occlusion. The albedo one is srgb encoded .jpg whereas the ambient occlusion is linear encoded .jpg. Now, I want to load these two images (preferably in node.js) and multiply their rgb values evenly(0.5 weight) and output the image in .jpg format with sRGB encodin...
Well I found out a trick with which we can trick sharp to work with linear encodings. So, we know that our file is linear encoded. But since it has no metadata, sharp assumes it to be sRGB encoded. So what can we do? Hmm.. sharp(ifile) .pipelineColourspace('srgb') .toColourspace('srgb') .toBuffer(); We say...
73,011,966
73,012,797
Unable to compile C++ program with Clang-14
I am currently trying to compile a small program I have been working on with Clang and am getting the following error on compilation using scons as the build system: /usr/bin/clang++ -o src/PluGen/main.o -c -std=c++17 -fPIC -I. -O2 -fno-strict-aliasing -fpermissive -fopenmp --param=ssp-buffer-size=4 -Wformat -Wformat-s...
You are using -flto when compiling, but not when linking. clang can't do that. -c -flto compiles to LLVM IR bitcodes which the linker cannot use directly. You should either drop -flto everywhere, or use it everywhere. $ clang++ -flto -c hello.cpp $ file hello.o hello.o: LLVM IR bitcode $ clang++ -o hello hello.o && ech...
73,012,005
73,012,066
Expansion of multiple parameter packs of types and integer values
I previously asked this question, which basically asked how do I change the following "pseudo code" to get the result the comments show: struct MyStructure { std::array<pair<TYPE, int>> map { { int, 1 }, { char, 2 }, { double, 4 }, { std::string, 8 } }; template <typename T> auto operator=(con...
It's not possible to generate specializations, but you don't actually need those. It's not possible to have more than one template parameter pack per class template, so we'll have to work with a single one, with a helper struct that combines both a type and its index into a single type. #include <cstddef> #include <ios...
73,012,092
73,018,927
Getting cable a connected/disconnect notification
On Windows with Qt5.15, I implemented a cable connected/disconnected notifier based on QNetworkInterface. It calls allinterfaces() every second and checks the flags. It works. However now I'm wondering what are the alternatives. Is there a simpler way, perhaps a native Windows thing that I should just listen?
There is not really a signal for this in QNetworkInterface. Polling is the only way to achieve this cross-platform using the isUp method. I would not compromise the cross-platform behaviour for a Windows specific API as that would have an impact on the portability of the application. Polling may not be ideal for you, b...
73,012,226
73,012,257
Trim the last letter of a string
Lets say that I have a text file "myfile.txt" that assigned to a string variable and I want to get rid of the dot and the rest of extension file character .txt #include <stdio.h> #include <string> #incldue <iostream> int main() { std::string F = "myfile.txt"; return 0; } So the output I want to achieve i...
When you're dealing with paths, using std::filesystem is helpful. #include <filesystem> #include <string> #include <iostream> int main() { std::string F = "myfile.txt"; std::filesystem::path p(F); std::cout << p.stem(); // prints "myfile" } or if you want it back as a string: #incl...
73,012,556
73,035,564
Code::Blocks Debugger : how to `step into` functions on line-by-line execution?
When debugging a C++ program on Code::Blocks 20.03, I press SHIFT+F7 to step into the program, then I begin pressing F7 to go to the next line and watch variables changing in "real time". But Code::Blocks 20.03's debugger won't enter any functions beside main, making it pretty useless, or forcing me to not use any func...
Set a breakpoint (red circle) exactly on the line the function main is defined; Instead of pressing F8 (the same as clicking Debug->Start/Continue), which would make the program just run until the last line and exit (only flashing on the screen before disappearing), press Shift+F7 (the same as clicking Debug->Step Int...
73,012,635
73,021,315
Check if given keypair is valid C++
I want to check if the given key pair is valid, I had found solution, but it didn't work because object of the RSA class doesn't have parameter n. #include <openssl/rsa.h> #include <openssl/pem.h> int main() { RSA *pubkey = PEM_read_RSA_PUBKEY(...); RSA *privkey = PEM_read_RSAPrivateKey(...); if (!BN_cmp...
OpenSSL 3.x OpenSSL 3.x provides EVP_PKEY_get_bn_param. It can be used like this (error handling for reading the keys etc. has to be added accordingly of course): #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/core_names.h> ... EVP_PKEY *priv_key= NULL, *pub_key= NULL; ...
73,012,745
73,013,308
How I can keep aggregate initialization while also adding custom constructors?
If I don't define a constructor in a struct, I can initialize it by just picking a certain value like this: struct Foo { int x, y; }; Foo foo = {.y = 1}; But if I add new default constructor then I lose this feature: struct Bar { int x, y; Bar(int value) : x(value), y(value) {} }; Bar bar1 = 1; Bar bar2 ...
Similar to what ellipticaldoor wrote: struct FooBase { int x = 0, y = 0; }; struct Foo : FooBase { Foo(int x_) : FooBase{.x = x_} { } Foo(FooBase &&t) : FooBase{t} {} }; Foo foo = {{.y = 1}}; Foo foo2{1};
73,013,124
73,013,992
How to cast a void pointer to another type of pointer and assign it
What I've tried: Main.h #pragma once union TBufferRec { int ID; }; extern TBufferRec BufferRec; Main.cpp #include "Main.h" void CastPointer(void* PPointer) { static_cast<TBufferRec*>(*BufferRec) = static_cast<TBufferRec*>(PPointer); } Errors: E0349 no operator "*" matches these operands C2679 binary '=':...
Let's do it step by step, solving one problem at a time and building upon previous solituons. Suppose you have two pointers to TBufferRec objects, how to assign one object to the other? Given a pointer, you access the pointed-to object by dereferencing (the unary asterisk operator). void assign0(TBufferRec* lhs, TBuffe...
73,013,185
73,013,265
Opengl GLSL value changes for no reason
I recently decided to make my own voxel game with opengl in C++ (using glfw). I'm looking to add textures to the blocs (I already done the chunk system). To do this, I add for every bloc added to the vertices array and ID for the texture (1 = cobblestone, 2 = dirt, ...) and I take the ID back directly in the shader to ...
"I have the impression that the value of the ID of the bloc changes for no reason between the vertex shader and the fragment shader" Of course, the value of the fragment shader input is interpolated between the outputs of the vertex shader associated with the primitive. If you don't want the input to be interpolated,...
73,013,608
73,013,622
Returning vector array from a function
I am actually trying to solve the K rotate question where we have to rotate the key number of elements to the right and place them on the left. I have checked the whole code using a normal array instead of a vector and it works fine but the function with the vector array never returns anything when i run this. I have c...
The vector subst in the function rotate_array has no elements, so accessing its "elements" (subst[j] and subst[i]) is illegal. You have to allocate elements. For example, you can do that using the constructor: vector<int> subst(n); // specify the number of elements to allocate
73,014,358
73,014,488
How to implement Singleton C++ the right way
I am currently trying to implement a class with the Singleton Pattern in C++. But I get following linking error: projectgen.cpp:(.bss+0x0): multiple definition of `Metadata::metadata'; C:\Users\adria\AppData\Local\Temp\ccdq4ZjN.o:main.cpp:(.bss+0x0): first defined here collect2.exe: error: ld returned 1 exit status Wha...
An #include statement is logically equivalent to taking the included header file and physically inserting it into the .cpp file that's including it. Metadata* Metadata::metadata = nullptr; In the included header file, this defines this particular static class member. Therefore, every .cpp file that includes this heade...
73,014,412
73,014,582
How to understand const Someclass& a in constructor
I'm trying to understand the code below. More specifically, why is b.x in the main function 5? As far as I understand, I have a constructor Someclass(int xx):x(xx){} in the class which sets my attribute x to xx. Therefore, a.x in the main function is 4. But what do the lines Someclass(const Someclass& a){x=a.x;x++;} an...
When you instantiate a with the following line: Someclass a(4); You are calling the "normal" constructor, namely: class Someclass { public: int x; public: Someclass(int xx):x(xx){} // <= This one Someclass(const Someclass& a){x=a.x;x++;} void operator=(const Someclass& a){x=a.x;x--;} }; When you i...
73,015,147
73,016,378
Why r-value reference to pointer to const initialized with pointer to non-const doesn't create an temporary and bind it with it?
If we want to initialize an reference with an different type, we need to make it const (const type*) so that an temporary can be generated implicit and the reference binded to with. Alternativaly, we can use r-value references and achieve the same [1]: Rvalue references can be used to extend the lifetimes of temporary...
The standard has a concept of two types being reference-related. This is fulfilled by two types being similar, which basically means if they are the same type with the same number of pointers but possibly different cv-qualifiers (e.g., int and const int are similar, int* const ** volatile and volatile int** const * are...
73,015,262
73,020,965
Is it possible to install different versions of a library in one place?
The Requirement I want to have multi versions of a library installed in one place(e.g. the default system prefix path) using CMake to be used like: find_package(Package 1.0.0 REQUIRED). Why just don't set some paths? Because I'm an idiot at remembering paths and flags and other related stuff and I think it's the CMak...
You are working in Config Mode of find_package, so the search mode according to the documents is like: <prefix>/(lib/<arch>|lib*|share)/cmake/<name>*/ (U) <prefix>/(lib/<arch>|lib*|share)/<name>*/ (U) <prefix>/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (U) So you need ...
73,016,267
73,016,419
Casting structs with non-aggregate members
I am receiving an segmentation fault (SIGSEGV) when I try to reinterpret_cast a struct that contains an vector. The following code does not make sense on its own, but shows an minimal working (failing) example. // compiler: g++ -std=c++17 struct Table { std::vector<int> ids; }; std::vector<std::byte> storage; //...
I see at least three reasons for undefined behavior in the shown code, that fatally undermines what the shown code is attempting to do. One or some combination of the following reasons is responsible for your observed crash. struct Table { std::vector<int> ids; }; Reason number 1 is that this is not a trivially c...
73,017,117
73,017,238
How to disallow increment operator when operated multiple times on a object?
How do I overload the increment operator so that this code becomes invalid - Point p(2, 3); ++++p; while allowing the following - Point p(2, 3), a(0, 0), b(1, 4); a = ++p + b; Like in C this would be invalid - int a = 2; ++++a;
One way you could do this is to make your operator++() return a const reference. That would prevent subsequent modification of the returned value, as in a 'chained' ++++p;. Here's an outline version that also includes the required binary addition operator, implemented as a non-member function (as is normal): #include <...
73,017,855
73,017,935
add "std::mutex" as a member field into an only-movable class without manually code "move constructor" (std::unique_ptr<> is ugly)
By design, class B is uncopiable but movable. Recently, I enjoy that B has automatically-generated move constructor and move assignment operator. Now, I add std::mutex to class B. The problem is that std::mutex can't be moved. #include <iostream> #include <string> #include <vector> #include <mutex> class C{ public:...
I enjoy that B has automatically-generated move constructor Why don't rename class B and use it as a base class? #include <iostream> #include <string> #include <vector> #include <mutex> class C{ public: C(){} public: C(C&& c2){ } public: C& operator=(C&& c2){ return *this; } //: by design, I don't all...
73,018,270
73,047,050
C++ Google Type-Parameterized and Value-Parameterized Tests combined?
I would like to be able to parameterize my tests for various types through the following code snippet: template <typename T> class MyTestSuite : public testing::TestWithParam<tuple<T, vector<vector<T>>, T, T>> { public: MyTestSuite() { _var = get<0>(GetParam()); // and the rest of the test param...
Decided to use a template base test fixture class with parameterized tests: template <typename T> class MyTestFixture { protected: void SetUp(...) {} T _var; }; class MyTestSuite1 : public MyTestFixture<size_t>, public testing::TestWithParam<tuple<size_t, vector<vector<size_t>>, size_t, size_t>> { public: voi...
73,018,299
73,018,592
How do I convert a regular expression match into a "struct"?
Regular Expression: ([0-9]*)|([0-9]*\.[0-9]*) String: word1 word2 0:12:13.23456 ... example string match: 0,12,13.23456 Requirement: convert to a struct -> struct Duration { unsigned int hours; unsigned int minutes; double seconds; }; Current matcher: Duration duration; std::regex regex("([0-9]*):([0-9]*):...
I recommend using std::regex_search instead of iterators and loops. Then you get a match result which you can index to get the separate matches. Once you have the separate matches, you can call std::stoul or std::stod to convert the matched strings to their numeric variants. Perhaps something like this: #include <iostr...
73,018,590
73,021,254
Program crash when using boost::iter_split?
my main function in vs2022-v143 and boost-v1.79: struct func_info { func_info(const std::wstring& _var, const std::wstring& _name) :var(_var), func_name(_name) { } std::wstring var; std::wstring func_name; std::vector<std::wstring> values; }; void main_function(){ for (...
You have Undefined Behavior elsewhere. The problem is not in the code shown (modulo obvious typos): Live On MSVC as well as GCC with ASAN: #include <boost/algorithm/string.hpp> #include <iomanip> #include <iostream> #include <string> #include <vector> // myfunc.h void get_split(const std::wstring& input, std::vector<s...
73,020,562
73,021,029
Extract all declared function names from header into boost.preprocessor
I have a C header file containing various declarations of functions, enums, structs, etc, and I hope to extract all declared function names into a boost.preprocessor data structure for iteration, using only the C preprocessor. All function declarations have two fixed distinct macros around the return type, something li...
I don't think this is going to work, due to limitations on where parentheses and commas need to occur. What you can do, though, is the opposite. You could make a Boost.PP sequence that contains the signatures in some structured form and use it to generate the declarations as you showed them. In the end, you have the re...
73,020,842
73,021,515
c++ OpenSSL, writing a public key in to a file and reading it from same file does not return correct key
I have generated an 256 bytes RSA keypair and I am now trying to write the public key into a PEM file. I am using this code: // Put the public key inside a pem file ofstream file("temppubkey.pem"); file.close(); FILE * pemFile = fopen("temppubkey.pem", "w"); PEM_write_PUBKEY(pemFile, servTempPubKey)...
BIO_dump_fp dumps raw binary bytes from a structure into the file. Doing this kind of comparison, this way, only works if EVP_PKEY points to a trivial type, with no padding. OpenSSL's documentation makes no guarantees, whatsoever, what EVP_PKEY's underlying object is. In fact, the definition of its contents is complete...