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
74,431,194
74,433,643
Wierd stuff happens when overloading operator<< with a class template
Here's the functionality I am expecting to achieve: darray<int> a; a.push_back(1); a.push_back(2); a.push_back(3); std::cout << a << std::endl; // displays: {1, 2, 3} My implementation: template <typename T> class darray { private: long m_capacity; long m_size; T* m_data; void resize(); public: //...
Friend functions in template classes have to be defined inside the class declaration. This is the only way I have found to have the friend function to correctly accept an instance of the templated class with the expected template. So here I would write: ... friend std::ostream& operator<<(std::ostream& os, darray<T> co...
74,431,880
74,432,050
E0349 no operator "<<" matches these operands
I try to overload operator << and ++ (post and pre). This is part of my code, but I get error "e0349: no operator matches these operands". Could you tell me where I made a mistake? (C++, VS2022) #include <iostream> #include <string> using namespace std; class K { int x, y; public: K(int a, int b) :x(a), y(b) ...
Simply the post-operator++ is written so that it returns a copy of the temporary value which can be used as rvalue but being that the signature of the insertion operator requires a reference of the value, it does not know how to retrieve the data passed as a copy. This is how you should modify the overloading function ...
74,431,937
74,431,998
Getting a "expected a ')' " error in win32 api c++
I have defined ID_BUTTON as 1 and when I try to run the code: CreateWindow(L"Button", L"TEst", style, monitor.right / 2 - 100, 200, 100, 50, m_hWnd, (HMENU) ID_BUTTON, NULL, NULL); I get an error saying "expected a ')' " It works fine if I put NULL instead of "(HMENU) ID_BUTTON", what am I missing? #include "Window.h...
#define ID_BUTTON 1; You defined the ID_BUTTON macro as "1;". Macros work as nothing more than a search/replace function. Therefore, after macro expansion, the relevant line now reads: CreateWindow(L"Button", L"TEst", style, monitor.right / 2 - 100, 200, 100, 50, m_hWnd, (HMENU) 1;, NULL, NULL); The syntax error shou...
74,432,833
74,432,912
C++ const std::array size from constructor
Say I get an int from a lambda function ran at initialization of a class object. Is it possible to use that int to define the size of a std::array? Something like the following code. #include <array> #include <vector> #include <iostream> class Test1 { public: Test1( std::vector<int> vec1 ) : n...
No. The size of the array is part of its type. You cannot let it be determined at runtime. You can have it be determined at compile time, if you do pass a std::array to the constructor. Since C++17 there is CTAD (class template argument deduction) which lets you write: #include <array> template <size_t N> class Test1...
74,432,989
74,433,078
Overloading the arithmetic operators using friend functions
I found an example of how to overload arithmetic operators using friend functions, and the overloaded operator function is defined inside the class with comments stating that: /* This function is not considered a member of the class, even though the definition is inside the class */ this is the example: #include ...
From the C++ 17 Standard (12.2 Class members) 2 A member-declaration does not declare new members of the class if it is (2.1) — a friend declaration (14.3), (2.2) — a static_assert-declaration, (2.3) — a using-declaration (10.3.3), or (2.4) — an empty-declaration. For any other member-declaration, each declared entity...
74,434,270
74,434,522
Ceres solver - Set size of parameter block of CostFunction
in this Ceres example, SizedCostFunction<1,1> is used. I would like to change it to CostFunction since I do not know the size of input parameters during compilation time. I found out that the number of residuals can be easily changed with set_num_residuals(int), however, I cannot find a way to set the number of inputs....
You can call from QuadraticCostFunction these protected CostFunction member fuctions: set_num_residuals(num); *mutable_parameter_block_sizes() = std::vector<int32_t>{ /* size_1, ..., size_num */ }; You don't seem to need to inherit SizedCostFunction. class QuadraticCostFunction : public CostFunction {
74,434,337
74,475,762
how to add a dependecy to a system library in my conanfile .py?
My ConanFile.py for TWSAPI's C++ code from conans import ConanFile, CMake, tools IBKR_VERSION = "10.18.01" class TwsApiConan(ConanFile): name = "twsapi" version = IBKR_VERSION license = "NA" url = "URL_TO_CODE_FORK" description = "Built from a mirror of the actual TWS API files in Github" topi...
I think you're looking for self.cpp_info.system_libs: def package_info(self): self.cpp_info.libs = ["twsapi"] self.cpp_info.system_libs = ["bidgcc000"]
74,435,017
74,440,081
Getting " Cannot open source file "pugixml.hpp" " error
When I try to build solution in visual studio I get an error saying : Cannot open source file "pugixml.hpp" along with some other errors , such as : Cannot open include file: 'cereal/types/list.hpp': No such file or directory. I downloaded the code onto my local machine from a SVN repository and the solution is an int...
Generally speaking, downloading an external library needs to include its library directory and various header file directories. If a dll is used, this document explains how to use the dll. Regarding Cannot open source file "...hpp", you could refer to the method in this issue.
74,435,189
74,463,042
How to create a synthetic keyboard event in wxWidgets to trigger shortcuts set in a wxAcceleratorEntry?
I am using wxWebView in my application. Since this widget consumes all keyboard events internally, I have to create a synthetic keyboard event and process it. This is the code that I am using for creating a synthetic keyboard event: // create a synthetic keyboard event and handle it wxKeyEvent keyEvent(...
I used sendInput function of Win32 to create a synthetic key down event. It is exactly emulating keyboard events which means it triggers the shortcuts in accelerator table. Also be noticed that the keyboard event goes to the focused widget. INPUT inputs[ 2 ] = {}; ZeroMemory( inputs, sizeof( inputs ) ); aut...
74,435,920
74,479,298
Acyclic undirected graph allocation problem
We have an allocation problem: each node is a fuel source, and every edge contains a number of evenly spaced out lamps (think of them as being 1 m apart from each other). Each fuel source can power lamps that are on the immediate edges around it (it cannot fuel lamps through other nodes). A fuel source also has a radiu...
Algorithm pseudocode: WHILE lamps remain unfueled LOOP over sources IF source has exactly one edge with unfueled lamps SET fuel source to source at other end of unfueled edge INCREMENT radius of fuel source with unfueled edge lamp count LOOP over edges on fuel source IF edge fueled lamp count from fuel sourve < fu...
74,436,273
74,438,729
AVX2 _mm256_cmp_pd to return number values
My goal is to vectorize comparisons to use them as a masks in the future. The problem is that _mm256_cmp_pd returns NaN instead of 1.0. What is the correct way to do comparisons in AVX2? AVX2 code: __m256d _numberToCompare = _mm256_set1_pd(1.0); __m256d _compareConditions = _mm256_set_pd(0.0, 1.0, 2.0, 3.0); __m256d ...
Ad 1: The result is a bitmask (in binary 0xffff'ffff'ffff'ffff for true or 0 for false) which can be used with bitwise operators. Ad 2: You can compute _result = _mm256_and_pd(_result, _mm256_set1_pd(1.0)) if you really want 1 and 0 (but usually, using the bitmask directly is more efficient). Also be aware that _mm256_...
74,436,602
74,436,751
Using std string accessor with ostream operator <<
If I create a class: // First Example #include <iostream> #include <string> class my_class { std::string str; public: my_class(const char* s = "") : str(s) {} operator const char* () const { return str.data(); } // accessor }; my_class mc1{"abc"}; std::cout << mc1; // Calls the char* accessor and successfully ...
This happens because of how the functions are defined. For the const char* case, the operator << that cout has available for that is declared as: template< class CharT, class Traits > basic_ostream<CharT, Traits>& operator<<( basic_ostream<CharT, Traits>& os, const char* s ); So, when the compiler analyzes std::co...
74,436,806
74,438,164
What precisely is an expression?
Consider whether x in the declaration int x; is an expression. I used to think that it's certainly not, but the grammar calls the variable name an id-expression here. One could then argue that only expression is an expression, not ??-expression. But then in 1 + 2, neither 1 nor 2 match, because those are additive-expre...
After looking at the links provided by @LanguageLawyer (1, 2), I'm convinced the consensus is that id-expression is a misnomer, and not always an expression (e.g. it's not an expression in a declaration). Then, a source substring is an expression if at least one of its parents in the parse tree is called: expression, ...
74,436,888
74,436,961
Uniqueness of objects in shared pointers
Let's consider code below: class A { string a; public A(string a) : a(a) { } }; class B : public A { public B(string a) : A(a) { } }; int main() { std::shared_ptr<A> x1 = std::make_shared<B>("x"); std::shared_ptr<A> x2 = std::make_shared<B>("x"); A* atom1 = x1.get(); A* atom2 = x2.get()...
A* atom1X = std::make_shared<B>("x").get(); // (1) A* atom2X = std::make_shared<B>("x").get(); // (2) In these definitions, std::make_share<B>("x") creates a temporary std::shared_ptr that ceases to exist at the end of the full expression (essentially at the next ;). That means that the object each of these pointers ...
74,437,204
74,437,260
Is this indirect const access an UB?
When I was checking some code today, I noticed an old method for implementing std::enable_shared_from_this by keeping a std::weak_ptr to self in the constructor. Somthing like this: struct X { static auto create() { auto ret = std::shared_ptr<X>(new X); ret->m_weak = ret; return ret; } ...
The object that is modified is not const. There is no undefined behavior. Add a method like this: #include <memory> #include <iostream> struct X { static auto create() { auto ret = std::shared_ptr<X>(new X); ret->m_weak = ret; return ret; } void show() const { std::cout << "const \...
74,437,249
74,437,761
Can I create a second vector which contains the identical objects as the first vector?
I am trying to convert a performance critical part of a Java code to a C++ code. In Java I work with lists containing a small sample of the original list. When I add objects of the first list to the second list actually only a reference to the object is stored, so I do not copy the object. This is what I would like to ...
The learning curve for C++ is not the best. I don't think it's a good idea to just jump into it and try to write efficient code without any experience. Anyway, here it is, I hope it helps: #include <string> #include <vector> #include <memory> #include <iostream> class Data { public: Data(int id) : id_{id}...
74,437,901
74,438,830
g++ std=c++11 : is anything wrong in allocating/deallocating a 2d array this way
I'm using g++ -std=c++11 and this compact approach to allocate/deallocate 2d arrays : int(*MyArray)[Ydim]=new int[Xdim][Ydim]; delete[] MyArray; Everything seems to be working fine (compile time and run time). I know there are many ways to do the same but this is compact and seems to be doing the job. Is anything wron...
Assuming you want to stick to your current instantiation, I don't think you will receive any memory leak problems. If your internal nested array was a pointer as well you would need to de-allocate before de-allocating the external one. Alternatives to avoid Dynamic Allocation: To avoid the "new" and "delete" operators,...
74,438,015
74,439,229
Error while using EVP_MD_CTX_cleanup(ctx ) in C++ using openssl 1.1.0
I am trying to run/compile old code that was made in 2018 using an old OpenSSL version. I faced so many errors, but I solved them all. Now I'm just stucking with last error on this line: EVP_MD_CTX_cleanup(ctx) The error is here: error: ‘EVP_MD_CTX_cleanup’ was not declared in this scope; did you mean ‘EVP_MD_CTX_cre...
OpenSSL 1.1.0 is not that old, just a few years. Are you sure that is the correct version you are supposed to be using? More likely, you should be using 1.0.2 instead, as EVP_MD_CTX_cleanup() doesn't exist in 1.1.0. One of the major changes in 1.1.0 was changing the majority of OpenSSL's structs into opaque pointers i...
74,439,230
74,443,325
C++ how to make it so a double variable can only have numbers entered in using cin
void addNumbers(vector<double> &vec) { double add_num {}; cout << "Enter an integer to add: "; cin >> add_num; vec.push_back(add_num); cout << add_num << " added" << endl; } The vector is empty, and I only want people to be able to add numbers into it, and whenever they try anything else it says "I...
You need to check the return code of your extraction command cin >> add_num. And in general, you need to check the state of a stream after any IO operation. So, what could happen? If you enter any invalid data, like for example "abc", then cin >> add_num will of course not work, and the state of the stream (cin) will s...
74,439,722
74,439,730
What would be the long form of the following statment?
I was looking at some code which came with the following short-hand statement score = ((initialPlayer == player) ? CAPTURE_SCORE : -CAPTURE_SCORE) + recursive_solver(lastMap, initialPlayer, findOpponent(player), 1 + rounds); I think that I understand the first portion of the code, if(initialPlayer == player){ scor...
if(initialPlayer == player) score = CAPTURE_SCORE + recursive_solver(lastMap, initialPlayer, findOpponent(player), 1 + rounds); else score = -CAPTURE_SCORE + recursive_solver(lastMap, initialPlayer, findOpponent(player), 1 + rounds); Explanation: A = (C ? B : D) + E; If C is true: A = (B) + E; If C is false: A ...
74,439,812
74,439,919
Unary Predicate results in error "called object type 'bool' is not a function or function pointer" in remove_if
I'm trying to use remove_if from the STL, and the predicate of remove_if requires a Unary Predicate. I hope to get the result of removing elements from the vector that equals "whereValue." So I'm trying to call my predicate in: // Create EqualTemplate object EqualTemplate equalTemplate = EqualTemplate(whereValueEntry,...
The error is quite clear. You are passing a bool as UnaryPredicate instead of a function - this is because you are calling the function and passing its return type, a boolean, to UnaryPredicate. Just pass equalTemplate, not equalTemplate(tables[tableName].table[tables[tableName].colNames[whereColName]]) - std::remove_i...
74,439,909
74,439,948
Creating variable without defining the variables type class yet
class Component { public: Entity *parent = nullptr; }; class Entity { public: Component components[25]; }; I am trying to create an entity component system, and above I have an issue. In the component class I am creating a pointer variable with the datatype being the "Entity" class, even thoug...
You need to declare Entity as a class, so the compiler knows what type this is. class Entity; Usually you would put these sorts of forward declarations in a generic header file, then define each class completely in its own Classname.cpp file.
74,440,760
74,440,933
How can i make my program do a specific calculation in a sequential IF statement
#include <stdio.h> int main() { char ticketType; int totalBill, studAmount, ticketType_R= 6500, ticketType_G= 7500; printf("\nEnter your ticket type: "); scanf("%c", &ticketType); printf("\nEnter amount of students: "); scanf("%d", &studAmount); if(ticketType==ticketType_R) { totalBil...
In your case, I believe you want to calculate value according to ticket type and the number of students. That's how we can do it: #include <stdio.h> int main() { char ticketType; int totalBill, studAmount, ticketType_R= 6500, ticketType_G= 7500; printf("Enter the ticket type (R/G): "); // Input ticket type ...
74,440,855
74,449,373
When to use x3::lit in Boost spirit
I am beginning with Boost Spirit x3 parsing library - and I'm very excited about it. One thing unclear to me is when and why one should use x3::lit. From what I understood, it's because we can not expect an expression like ']' >> double_ to be interpreted as intended within C++ syntactic rules. But my interpretation se...
You can not generally expect '[' >> x to see the X3 expression overload. Overload resolution depends on the types of both operands. Since '[' is char, there cannot be user-defined overloads. So in this case, only if x is already an x3 parser expression the x3 overload of operator>> will be found. In generic code, if bo...
74,440,957
74,441,301
Crashing before calling unlink() on file created by mkstemp()
I am doing something like the following auto tempFd = mkstemp(filePathTemplate); // 1) write to temp file, on error, unlink() // 2) sync temp file, on error, unlink() // 3) close temp file, on error, unlink() // 4) rename to implement an atomic write, on error unlink() Here, what happens if the program crashes anywhe...
The file will either be deleted or not. If it's not deleted it will persist till you either delete, or you reboot the system if you happen to write the file a tmpfs (memory) backed directory. You write a log (fsync; local or remote) it that you are about to create a temporary file. When you start your program, you pr...
74,441,348
74,441,458
why does my code not read or follow the if statements?
Why does my code not read or follow the if statements? #include<iostream> using namespace std; int main (){ int sum = 0; int integer; while ((integer != -1) && (sum < 2000)){ int integer; cout<<"Enter an integer: "; cin>>integer; if (integer == -1){ ...
you want only 1 branch to be entered, so you need a if else if chain. if (sum >= 2000) { std::cout << "Congratulations!" << "Your total sales are: " << sum << std::endl; break; } else if (sum > 1499) { std::cout << "You're almost there!" << std::endl; } else if (sum > 999) { std::cout << "You're halfway...
74,441,894
74,445,181
Compute shader can't get result image
I am using the compute shader to get a column of colors to match the conditions and I want to get the results for further processing. I want to get the output data in image1D imgOutput, but get_img can't get anything, did I do something wrong? the texture in the first block has been generated before. Shader spriteRowPr...
One issue might be that if you want to access images after the compute shader, the argument for glMemoryBarrier should be GL_SHADER_IMAGE_ACCESS_BARRIER_BIT and not GL_SHADER_STORAGE_BARRIER_BIT. So spriteRowProgram.setInt("input_width", TEX_WIDTH); spriteRowProgram.setInt("input_height", TEX_HEIGHT); glDispatchCompute...
74,442,281
74,488,642
Deadlocked program using pthread condition variables, critical sections [C++]
What I'm trying to do is have each thread copy information from a struct in main using a critical section before main changes the struct for other threads. #include <iostream> #include <pthread.h> using namespace std; struct foo { public: int var; int *turn; int index; pthread_mutex_t *bsem; pthread_co...
I see race condition on mainStruct.index. Main thread modifies it without lock and multiple threads are accessing it under a lock. So if first thread starts fast it will interact with your loop spawning threads. Looks like you plan was to have multiple instances of Foo, but you have one. So imagine scenario: Main thr...
74,442,721
74,442,864
Pass a lambda which captures a unique_ptr to another function
I want to pass a mutable lambda which captures a unique_ptr to another function as shown in the code snippet below. #include <functional> #include <memory> #include <iostream> struct Adder { Adder(int val1, std::unique_ptr<int> val2) : val1_(val1), val2_(std::move(val2)) { } int Add() { return val...
You can template CallAdder on a function parameter. [Demo] #include <functional> #include <iostream> #include <memory> struct Adder { Adder(int val1, std::unique_ptr<int> val2) : val1_(val1), val2_(std::move(val2)) {} int Add() { return val1_ + *val2_; } int val1_; std::unique_ptr<int> val2_;...
74,443,349
74,443,441
how to print elements of a vector of type Person class in c++
I created a class called person with two members name and age then I created two objects of that class p1 and p2 and then I added them to a vector. I tried then to print them but could not. this my code: class Person{ public: string name; int age; }; int main(){ Person p; vector <Person> vector;...
You can implement operator<< or just write something like this: cout << vector[i].name << ": " << vector[i].age << endl; cout doesn't know how to print this object by default.
74,443,625
74,451,693
Split text with array of delimiters
I want a function that split text by array of delimiters. I have a demo that works perfectly, but it is really really slow. Here is a example of parameters. text: "pop-pap-bab bob" vector of delimiters: "-"," " the result: "pop", "-", "pap", "-", "bab", "bob" So the function loops throw the string and tries to find de...
It might be a good idea to use boost expressive. It is a powerful tool for various string operations more than struggling with string::find_xx and self for-loop or regex. Concise explanation: +as_xpr(" ") is repeated match more than 1 like regex and then prefix "-" means shortest match. If you define regex parser as sr...
74,443,994
74,444,587
How to pass a pointer argument to std::format?
In the following code, when the first argument is an int and another a pointer casted to void*, the code compiles: AYAPI_API int AYBlitBuffer(int a1, int a2, int* a3, int* a4) { Log(std::format("@{}: a1 = {}, a2 = {}, a3 = {}, a4 = {}", __FUNCTION__, a1, a2, static_cast<void*>(a3), static_cast<void*>(a4))); ret...
The error you are seeing has nothing to do with the presence or absence of any int arguments amongst the parameters to the call to std::format. (Try changing the format string in your first snippet so that it ends with a4 = {:#010x} in place of a4 = {} and you will see the same error message, there.) Rather, the error ...
74,444,442
74,444,696
How to convert vector<vector<int>>to int**?
vectoris easy to obtain int* through vector::data(), so how to convert vector<vector>to int**? int main(int argc, char *argv[]) { std::vector<std::vector<int>> temp {{1,2,3},{4,5,6}}; int **t; t = reinterpret_cast<int **>(std::data(temp)); for (int i = 0; i < 2; ++i) { for (int j = 0; j ...
There is a simple "trick" to create the pointer that you need, as a temporary workaround while the code is being refactored to handle standard containers (which is what I really recommend that you should do). The vectors data function returns a pointer to its first element. So if we have a std::vector<int> object, then...
74,444,665
74,445,757
How to initialize a static array within a c-style struct by an existing static array?
I'm currently doing c++ with OpenCL, where a c-style struct is required to carry configuration information from the c++ host to the OpenCL kernel. Given that dynamically allocated arrays are not guaranteed to be supported by every OpenCL implementation, I must ensure every array accessible by the kernel code be static-...
If you want to copy the entire string, you have to use memcopy into conf.id (or strncpy if it is guaranteed to be a zero-terminated string). Unfortunately this means that the id in conf_t cannot be const anymore: #include <iostream> #include <cstring> #include <string> #define ID_SIZE 16 struct conf_t { const unsi...
74,445,620
74,446,144
Implementing move semantics in the legacy C++ class
I am working on a legacy application with a class named Point3D as shown below... template <class T> class Point3D final { T values[3]; public: Point3D(); Point3D(T x, T y, T z); explicit Point3D(const T value); Point3D(const Point3D& point); explicit Point3D(const Point2D<T>& point); ~Point...
Also, the legacy code passes this vector as a value and returns by value. This is making the application very slow. Your suggested modifications will make this worse in general. The cost of copying or moving your original Point3D is very small if T is a simple type like double. It will just copy three double values. ...
74,446,006
74,446,514
How load two QML merging two project
I'm merging two QML\Qt project into new one and I've a problem with *.qml files. In original projects I've a main.qml with timer, proprieties,... and a loader for bring-up the custon *.qml, to summarize: 2 folder (QML_10 and QML_15), 2 main.qml and several other qml files. I would have a sinle project which is able to ...
With setUrl you replace the complete content of QUrl, leading to a URL without scheme, upon which the default file: scheme is assumed. You should either put qrc: in front, or use setPath. Alternatively you could use setScheme("qrc") afterwards.
74,446,181
74,446,275
Regular expression missing the pattern match
I am trying to match a pattern with my input using regular expression . I am trying to match the following string 00010_mesh_fbx_low_pileOfStoneAtWonwonsaTemple.fbx using the following regular expression std::regex("^[0-9]+_mesh_fbx_low_[a-z][A-Z][0-9].(?:fbx|glb|obj)")) But I do not get a match for the input string
[a-z][A-Z][0-9]. matches a sequence of four chars: a lowercase ASCII letter, then an uppercase ASCII letter, then an ASCII digit and then any char other than line break chars. You can fix your regex by using std::regex(R"(^[0-9]+_mesh_fbx_low_[a-zA-Z0-9]+\.(?:fbx|glb|obj))") std::regex(R"(^[0-9]+_mesh_fbx_low_\w+\.(?:f...
74,446,197
74,446,291
C++ How does if (system("CLS") {system("clear)} work
C++ How does this work if (system("cls")) { system("clear") } I was trying to find a cross-platform way to clear console in c++ and I remembered some code with this syntax so I tried it and it worked but I want to know how it works like does it return an error or something if the command was not found sorry if it ...
cls and clear are terminal/command prompt commands used to clear the screen. system is a c++ command used to interact with the cmd/terminal directly. It returns 0 if a command was completed successfully. In this case, if cls fails to clear the screen (in other words, the system command returns something other than 0) t...
74,446,298
74,446,467
need to parse json file and put all subfields into 2-level array
JSON: { "media": { "Test1": "https://storage.tst", "Test2": "https://storage.tst" } } I need to put those keys (Test) and it's value in to 2-level array in cycles Like @sehe offered, I used next code: #include <boost/json.hpp> //#include <boost/json/src.hpp> // for header-only //(in the another...
You should use the other lines of code that @sehe provided as well: auto sample = boost::json::parse(R"( { "media": { "Test1": "https://storage.tst", "Test2": "https://storage.tst" } })"); They conveniently included a live demo: Live On Coliru #include <boost/json/src.hpp> // for header-only #...
74,446,359
74,452,180
Creating Win32 controls in a separate class
I have a Window class and a MainMenu class. In the Window class, I create the window itself, and in the MainMenu class I create the controls for the Window (like in C# with form and user-control). Do I need to define, let's say #define EXIT_BUTTON 1, in Window.cpp and MainMenu.cpp for button events to work, or is there...
You should create app_common.h header file and write define to it. app_common.h #pragma once #define EXIT_BUTTON 1 and update your Window.cpp #include "app_common.h" #include "Window.h" .... and then update your MainMenu.cpp #include "app_common.h" #include "MainMenu.h" .....
74,446,648
74,446,949
Function pointers, conversions and comparisons
From what I get, casting function pointers to different types is allowed by the C++ standard (as long as one never invokes them): int my_func(int v) { return v; } int main() { using from_type = int(int); using to_type = void(void); from_type *from = &my_func; to_type *to = reinterpret_cast<to_type *>(...
From [expr.reinterpret.cast].6 (emphasis mine): A function pointer can be explicitly converted to a function pointer of a different type. [...] Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original poi...
74,447,077
74,447,297
Sort a list of objects by property in C++ using the standard list
I am currently trying to sort a list of objects in this case students, based on their grades, student number, name, etc. listOfStudents.sort([](const Students& student1, const Students& student2) { if (student1.getStudentNumber() == student2.getStudentNumber()) return student1 < ...
int getStudentNumber() { return this->studentNumber; } should be int getStudentNumber() const { return this->studentNumber; } and the same for all the other getters in your code.
74,448,142
74,448,328
Lambda to function using generalized capture impossible?
A lambda can be easily converted to std::function though this seems to be impossible when the lambda uses generalized capture with a unique_ptr. Likely an underlying std::move is missing. Is there a workaround for this or is this a known issue? #include <iostream> #include <memory> #include <functional> using namespac...
Is there a workaround for this or is this a known issue? std::function requires that the underlying callable must be copyable, since the lambda object in your example is move-only, this is ill-formed. It's worth noting that C++23 introduced move_only_function, which does exactly what you need std::move_only_function<...
74,448,716
74,449,294
How to select a huge string variable in VS Code?
So I have this huge line-by-line std::string variable which is about 58 thousand lines. How could I select my entire variable? By clicking and dragging I think it takes about 5 minutes :) This is how I stored my string: std::string str = "504b0304140000000800b3ab584fd82c4d1ec01b00002a45000007000000" "...
I was able to select my huge variable by clicking at the beginning of my variable and Shift+click at the end of it. (@Ranoiaetep idea)
74,449,213
74,451,251
How to get all global variable addresses and size at runtime through llvm or clang
I'm analyzing c/c++ projects for memory errors tracking (out-of-bounds read/write). I would like to create at runtime a list of all global variables addresses , i.e. their boundaries. Is there any workaround with LLVM (e.g. some llvm module pass) I can came up with, such that at runtime I'm able to locate all global va...
The LLVM pass AddressSanitizer already detects out of bounds memory accesses, including globals and also stack and heap. You can pass -fsanitizer=address to clang to use it. It's even been ported to GCC under the same flag. You can combine it with UBSan, the undefined behaviour sanitizer, as -fsanitize=address,undefine...
74,449,386
74,449,606
Can I use C++20 concepts for partial template specialization?
I was given an assignment on my computer science class to implement a String<T> class in C++ which would have print method throw an exception, unless T = char. So I defined a method for template<typename T> class String this way: void print(std::basic_ostream<T> stream) { throw StringTypeError("Can't print with the...
is there any concept-like alternatives? There is an appropriate tool for the job, a particularly nice new feature with concepts and its related requires-clauses, one which is not possible with pre-C++20 SFINAE, namely that non-template member functions of class templates can be declared with requires-clauses. This me...
74,450,230
74,547,692
Context menu does not consistently work on arch linux?
I am using arch linux and a basic cpp xlib custom window manager. However, every time I right click to open the context menu it just flickers and disappears. I cannot use it at all. I also cannot use top drop down menus (file, edit, about, ect.) on any application. Is there anything in Xlib which I have to look out for...
It is necessary to make sure the client window has input. I had the input set to whatever was clicked (frame, title bar, or client) because it worked fine as far as normal input is concerned. However, the context menus will only work if you make sure the input is set to the client window directly.
74,450,307
74,450,695
Is it necessary to have a co_return statement on each execution path of a coroutine that returns void
I wonder whether the below code is valid C++ code or if not using co_return results in undefined behavior. IAsyncAction MyClass::MyCoroutine() { co_await someOtherClassInstance.SomeCoroutine(); } I.e. is it necessary to adjust the code as follows? IAsyncAction MyClass::MyCoroutine() { co_await someOtherClassInstan...
Omitting the co_return; statement is well defined here. According to [stmt.return.coroutine] this is allowed as long as p.return_void() is a valid expression (where p is the promise type). C++/WinRT implements return_void() for IAsyncAction and IAsyncActionWithProgress (or rather the internal await adapter structs for ...
74,450,650
74,450,918
What's going on when we expand std::vector<>?
What happens when we do push_back with size() == capacity()? I've heard a lot of opinions regarding this question. Most popular is: when the vector's size reaches its capacity, it allocates a new region of memory, copies the vector to the newly allocated memory, and inserts new value to the vector's end. But, why do we...
You understand virtual memory mechanism correctly, basically you can create any amount of continuous page-aligned arrays in the proces' virtual memory space and they would be backed by non-contiguous physical memory. But that is irrelevant to std::vector because std::allocator does not provide any API to take advantage...
74,451,129
74,452,239
How do I perform a narrowing conversion from double to float safely?
I am getting some -Wnarrowing conversion errors when doubles are narrowed to floats. How can I do this in a well defined way? Preferably with an option in a template I can toggle to switch behavior from throwing exceptions, to clamping to the nearest value, or to simple truncation. I was looking at the gsl::narrow c...
As long as your floating-point types can store infinities (which is extremely likely), there is no possible undefined behavior. You can test std::numeric_limits<float>::has_infinity if you really want to be sure. Use static_cast to silence the warning, and if you want to check for an overflow, you can do something like...
74,451,237
74,451,394
Implicit conversion in concepts
Consider the following concept, which relies on the operator bool() conversion member function of std::is_lvalue_reference<T> and std::is_const<T>. #include <type_traits> template <typename T> concept is_non_const_lvalue_reference = std::is_lvalue_reference<T>{} && // Malformed for GCC 12.2 and MSVC 19.33 !st...
The rule is, from [temp.constr.atomic]/3: To determine if an atomic constraint is satisfied, the parameter mapping and template arguments are first substituted into its expression. If substitution results in an invalid type or expression, the constraint is not satisfied. Otherwise, the lvalue-to-rvalue conversion is p...
74,451,764
74,452,066
Compile-time concatenation of std::initializer_list's
I would like to write some code like the following: using int_list_t = std::initializer_list<int>; struct ThreeDimensionalBox { static constexpr int_list_t kDims = {1, 2, 3}; }; struct FourDimensionalBox { static constexpr int_list_t kDims = {4, 5, 6, 7}; }; template<typename Box1, typename Box2> struct Combined...
std::initializer_list can be initialized only as empty, with a list of brace-enclosed elements, or by copy. However even with a copy construction, the lifetime of the actual array that std::initializer_list references is determined by the lifetime of the original std::initializer_list object that was initialized by a b...
74,451,998
74,452,091
Why type deduction fails for a class member?
Let's assume that we have this small code: template<typename T> struct Test { Test(T t) : m_t(t) {} T m_t; }; int main() { Test t = 1; } This code easily compiles with [T=int] for Test class. Now if I write a code like this: template<typename T> struct Test { Test(T t) : m_t(t) {} T m_t; }; struc...
There is a difference between your two snippets - first Test t = 1 declares, defines, and initializes a new variable while the second only declares a member variable and specifies how it might be initialized. The default member initializer is relevant only in the context of a constructor without t in its member initial...
74,452,464
74,460,122
CMake Error at CMakeLists.txt:14 (target_link_libraries)
I try to add GTest project to my solution. I have a project structure: my project structure I created Cryptograph and CryptographTests directories, after that created binTests and lib into CryptographTests. I have a few CMakeLists.txt files: Cryptograph/CMakeLists.txt: cmake_minimum_required(VERSION 3.17) project(Cry...
Your intuition that your test executable needs access to your Cryptograph code somehow in order to test it is correct. However, linking an executable to another executable is not possible. You'll want to make Cryptograph a library instead so that it compiles once and your executables (cryptograph_samples and runCommonT...
74,453,091
74,453,203
C++ removing file with filesystem library doesn't work
I have a russian Roulette script written with C++. If two randomly generated numbers are the same, the script deletes a specified file. People suggested to me that I should use C++17 for using the <filesystem> library in order to run file-related operations correctly. The removing operation runs if the conditions are m...
Your file path is wrong. I just got your code to work on my system by changing the path from E:\Test\delete.txt to /mnt/e/Test/delete.txt. Under WSL, all Windows drives (C:, E:, etc.) are mounted under the /mnt directory, in subdirectories that match the drive letter (/mnt/c/, /mnt/e/, etc). In order to convert your Wi...
74,453,163
74,453,698
How to SecureZeroMemory on a string_view?
With this code: std::string_view test = "kYp3s6v9y$B&E)H@"; SecureZeroMemory((void*)test.data(), test.length()); I get an exception: Exception thrown: write access violation. **vptr** was 0x7FF755084358. With std::string i get no exception: std::string test = "kYp3s6v9y$B&E)H@"; SecureZeroMemory((void*)test.data(), t...
std::string_view is meant to be a read-only view into a string or memory buffer. In your particular example, the string_view is pointing at a read-only string literal, so no amount of casting will make it writable. But, if you do the following instead, then you can modify what a string_view points at, as long as it i...
74,453,623
74,453,648
memcpy not behaving as expected
I have a char array with a fixed length of 2 and I want to read a 2 byte subsection of data from a buffer of size 1024 starting from index '0'. char signature[2]; char arr[1024]; // this is populated with data memcpy(&signature, &arr[0], sizeof this->signature); If I manually look at the first two characters in arr wi...
The memcpy works but your code for displaying the result is incorrect. Passing a char array to std::cout only works if the array contains a null-terminated string. To display a char array that does not contain a null terminated string you could do something like: for (char ch : signature) std::cout << ch; std::cout...
74,453,689
74,453,742
Class that automatically keeps track of the number of its instances in existence (C++)
I am tasked to have a class C which automatically keeps track of the number of its instances that exists, and to have a function that returns this number. Here is what I have: class C{ public: static int num; C(){++num;} ~C(){--num;} int get_number_objs(){return num;} }; int C::num = 0...
Does this do the trick? Almost. You also need to increment num inside of the class's copy constructor, as well as the move constructor in C++11 and later. Also, there is no point in having get_number_objs() if num is public, but since that does expose num to tampering from outside, num should be private instead. An...
74,453,958
74,454,045
Why do we need to make a local copy of smart_ptr first before passing it to other functions?
CppCon 2015: Herb Sutter "Writing Good C++14... By Default" Slide 50 Live on Coliru I have seen the following guideline through above talk. However, I have hard time to understand the critical issues both solutions try to solve in the first place. All comments on the right side of the code are copied from original talk...
f could be written like this: void f(int* p) { gsp = nullptr; *p = 5; } Since gsp is the only shared_ptr that owns the int, if it is cleared, then the pointer given to p is destroyed. Basically, it is reasonable for functions which are given non-owning pointers (or references) to expect that the objects being poin...
74,454,057
74,454,058
How to do mask / conditional / branchless arithmetic operations in AVX2
I understand how to do general arithmetic operations in AVX2. However, there are conditional operations in scalar code I would like to translate to AVX2. How shall I do it? For example, I would like to vectorize double arr[4] = {1.0,2.0,3.0,4.0}; double condition = 3.0; for (int i = 0; i < 4; i++) { if (arr[i] < co...
Use AVX2 conditional operations. Calculate both possible outputs on whole vectors. After that save those particular results that satisfy your conditions (mask). For your case: double arr[4] = { 1.0,2.0,3.0,4.0 }; double condition = 3.0; __m256d vArr = _mm256_loadu_pd(&arr[0]); __m256d vMultiplier1 = _mm256_set1_pd(1.75...
74,454,064
74,454,105
Variable types from inherited classes
If I have a class that inherits from a base class, can I use that base class as a variable type in c++? class Component { // Code here }; class TransformComponent : public Component { // Code here }; class Entity { // Code here Component *getComponent(Component *searchComponent) { // Code Here...
Absolutely! It's one of the beauties of OOP. Your instanced class of type TransformComponent is both an instance of Component as well as TransformComponent. If you had some function that returned a type of Component, this could return any class derived from Component as a Component! If you later wanted to refer to it a...
74,454,998
74,455,429
Segmentation fault while trying to add an item at the end of a linked list
When I try to add an item at the end of a linked list it says segmentation fault (core dumped) Here is the code LinkedList :: LinkedList() { head = NULL; } void LinkedList :: InsertItem(int data) { Node *new_node; new_node = new Node; new_node -> data = data; new_node -> next = NULL; new_node...
In the AddLast method, your iteration stops when curr == NULL. So when you attempt curr -> next = new_node; you get a segfault, since curr is null here. To fix this, change your iteration to while (curr->next != NULL) That will ensure that the iteration stops at the last node, just like you need it to.
74,455,206
74,455,423
EPP Server SSL_Read hang after greeting
I have strange problems in ssl_read/ssl_write function with EPP server After connected I read greeting message successfully. bytes = SSL_read(ssl, buf, sizeof(buf)); // get reply & decrypt buf[bytes] = 0; ball+= bytes; cc = getInt(buf); printf("header: %x\n",cc); printf("Received: \"%s\"\n",bu...
is it important? Yes, as outlined in RFC 5734 "Extensible Provisioning Protocol (EPP) Transport over TCP", the whole security of an EPP exchange is bound to 3 properties: access list based on IP address TLS communication and verification of certificates (mutually, which is why you - as registrar aka client in EPP co...
74,455,397
74,455,491
Why doesn't this class forward declaration compile in C++?
I'm sure that this has been asked, but I cannot find the question or answer, so here is the minimal code I tried to compile. // goof4.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> class A; class B { public: A func() { return A{}; } }; class A { }...
Because you have the function body using the (at that point) undefined type A in the class B itself and in a function body the type must already be defined. just do A funct(); in the class B itself and put the function body and after defining A, A B::funct() { return A{}; } https://ide.geeksforgeeks.org/2db37ea7-a62c-4...
74,455,518
74,455,594
Return type of function-template not const T&?
In the example below the type of the instantiation f<int&>(a) is reported to be int&. template<typename T> const T& f(const T& x) { return x; } int main() { int a{0}; decltype(f<int&>(a))::_; } But why is the type not const int& ?. Edit: The question is also why f<int&>(0) gives x as int& and not as const...
References themselves cannot be const-qualified (only the type they reference can), so const is ignored in const T if T is a reference type. References-to-references also don't exist. The reference collapsing rules say that trying to form a lvalue references to lvalue reference to type U will form a lvalue reference to...
74,455,536
74,460,538
What is the motivation of a separate config.hpp in boost spirit X3 program structure?
The title itself should be quite clear, but for more context, I was going through the tutorial about x3 program structure in order to re-structure my own baby-parsing-project before adding a recursive AST, and it is not clear to me what level of complexity management I can achieve using the proposed layers. Particularl...
Again, you're asking the big, core questions! You don't need a config.hpp. However, if you spread definition of rules across translation units, you will need to decide on the concrete template instantiations you need to be part of your object files. The two variable parameters here are iterator type context type The ...
74,455,595
74,457,146
regex_token_iterator<> sometimes misses matched substrings
I used regex_token_iterator<> to get all matched substrings in a line, as suggested in this question. But the code sometimes misses 2nd matched substrings in lines, and the lines where this miss happens changes at different runs. Is this a bug of regex_token_iterator<>, or is there something wrong in my code? The compi...
enabling address sanitiser shows that your code is causing undefined behaviour: https://godbolt.org/z/n3rnn9nqY riter contains iterators from line but at the end of your while loop you reassign line, invalidating line's iterators and therefore invalidating riter, when you then try to increment riter you enter the realm...
74,456,525
74,456,719
How to define 'i' in a (I think) constant array and the sum in c++ with variables?
I keep on getting an error message about line 29, and that the 'i' in "individualCommission[i]" isn't defined. Also, I am trying to find the sum of the entire array. #include <iostream> #include <iomanip> using namespace std; void heading( string assighnmentName ); // prototype - declare the function void divid...
Your code was simple to fix. You had put a statement outside the for and it couldn't save the data inside the array. The change was made in line 61: #include <iostream> #include <iomanip> #include <numeric> using namespace std; void heading( string assighnmentName ); // prototype - declare the function void dividerLi...
74,457,085
74,457,300
[[nodiscard]] attribute different compilation result for GCC and Clang
#include <iostream> #include <memory> class A { public: static [[nodiscard]] std::unique_ptr<A> create(); virtual int get_version() = 0; virtual ~A() = default; }; class B : public A { public: [[nodiscard]] int get_version() override { return 20; } }; std::unique_ptr<A> A::create() { ...
You can see here https://eel.is/c++draft/class.mem#general that the attribute can only appear first in a member declaration. Hence this static [[nodiscard]] std::unique_ptr<A> create(); is wrong. And should be [[nodiscard]] static std::unique_ptr<A> create(); Your code has a typo. Newever versions of gcc report a mor...
74,457,351
74,457,563
Can a parent class which is reinterpreted as a child class use the child's functions in its functions?
I want to call the child's function from parent's function in reinterpreted class, like below. Example #include <iostream> class A { public: void func1() { // some code func2(); // some code } protected: virtual void func2() { printf("class A\n"); } }; class B : public ...
For C++ polymorphism to kick in, you must create an instance of the derived class somewhere, but you can store a pointer to the base class. Using the base-class pointer will dispatch to the overridden functions of the derived class. So your definition of A and B is fine, your usage in the main function is not. reinterp...
74,457,605
74,458,654
Why can't wcout use the hex keyword to output hexadecimal format?
I have entered a wchar type variable and want to see the hexadecimal of the variable. However,when I use the wcout keyword, I can't always output hexadecimal. Is there a grammatical error? #include <iostream> void test_wide_character_input() { using namespace std; wchar_t ch = L'?'; wcout << ch << endl; wcout...
Change the character to unsigned int type before converting it to hexadecimal like this: wcout << hex << (unsigned)ch;
74,457,857
74,463,594
ReadFile buffer output is weird (prints content + some more)
I am trying to open a file and read its content using the Win32 API: HANDLE hFileRead = CreateFileA(FilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NO...
std::cout << buffer expects buffer to be null-terminated, but it is not. You need to allocate space for the terminator, eg: PBYTE buffer = (PBYTE)HeapAlloc(GetProcessHeap(), 0, fileSize.QuadPart + 1); ... buffer[dwBytesRead] = 0; Alternatively, you can use cout.write() instead, then you don't need a terminator, eg: st...
74,458,909
74,459,476
How to make the QGraphicsView size consistent with the size of the image and the main window in Qt?
I'm developing a graphic editor with Qt. I'm using a QGraphicsView to display the picture and need to resize it so that it's consistent with the size of the image and the main window. Now I'm resizing it like this (in the method of the MainWindow class): ui->graphicsView->resize(picture->width, picture->height); //...
just override resizeEvent() in QMainWindow const QSize &QResizeEvent::size() const Returns the new size of the widget. void MyMainWindow::resizeEvent(QResizeEvent* event) { // ui->graphicsView->resize(event->size()); QMainWindow::resizeEvent(event); }
74,459,462
74,460,041
Why C++ does not perform RVO to std::optional?
I am wondering why C++ does not perform RVO to std::optional<T> when returning T. I.e., struct Bar {}; std::optional<Bar> get_bar() { return Bar{}; // move ctor of Bar called here // instead of performing RVO } Bar get_bar2() { return Bar{}; // NO move ctor called // RVO perf...
get_bar_rvo does not perform RVO, it performs NRVO (Named Return Value Optimization). This is not guaranteed. For get_bar, instead of constructing a Bar yourself, you can leave that to std::optional using std::make_optional or its in-place constructor (6): std::optional<Bar> get_bar() { return std::make_optional<Ba...
74,459,498
74,459,898
C++ how to write a wrapper for a C api that doesn't know about class instances?
In a project that we intended to write in C++, we use a C-library. This C library provides functions to register callbacks, that are called on each interrupt. We register our callbacks inside the constructor. So we basically have the following (simplified) structure: OurClass::OurClass() { //the registerISRCallback i...
Your class may integrate a static method that you pass as a C callback function (provided the calling conventions are made compatible; if not possible, wrap it in a pure C call). In addition, let your class keep a static table of the created instances, in correspondence to the pins. When a callback is invoked, by knowi...
74,459,707
74,459,855
Why do the C++ Core Guidelines not recommend to use std::optional over pointers when approriate?
In the C++ Core Guidelines std::optional is only referred once: If you need the notion of an optional value, use a pointer, std::optional, or a special value used to denote “no value.” Other than that, it is not mentioned in the guidelines, so in particular there is no recommendation to use it instead of a pointer, w...
That guideline is not listing things in order of "pick this first". It is listing options that are appropriate in different situations, and leaves it up to you which is most appropriate for your situation. In particular, choosing between (const)T* and std::optional<T> is the same as choosing between (const)T& and T. Ad...
74,460,102
74,461,001
How can I print a diagonal matrix in Eigen
I was reading this post and when I was replicating it using #include <iostream> #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Dense> int main(){ Eigen::DiagonalMatrix<double, 3> M(3.0, 8.0, 6.0); std::cout << M << std::endl; return 0; } I get the error error: invalid operands to binary expression ('...
In order to print the matrix you have to cast your DiagonalMatrix to a DenseMatrixType, for example by doing: std::cout << static_cast<Eigen::Matrix3d>(M) << std::endl; Or by using the toDenseMatrix method: std::cout << M.toDenseMatrix() << std::endl;
74,461,244
74,461,644
glfwInit() causes segmentation fault with exit code -1073741515 (0xc0000135)
I have been trying to get one my older projects to work which uses some OpenGL code. I am unable to produce a working executable. All that happens is, just by calling glfwInit(), is a segmentation fault: My best guess is that it somehow doesnt use/find the glfw dll i am trying to use. Let me explain my current setup:...
0xc0000135 is the error you get when your Windows OS could not find a required dll when executing your program. There is a handy site that decodes these types of errors here: https://james.darpinian.com/decoder/?q=0xc0000135 Use this program: https://github.com/lucasg/Dependencies to figure out what dll can not be foun...
74,462,470
74,463,213
If there are many threads are waiting to be notify, which one does the std::condition_variable::notify_one() function notify?
I am writing a c++ multithread program, which have more than one thread wait to be notify. std::mutex mutex; std::condition_variable cv; bool is_prepared = false; bool is_fornt_left_finished = false; bool is_fornt_right_finished = false; bool is_back_left_finished = false; thread t1(&Underpan::FrontLeft,...
It is unspecified which thread will be woken up. There doesn't need to be any particular rule to it. There doesn't need to be any "sequence" either. It could just always keep waking up the same thread (as long as it is always waiting when the notification happens) and it could also randomly wake up a different thread. ...
74,462,835
74,463,025
How can someone else be able to run my C++ project if I use SFML libraries?
I'm new to C++ programming and am working on a Pong game. I want to use SFML libraries, but I want to send the project to a friend. Will he be able to run the project without errors if he does not have SFML installed? Note: I want to send it as a Visual Studio project, not as an executable.
You can just make a "libraries" folder to your project file and add there the SFML folder. After doing that open the SFML folder and go to the bin folder and copy all the .dll files you see. Then paste the dll files to the folder your vs files are (.vcxproj etc)
74,462,888
74,477,308
AES Encryption with EasyCrypto C# and Decryption in C++ using Crypto++
I have encrypted a string using EasyCrypto in C# using the following code Encryption C#: /* EasyCrypto encrypted key format from CryptoContainer.cs file from the EasyCrypto source on GitHub. * Format: * 04 bytes 00 - MagicNumber * 02 bytes 04 - DataVersionNumbe...
In the Crypto++ code, the following steps must be performed for decryption: Base64 decoding of the EasyCrypto data Separating IV, salt and ciphertext (using the information from the CryptoContainer.cs file) Deriving the 32 bytes key via PBKDF2 using salt and password (digest: SHA-1, iteration count: 25000) Decryption ...
74,463,290
74,467,080
Dynamically binding of overridden methods
I'm trying to understand when the compiler has, or not, all the information needed to decide statically or dynamically how to bind method calls to method definitions. I read that in Java there is a rule that binds them statically when the method is overloaded and dynamically when it is overridden. I'm playing around wi...
C++ uses virtual method tables to support dynamic dispatch. An instance of a class contains a hidden pointer to a struct containing the function pointers for the virtual methods for that class. For a simple example: class A { public: virtual void p(); }; void some_function(A* ap) { ap->p(); } The compiler has...
74,463,353
74,470,698
emplace pointer as proper type into std::variant in template
Is it possible to emplace some void* pointer into variant with a runtime generated index. Can this nice solution (from here link), be updated to get index and pointer to emplace? #include <variant> template <typename... Ts, std::size_t... Is> void next(std::variant<Ts...>& v, std::index_sequence<Is...>) { using Fu...
You can do it like this, unpack Ts... and check if the type matches. template <typename T, typename... Ts> bool set(std::variant<Ts*...>& v, int typeIndex, void* ptrToData) { constexpr static auto idx = index_v<T, Ts...>; if (idx == typeIndex) { v.template emplace<idx>(static_cast<T*>(ptrToData)); ...
74,463,881
74,463,973
C++ vector not saving the parent of an object
Suppose I Have class A like this class A { public:int num; public:A* parent; A(){}; A::A (const A &s) { this->num = s.num; } }; Inside the main function I make two object from class A int main() { A a1; a1.num = 2; A a2 = a1; a2.parent = &a1; cout << a2...
Your problem is here: A::A (const A &s) { this->num = s.num; } This is a copy constructor. It is triggered on A temp = List.front(); However, it doesn't set this->parent, which remains uninitialized. So, next line, when you do temp.parent->num you access uninitialized memory. You should also do: (Or remove it ...
74,463,919
74,464,104
Variable Length Array elements random generator
simple task, to generate arrays with length I want to. I don't also know how to get array I've created, except my own weird method. Does the first part of my code work alright and I should reconsider the way I want to get them (optional)? although, I do understand why do I get the same values each time, but I don't thi...
Or using header and std::vector, std::generate (no raw loop). Also when you write code, write small readable functions. And to get unique random numbers random generators need to be seeded. #include <algorithm> #include <iostream> #include <random> #include <vector> int generate_random_number() { // only initiali...
74,464,115
74,464,168
Segmentation fault in linked list c++
I can't seem to get rid of segmentation fault in 2 places. This is the whole code. I would be so grateful if someone could let me know why it isn't working and how can I make it work #include <iostream> template <typename Key, typename Info> class Sequence { private: struct Node { Key key; Info...
You forgot to set next Node *ptr; ptr = new Node; ptr->key = key; ptr->info = info; ptr->next = NULL; // <--- here Honestly it would be better if you looked at your own code rather than looking online. Especially you should learn how to use a debugger. If you were experienced at using a debugger you would have found t...
74,464,611
74,466,697
Move few elements from list to a vector
I am planning to move some elements from a list to the target container(say vector) for further processing. Is it safe to use move_iterator for moving to target And erase the moved section of the source container? #include<list> #include<vector> #include<iterator> struct DataPoint {}; int main() { std::list<Datapoi...
You may find std::move easier to use. And yes, you do need to erase the moved elements in the source container. [Demo] #include <algorithm> // move #include <fmt/ranges.h> #include<list> #include<vector> #include<iterator> // back_inserter int main() { std::list<int> l{1, 2, 3, 4, 5}; // source std::vector<...
74,464,890
74,466,164
Is there an objective reason why the explicitly instantiated std::less, std::greater and similar offer no conversion to function pointer?
Stateless lambdas can be converted to function pointers, e.g. this is valid, using Fun = bool(*)(int, int); constexpr auto less = [](int a, int b){ return a < b; }; Fun f{less}; but objects like std::less<int>{} can't. I do understand why std::less<>{} can't, because it's operator() is not instantiated until the objec...
Stateless lambdas can be converted to function pointers, e.g. this is valid, [...] but objects like std::less<int>{} can't. "Can't" is the wrong word. After all, a "stateless lambda" is just an object, and it doesn't have any magical rules compared to other objects. A lambda is a class type like any other. It is simp...
74,465,379
74,465,557
What is the use for this Condition in the for loop for(int i = 0; i < m and n; i++)?
I encountered a question in competitive programming and the solution for that include a for loop with a syntax like for(int i = 0; i < m and n; i++){ //Do Something } When I changed the condition from i < m and n to i < m and submitted the solution it was giving TLE whereas in the i < m and n condition the Solutio...
According to the C++ Standard (for example C++ 14 Standard4,section 12 Boolean conversions) 1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other val...
74,465,629
74,466,597
C++ Vector Returned from function not printing right values
I have class A and a main() function: class A { public: int num; public: A* parent; A(){}; A::A (const A &s) { this->num = s.num; this->parent = s.parent; } public : vector <A> foo(A a) { A a1; a1.num = a.num; a1.parent = &a; vector...
In foo(), you are passing in the a parameter by value. That means the A object that main() is passing to foo() gets copied into the a parameter. The a parameter itself is a local variable to foo(). As such, a1.parent is being set to point at a local variable. And then list.push_back(a1); makes a copy of a1, which cop...
74,465,957
74,466,064
How to find elements of a string that cannot be part of a non contigous substring?
I want to write a program that takes 2 strings as input, s1 and s2, and determines which characters of s1 couldn't be part of a non contigous substring that is 2. So after inputting 123625421454 as s1, and 254 as s2, the program would output 0 1 0 0 1 1 1 1 0 1 1 1, where 1 means that a character can be a part of the ...
A key observation is, if you reach a sub-substring prefix of length k up to a position, then you can have a sub-substring of any length less than k up to that position, simply by skipping some of the tail elements. Same holds for postfix. It might sound trivial, but it leads to the solution. So you'd like to maximize t...
74,466,059
74,466,330
unique_ptr is copying when raw pointer is passed into its constructor
I am trying to understand how unique pointers work in modern C++. When I went through the documentations (cppreference and others), I was able to understand that unique_ptr will transfer ownership and not share it. But I am not able to understand why unique_ptr is acting strange when working with a raw pointer passed i...
Is the raw pointer being passed into the copy constructor? Not the copy constructor, no (that takes another unique_ptr as input). The raw pointer is being passed to a converting constructor instead, specifically this one in this case: explicit unique_ptr( pointer p ) noexcept; Isn't the copy constructor deleted (=...
74,466,363
74,466,476
incorrect data in array index - what will happen?
I found a mistake I made in my code associated with indexing an array. It compiled and I didn't notice the issue for some time. I'm curious what the index really was. Intended code: if(arr[i] > 3){//do stuff} what was written: if(arr[i > 3]){//do stuff} what did the array index end up being?
In reality, what happens is very simple. In the first case, the if checks each element of the array and sees if it is greater than 3. In the second case, it's more complex than it seems. In practice, as long as the i is greater than 3, the index taken will be 1, as it satisfies the equation x > 3, otherwise I take the ...
74,466,912
74,466,958
What does 'dict' do in c++?
I was looking at a solution for this problem: Given a string s, find the length of the longest substring without repeating characters. The following solution was posted, but I am having trouble understanding what dict does. I've tried looking for documentation in C++. However, I have not found anything. Can someone e...
dict is just the name that was used for this vector<int>, first parameter is the the size of vector, second is value that should be assigned to all of its positions. This is one of the possible ways to use its constructor, check the example on this page.
74,466,943
74,468,206
How to package several icons for different sizes in a VS C++ app?
I'm developing a C++ app in Visual Studio 2022 with a UI (UI library is wxWidgets). I'm trying to figure out how icons work. I gathered from researching that Windows expects a variety of different icons to be packaged with apps for the best UX (see Which icon sizes should my Windows application's icon include?). Howeve...
You should embed all your ico files with different resolution into one ico file. The ico file is actually a container and can contain multiple images inside.
74,468,115
74,469,652
How to calculate angle of two vectors for determining vertex concavity in ear clipping algorithm
I am trying to implement this ear clipping algorithm (from the pseudocode) here Currently at the point in the algorithm where I am trying to calculate the angle of each vertex in a polygon. I also got the idea of how to calculate the angles with vectors here: here This way I can also determine convexity/concavity. Als...
curr->Angle appears to be set to sin(Angle) from u to v. Therefore concavity/convexity is determined by the sign of ((u.x * v.y) - (u.y * v.x)), since the denominator is always positive. In particular, if the interior of the polygon is on the right as traversing the vector u from its tail to its head, the positive sig...
74,469,222
74,469,247
Returning a child class from a parent class array C++
class Component { // Code here }; class TransformComponent : public Component { // Code here }; class Entity: public: Component components[25]; TransformComponent *getTransform() { for(int i = 0; i < 25; i++) { if(typeid(components[i]) == typeid(Transfo...
'I have an array of components, and inside could be any child class of "Component", like "TransformComponent".' - this statement is false. If you have an array of Component objects, then at each index in the array, there's exactly a Component-typed object and not a descendant. If you'd like to store multiple (e.g. Base...
74,469,225
74,469,427
Is initializer_list considered part of the C++ core language?
I ask because auto deduces{} to be initializer_list. I don't know of any other class in the standard library that the core language depends on like this. You could take out vector or array and C++ would still function, but take out initializer_list and it would break.
What you call {} (specifically = {...}) the standard calls copy-list-initialization. And yes, std::initializer_list is given special consideration in the wording of the standard. If the placeholder-type-specifier is of the form type-constraint auto, the deduced type T replacing T is determined using the rules for temp...
74,469,734
74,469,769
How to copy data from base class to derived class fastly?
I know move constructor can avoid copy, with a high performance. but can i use it in copy data from base class to derived class? for example: // base.h class Base { public: int a; char buff[24]; double bp_[10]; }; // derived.h class Derived : public Base { public: int b; char buff2[16]; }; // main.cpp int...
There is no general way to do this, as the layout of the data in the base and derived classes may be different. You'll need to write a specific function to do the copying for each class. One approach would be to write a template function that takes a base class and a derived class, and uses a static_cast to copy the da...
74,469,822
74,469,832
What does this program do, and how does it do that?
I am having trouble figuring out why this program works. I wrote it based on my notes (OOPP and classes) but I do not understand how exactly it works? I would appreciate any help! Here is the code: #include <iomanip> #include <iostream> using namespace std; class Base{ public: void f(int) {std::cout<<"i"...
This program defines a class called Base, which has a member function called f that takes an int parameter. It also defines a class called Derived, which inherits from Base and has a member function called f that takes a double parameter. In the main function, an object of type Derived is created, and an int variable i...