question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
68,330,903
68,330,982
How to modify value as parameters in lambdas?
In my program, I have a global static value like this: static bool done=false which is taken by callback like this: Library::CallbackType callback(bool& isDone, par1type& par1,....){ return [&isDone,&par1,...](par0type par0){ if(conditionTrue){ doSomething(); } else { thread(...
thread([isDone,par1]()mutable{ This thread is capturing isDone by value. Which means that when it sets isDone to true it will set only its own copy of the original isDone to true. This thread needs to capture it by reference, too. And, if that's the only reason for this to be a mutable lambda, the mutable can ...
68,331,454
68,331,479
Using dependent name in base class name without "typename"
I have a template class for which the base class is also a template parameterized with a type member of one of the outer template type parameters. Example: template <typename X> class Adapter : public Generator<typename X::generated_type>{ using G = typename X::generated_type; }; Here X is some type that has a mem...
One possible solution is to cheat, something along these lines: template <typename X, typename G=typename X::generated_type> class Adapter : public Generator<G>{ // ... }; You were almost there, heading into an additional template parameter territory, but you don't need to explicitly pass it in, just default it. Co...
68,331,504
68,331,520
How can I improve my look-up table using std::map if TOLERANCE is introduced
let's say I have a system to let people query their "social points" according to personal annual income, also I have a look-up table implemented with std::map, where <key, value> indicates <annual income, social points> to avoid repeated Points generation, take a look at this: #include <iostream> #include <map> using ...
You can use either the map's lower_bound or upper_bound methods which will work just like find(), if the key exists, or they will give you an iterator to either the previous or the next key in the map (with certain subtle details that I'll leave for you to discover on your own). You'll just need to add a little bit mor...
68,331,555
68,331,817
Recursive rectangle sub division
I'm really curious about this image and I have little to no information how it was created. Thus, I'm here to research how to do it. Can someone tell me where to begin? I only know this problem might be related to a recursive subdivision task. I can only see the images was divided into 64 blocks initially. There is som...
With help of Google Images I was able to find the name of the person who is in the image: Kenny Cason. With some more research I was able to find the answer. The problem is related to Quad Tree Images: Partition the image into four quadrants. Color each quadrant based on the average color of the pixels in the target i...
68,331,580
68,331,658
Convert boost/filesystem to string
I'm trying to convert boost::filesystem type to string, but it tell me that "string()" is not a member of the boost::filesystem : void myClass::encryptFile() { // Récursion sur un chemin donné for (boost::filesystem::recursive_directory_iterator end, dir(DirPath); dir != end; ++dir) { // Vérification du type d...
Get the boost::filesystem::path first. void myClass::encryptFile() { // Récursion sur un chemin donné for (boost::filesystem::recursive_directory_iterator end, dir(DirPath); dir != end; ++dir) { // Vérification du type de l'objet if (!boost::filesystem::is_regular_file(*dir)) { string...
68,331,631
68,331,714
IO-manipulators as template parameters?
I'm trying to work with a class, let's call it a stream_wrapper. It contains a value of (or a reference to) an std::ostream object as one of its fields. All I want to do is to overload the << operator, so I can use this wrapper like a normal stream. My first idea was just to write it as a function template. Example: cl...
First off, your overloaded operator<< is missing a return *this; statement. Second, I/O manipulators are implemented as functions that take a stream object as input. For example, std::endl is declared like this: template< class CharT, class Traits > std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Tra...
68,331,821
68,331,913
Dynamic memory Allocation in Linked list insert function
I was going through a tutorial on Linked Lists in C++. I found the following code for the implementation for inserting an element in the Linked List: /* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */ void append(Node** head_ref, int new_data) { /* 1. alloca...
Variable names don't exist at runtime, only at compile-time. The new_node variable represents a chunk of memory that is local to the append() function. Each time append() is called, a new memory chunk is created when it enters scope, and that chunk is released when it goes out of scope. Each call to new allocates a ne...
68,332,022
68,332,092
Similar random number generation in python and c++ but getting different output
I have two functions, in c++ and python, that determine how many times an event with a certain probability will occur over a number of rolls. Python version: def get_loot(rolls): drops = 0 for i in range(rolls): # getting a random float with 2 decimal places roll = random.randint(0, 10000) / 10...
In C++ rand() "Returns a pseudo-random integral number in the range between 0 and RAND_MAX." RAND_MAX is "is library-dependent, but is guaranteed to be at least 32767 on any standard library implementation." Let's set RAND_MAX at 32,767. When calculating [0, 32767) % 10000 the random number generation is skewed. The va...
68,332,036
68,350,012
I cannot send an email using curl and c++
im trying to send an email with curl and c++ just like this example but when i execute the program: #include <iostream> #include <curl/curl.h> int main() { int a; char errbuf[CURL_ERROR_SIZE] = {0}; CURL *curl = curl_easy_init(); CURLcode res; struct upload_status upload_ctx = { 0 }; if(cur...
The problem i had in my code was that i thought that by using: curl_easy_setopt(curl, CURLOPT_MAIL_FROM, "myemail@example.com"); i was specifyng the username, which was in fact, an error. To specify the username libcurl has another option: curl_easy_setopt(curl, CURLOPT_USERNAME, "myemail@example.com");
68,332,067
68,332,335
Setting up GL_TEXTURE_2D_ARRAY, framebuffer incomplete
For cascaded shadow mapping I'm trying to use a GL_TEXTURE_2D_ARRAY for the individual shadow maps. However following tutorials found online and even looking up things in a textbook I can't seem to create a working framebuffer, as it always errors with GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT. The code: glGenFrameb...
The tutorial you cited has led you astray. A 2D texture is not the same thing as a 2D array texture. You can either attach a specific array layer (of a specific mipmap level) to a framebuffer, or attach all of the array images in a mipmap. In neither of these cases can you call glFramebufferTexture2D to do this for an ...
68,332,323
68,787,251
Custom shaders/material not working in a custom QQuickItem object
I have tried following the tutorial given by QT's online documentation (QtQuick Scenegraph CustomMaterial Example), but when I debugged my program, the object does not show, appearing to be transparent. However, when I tried replacing my custom shader class with QSGFlatColorMaterial, and set a color, the object does sh...
Ok, so after prodding through the example repo, I did not multiply the vertex_object in the vert shader with the matrix of the object. So after implementing the methods and glsl code from the documention into mine's, I got the shader to show properly. Turns out that I did not properly set the shader position map.cpp bo...
68,332,641
68,332,753
Using Count_if on user input
What I am trying to do, is make a function that counts the number of bodies based on the track type listed within their container. Since this is looking for a certain parameter, I used count_if. This is how the structure is set up. struct body{ string name; string cartype; string tracktype; string price...
You are trying to pass a string to count_if() where a predicate is expected. Use a lambda instead, eg (assuming inventory is a collection of body elements): string tempStr; cout << "What track type?"; getline(cin, tempStr); int sum = count_if(inventory.begin(), inventory.end(), [&](const body &b) { return b.trackty...
68,332,750
68,430,422
Google kickstart Record breaker wrong answer
I was trying to solve the record breaker problem from google kickstart Round D 2020 I submitted the following code in C++: #include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int testcase; cin>>testcase; int t=1; while(t<=testcase){ ...
Finally I found the answer to my own question. Well I don't know whether posting answer on my own question is right or not but still I think it might help someone who may face similar problem. There is just a little problem with the logic, I missed just this one edge case which I tried hard to find. Kickstart considers...
68,332,909
68,332,951
OOP Basic question about compositions, inheritances and polymorphisms
I have this code and I want to know if it has these three concepts : compositions, inheritances and polymorphisms.(and if it doesn't have them how do i use them in the code) plase help.
Here is an example of composition: a Circle is composed of a Point and a radius: class Circle : public Shape { private: Point center; double radius; Here is an example of inheritance: a Rectangle is type of Shape: class Rectangle : public Shape Here is an example of polymorphism: The getArea() method is de...
68,332,966
68,335,150
How to set C/C++ compiler options for best optimizations for the CPU in use?
To build binaries with the best optimizations for a specific CPU, how to set C/C++ compiler options? For example, try to utilize CPU features like MMX/3DNow!/SSE/SSE2/SSE3 when the feature is available.
GCC and Clang support -march=native to select the CPU to generate code for from the processor type the compiler is executing on and -mtune=native to optimize code for it. Note that these switches are listed in specific architecture sections, such as the X86 or ARM architectures, so they might not be available for all a...
68,333,030
68,522,558
How to integrate msvc CL /DEBUG with visual studio devenv /DebugExe
I use msvc (visual studio cl.exe) on the command line to compile one of my c++ projects. To do so, I use the Visual Studio Community 2019 developer console In cmd, I initialize my environment by calling: call "%ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools\VsDevCmd.bat" call "%ProgramFiles(x86...
To summarize the answers provided in the comments to the question: The compiling and linking must be done in one step since the executable is being compiled outside of a visual studio project: to compile and link: cl /Zi /EHsc <compiler options> <source files> /link <linker options> <library and resource files> to deb...
68,333,284
68,333,456
Path Queries on a Tree
Given a tree and Q queries to be answered. In each query you will be provided with 2 nodes u & v. You should return the path, like u -> v1 -> v2... -> v I have a naive approach to perform DFS for each query but can it be made any better? Is any kind of pre-processing possible? (I'm new to graphs! Kindly help me and als...
I am assuming that at each tree node you also have the parent node, using which you can go up in the tree as well. With this assumption, this problem seems to be that of finding the lowest common ancestor. Which is a standard problem, and you can easily find on the net how to solve it. Once you have the lowest common a...
68,333,673
68,333,742
C++ C26495 warning shows up but I don't know how to solve
Here is my code: #pragma once #include "Card.h" class Foundation { Card* cards[13]; int current; char suit; friend ostream& operator<< (ostream& os, Foundation& f); public: Foundation(char suit = 'H'); bool isPlacable(Card* c); void put(Card* c); bool isFull(); void clear(); }; ...
You get the warning because you don't initialize the member in the constructor or use an initializer list. probably this can fix your warning: class Foundation { Card* cards[13] = {}; int current; char suit; friend ostream& operator<< (ostream& os, Foundation& f); public: Foundation(char suit = 'H...
68,333,789
68,333,854
C++ concept that checks if parameter present doesn't work
I have some class hierarchy in my project: template<typename T> class __declspec(dllexport) EnableSharedFromThis { public: ... uint64* last_valid_counter = nullptr; }; class __declspec(dllexport) Material : public Object, public EnableSharedFromThis<Material> { ... } class __declspec(dllexport) Material3...
In { expr } -> concept, the type of expr is determined as if by decltype((expr)). decltype((T::last_valid_counter)) is uint64 *&, so that's what you need to pass to std::same_as. Interestingly, Clang appears to have a bug, since it appears to use decltype(expr) instead.
68,333,902
68,334,129
a pointer points to an object in vector after sorting(C++)
There are structs like these class Component { string name; int x; int y; }; struct Relation_h { // also for Relation_v (h for horizontal, v for vertical) Component *; //some data in here; }; I have a initial vector vector<Component> data and vector<list<Relation>> relation_h and relation_v I wa...
One such solution (but of course, not the only one) as mentioned in the comments is to use an auxiliary index array as described in this answer #include <vector> #include <iostream> #include <algorithm> #include <string> #include <numeric> //... struct Component { std::string name; int x; int y; Compon...
68,333,931
68,333,991
Can't initialize a variable
I am trying to write a simple program for converting currency rates.But I cannot assign a value to double.Here is the error code Severity Code Description Project File String Suppression status Error C4700 used uninitialized local variable "grn" Twice D: \ programs \ Microsoft Visual Studio \ repos \ Twice \ Twice.c...
You dont have declared dollar variable. In Your code grn doesnt have any value so output can be always 0.
68,333,937
68,334,029
How to terminate an application when an error happnes?
I am using a Graphics Library called Irrlicht at some point i have to write this code if(!device){ //error code here` } i am not in the main function but want to close the application when this error happens please keep in mind that I am a beginner so this question might sound dumb i see some people do t...
The following example give you an idea about some of the possibilities. You can simply copy and paste it and play around with it. Simply use only one line of the "termination actions" like throw or exit. If you don't have the try catch block in the main function, your application will also terminate because the excepti...
68,334,432
68,334,551
Using find() function on vector of vector in c++
So I was trying to check whether a vector exists in a vector of vector or not, using the find() function but leetcode editor is showing compilation error #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<std::vector<int>> res{{1, 2, 3}}; if(std::find(res.begin(), res.end(), ...
You have to mention the vector type when calling find: #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<std::vector<int>> res{{1, 2, 3}}; if (res.end() != std::find( res.begin(), res.end(), std::vector<int>{1, 2, 3})) // An initializer list alone is not enough ^...
68,335,334
68,335,383
reference to a const player object
I have this: // Const in Classes #include <iostream> #include <string> using namespace std; class Player { private: std::string name; public: std::string get_name() const { // consty method return name; } void set_name(std::string name_val) { name = name_val; ...
const Player *p is a pointer to const-Player. It's not a reference at all. (And you code doesn't compile at least because of that). If you want a reference you need void display_player_name(const Player& p). In void display_player_name(const Player p) Player is passed by value, so it will be copied before being used by...
68,336,250
68,337,116
What is the best way to implement static variables per class child? [C++]
In my code, I want all children of class Component to have a unique ID that is only shared per their own instances. Right now, I'm implementing such a system like so: template <class componentType> struct Component { static unsigned int ID; }; Example component: struct Transform: public Component<Transform> { ...
What you could do is to let Component inherit from Component_base and that this class has a virtual function get_id which is implemented by Component: #include <iostream> namespace { static unsigned int next_id = 0; template<typename T> unsigned int get_type_id() { static unsigned int id = ++next_...
68,336,277
68,336,580
Template class member with different return types
I have a template matrix class, e.g. (simplified form): template<typename Scalar, typename Accessor = GenericAccessor> class Matrix { public: Matrix(size_t num_rows, size_t num_cols, const std::vector<Scalar>& elems) : num_rows_(num_rows), num_cols_(num_cols), accessor_(num_rows, num_cols), storage_(elems) {} pr...
If I understand your question correctly you want to return Matrix<Scalar, TransposeAccessor > if Accessor = GenericAcessor and the other way round. One way to do that is to create a helper class template, that allows you to get the opposite type (you might need to choose a better name) for your accessor by specializing...
68,336,280
68,336,770
Determine whether programs run on Powershell or CMD
I created a program that should rename some files system("rename file.txt file2.txt"); // examples only did run fine at cmd , but not powershell rename : The term 'rename' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, v...
How to determine whether my programs runs on powershell or cmd by C++ While that is possible, it also irrelevant to your use case, because the shell that launched your program is your program's parent process (to which you cannot submit commands). Since your program must launch its own shell (child) process in order ...
68,336,285
68,336,619
Sorting two arrays that are linked into descending order. One is a string array, one is an int array. c++
I'm still relatively new to coding and a recent assignment I had has been stumping me quite a bit. I have two arrays that are essentially linked to one another. 0 on one side must be 0 on the other, and I need to find the easiest way to sort the one with the numbers into descending order while doing the same to the oth...
You could sort the arrays like this in a double for loop: for(int j=0 ; j<studentNum ; j++) for(int i=0 ; i<studentNum-1 ; i++){ if(studentGrade[i] < studentGrade[i+1]){ //swapping condition string temp = studentName[i]; studentName[i] = studentName[i+1]; studentName[i+1]...
68,336,462
68,336,544
unable to read last line, using getline()
I have to read the test cast as follows. 3 ababa abc babac c++ code to read the above input. int main() { int t; cin>>t; while(t--){ string s; getline(cin,s); cin.clear(); cout<<s<<endl; } return 0; } but the output I'm getting is ababa abc can you help me h...
When you do cin >> t; the Enter key you used to end that input is left in the input buffer as a newline. This newline will be read by the first call to getline as an "empty" line. A simple solution is to ignore the remaining of the input after getting the input for t: cin >> t; cin.ignore(std::numeric_limits<std::stre...
68,336,624
68,336,697
Convert user's entered time into a Unix timestamp
I am trying to make a program that converts readable time, that user enters into a Unix timestamp. It should work like this: string time; int unixtime; getline(cin, time) // User enters time in a format as HH:MM, say 15:00 ??? // Today's date gets appended to time, so July 11th, 2021 ??? // Date gets converted to Unix ...
One option is to use std::get_time: #include <ctime> #include <iomanip> // std::get_time #include <iostream> int main() { // get current time std::time_t now = std::time(nullptr); std::tm ut = *std::localtime(&now); // or std::gmtime for UTC // get hour and minute from the user if(std::cin >> std:...
68,337,292
68,337,396
Multi-file Factory method
There are two classes Base and Derived. Base.h: class Base { public: Base* create_obj(); }; And Base.cpp : #include "Base.h" Base* Base::create_obj() { return new Derived(); }; and Derived.h : #inlcude "Base.h" class Derived : public Base { }; If the two classes were in main.cpp then there would be no error. But ...
You can try and do this // Base.h class Base { public: Base* create_obj(); }; // Base.cpp #include "Base.h" #include "Derived.h" Base* Base::create_obj() { return new Derived(); }; // Derive.h class Derived : public Base { }; Basically I removed "Derive.h" from "Base.h" and move it to "Base.cpp". Since you do...
68,337,376
68,337,715
What is the meaning of default_constructible range adaptors in C++23?
Since C++23, views are no longer required to be default_constructible. For range adaptors such as views::filter and views::transform, their default constructor is redefined as: template<input_­range V, indirect_­unary_­predicate<iterator_t<V>> Pred> requires view<V> && is_object_v<Pred> class filter_view : public vie...
The status quo before this paper is that views simply have to be default constructible, even if that isn't a meaningful requirement that can be fulfilled by the view, leading it to have a singular state that can only be assigned to. That wasn't very useful (and indeed harmful), which is why that requirement was removed...
68,337,380
68,337,792
Check if an item inside a tuple contains a specific method
I have a tuple and I'm trying to call initialize() for each object inside the tuple. Now, some objects might not contain that function. I know I can make that work by using C++20 requires feature to check if a class contains a given function. Unfortunately, I'm using MSVC and it doesn't support that yet. Is it possible...
If you don't have access to requires yet, then you will have to make use of SFINAE and write a type-trait for detecting whether initialize() is a callable member function. This can be done with std::void_t, albeit a little awkwardly: #include <type_traits> // std::void_t #include <utility> // std::declval template...
68,337,391
68,337,520
Why does this merge sort algorithm not work properly?
I get no errors or warnings. Here's my code: #include <iostream> void merge(int arr[], int l, int m, int r); void mergeSort(int arr[], int l, int r); int main(){ int arr[11] = {1, 9, 2, 5, 3, 10, 4, 8, 6, 7}; mergeSort(arr, 0, 10); for(int i = 0; i < 11; i++){ std::cout << arr[i] << "\t"; } ...
The problem is with the merge function. You have to loop through l to r, inclusive not 11. Please see the reference code for a better understanding. Reference Code #include <iostream> void merge(int arr[], int l, int m, int r); void mergeSort(int arr[], int l, int r); int main(){ int arr[11] = {1, 9, 2, 5, 3, 10,...
68,338,071
68,338,101
Adding a new line to existing txt file in c++
As a tutorial I've been a question to add new line to an existing file with a list of items. i've tried numerous ways to add it. no luck yet ofstream outdata; ifstream indata; indata.open("fruits.txt"); outdata.open("fruits.txt"); if(indata.is_op...
When you open a file for writing its contents are immediately removed, if the file already exists. outdata.open("fruits.txt"); You opened the same file for writing here. This is before your code tries to read anything from the same file (I don't actually see anything in your code that tries to read it, I presum...
68,338,203
68,343,479
Base Class causes Compilation Error (Visual Studio)
Beginner here. I´ve recently written a bit of code to log using spdlog. I based it on a "Singleton" base class and it doesn´t seem to be working, which irritates me, since in all other cases that I´m using that exact "Singleton" base class it works. I get the following errors: 1>D:\dev\Makeshift\MakeshiftEngine\src\Uti...
[Answer given by "Igor Tandetnik" & "drescherjm"] Circular Includes! Singleton.h included Log.h, which led to a circular include, causing the compiler to go haywire. Always check what you include, this can also happen if you include another file that includes the file your including it in. It happened to me with my pc...
68,338,330
68,338,444
remove hints in jetbrains
How to remove this hints in CLion in my case?
File > Settings > Editor > Inlay hints [C++]
68,338,833
68,338,973
Iterate throught n-dimensional vector c++
I wanted to write my own code to iterate over an n dimensional vector (where the dimension is known). Here is the code: void printing(const auto& i, const int dimension){ int k= dimension; for(const auto& j: i){ if(k>1){ cout<<"k: "<<k<<endl; printing(j, --k); } e...
If the dimensions are known at compile-time, this can be solved easily with a template that takes dimensions as the non-type argument. template <std::size_t Dimensions> void printing(const auto& i){ if constexpr (Dimensions != 0) { for(const auto& j: i){ // I'm not sure if it is intentional to p...
68,338,943
68,338,980
Int input (for a date) added to an AVL tree are incorrect
My problem is in C++. I have a class AVL tree that has been tested and works properly and a Map tree class. I created a Map tree like this: Maptree<string, Mapatree<Date, Maptree<string, int>>> personservice; And then tried to add a entry to the map tree like this: personservice["Mike"][Date(0, 15, 30, 30)]["Car"]++; ...
days = days; hours = hours; minutes = minutes; seconds = seconds; These four statements, in the constructor, assign the values of four constructor parameters to themselves. In other words, this does absolutely nothing at all, whatsoever. If you just look at these four lines of C++ code, outside...
68,339,701
68,339,755
C++ Create class that inherits a Vector
I would like to know if I can create a class that inherits a vector that contains vectors (2d) and can write my own methods. using matrix = vector<vector<float>>; class MyClass: public matrix; ... MyClass m; m = {{1,2,3}, {4,5,6}, {7,8,9}} m.randomize(); // my method m.pop_back() //class vector method
I would like to know if I can create a class that inherits a vector that contains vectors (2d) and can write my own methods Yes, nothing prohibits this although it's generally recommended to use composition instead. One reason why it's not recommended is that the standard containers destructor is not virtual so delet...
68,339,732
68,339,809
C++ transferring variables between functions
I'm not quite sure what I messed up here. I'm making a basic program that converts Fahrenheit to celsius. I can't figure out how to transfer the f variable over to the calcC function. All that I'm getting is a prompt for Fahrenheit and then it tells me that it is 0 degrees celsius. #include <iostream> using namespa...
You are ignoring the return values of getF() and calcC(), and you are not passing anything at all to calcC(). calcC() is performing integer arithmetic on (5 / 9), which will result in 0, not 0.555... as your formula requires. You need to use floating-point arithmetic instead. Also, your formula is wrong, as you need to...
68,339,912
68,339,987
How to call a method from a object instance that is being used by a thread?
Given a class in MyTimer.h: #include <iostream> using namespace std; class MyTimer { private: bool active = false; public: void run() { active = true; while (active) { cout << "I am running\n"; Sleep(1000); }; } void stop() { active = false; } }; When I execut...
You have three problems: active should be declared as a std::atomic <bool>. Without this, changes made in one thread may not be seen by another (the compiler might optimise out the check). std::thread th(&MyTimer::run, myTimer); copies myTimer. Instead, you want std::thread th(&MyTimer::run, &myTimer);. while (tru...
68,340,034
68,340,072
Why do `&n` and `&n + 1` differ by `4` instead of `1`?
I would expect the values of &n and &n + 1 to be adjacent memory boxes, so their address should differ by 1. However, every time I run these commands, I get addresses that differ by 4 (for example 0056F800 and 0056F804). Why does this happen? #include <iostream> using namespace std; int main() { int n = 3; co...
Pointer arithmetic creates a pointer to a specific element of an array (or equivalently, a single object which is treated as an array of size 1), so it effectively changes the value of the pointer by multiples of the element size. On your system an int is apparently 4 bytes in size so by adding 1 to an int * it creates...
68,340,057
68,340,093
How to read bytes from file using std::ifstream to std::array?
The below program tries to open a rom file and loads it to std::array. #include <array> #include <fstream> #include <iostream> const std::string ROM_FILE = "cpu_instrs.gb"; int main() { std::array<uint8_t, 0x8000> m_Cartridge; std::ifstream istream(ROM_FILE, std::ios::in | std::ios::binary); istream....
std::istream is written in terms of char_type being simply char, and similarly, std::istream::read is the same. The conventional approach would be to reinterpret_cast<char*> the pointer that you are reading to: istream.read(reinterpret_cast<char*>(m_Cartridge.data()), length); Although using reinterpret_cast is often ...
68,340,085
68,340,177
Custom Vector class jump on uninitialised value
im trying to create a custom vector class in c++. As im quite new to the whole c++ world im a bit confused. Valgrind is telling me that im doing a jump on an uninitialised value. However I don't know why that appears. My personal answer would be alright i dont initialize any values in the normal vector(unsigned startCa...
There are a lot of problems with this code. Most notably, your operator== has some logic errors in it. But more importantly, if(*this == x) in operator= should be if(this == &x) instead. Also, your copy constructor is implemented wrong. It allocates room for only 1 element, but then attempts to copy as many elements ar...
68,340,131
68,340,166
How do I prevent zero in a template parameter?
I have a template class where the template parameter corresponds to the size of an array within the class. template <typename T, size_t S> class Example { ... private: T values[S]; }; This leads to an expected warning: “ISO C++ forbids zero-size array.” In my case, something like Example<uint8_t, 0> would ma...
You're really trading in one compiler diagnostic for another, but here's one approach: template <typename T, size_t S, typename=std::enable_if_t< (S>0) >> Alternatively: use static_assert to get a friendlier error message: template <typename T, size_t S> class Example { private: static_assert(S>0); T ...
68,340,391
68,340,753
Lib boost not being accessible outside main
I'm trying to use Boost in my project, but it is only being accessed inside main.cpp. If I try to include it in another file I get an error. I don't know if it's something that must be specified in the CMakeLists.txt. # CMakeLists.txt ... include (cmake/CPM.cmake) CPMAddPackage( NAME PackageProject.cmake GITHUB_R...
As Tsyvarev pointed out in the main message thread, I forgot to link Boost with the other libs I wanted to use. I ended up being able to run it by adding the following line target_link_libraries(Utils PRIVATE Boost::system)
68,340,511
68,341,412
Multi-line comment indentation formatting in Visual Studio 2019
In Visual Studio 2019, are there any settings to allow the configuration of the multi-line comments in order to always align new star characters (i.e.*)? When inputting the first new line in a multi-line comment, a star (i.e. *) character is automatically generated and aligned with the backslash (i.e. \) character and ...
Okay, I figured it out. @VRichardJP was exactly right - this formatting feature is for a Visual Studio extension to do. After trying a few, I found an extension that does exactly what I need and allows some flexibility: Doxygen Comments. I am actually using Doxygen, so this extension is perfect for me, but even if you ...
68,340,530
68,377,314
Create new NativeFunction and use it then
I am wondering: how can I allow self-signed certs while app using openssl library? I saw that code which disables certificate validation StackOverflow question/answer hyperlink static int always_true_callback(X509_STORE_CTX *ctx, void *arg) { return 1; } This is the method, where I should put this new method, which ...
There are many ways to accomplish your goal TL;DR var SSL_CTX_set_cert_verify_callback = Module.findExportByName('libssl.so', 'SSL_CTX_set_cert_verify_callback'); Interceptor.attach(SSL_CTX_set_cert_verify_callback, { onEnter: function(args) { Interceptor.replace(args[1], new NativeCallback((_arg1, _arg2) => { ...
68,340,622
68,341,063
Why new and delete operators signatures are different from all other operators
The signature for the new operator is: void* operator new(size_t count) There is a white space between the word "operator" and the word "new". This is: Different from all other operator signatures (besides new, delete and their array counterparts). for example: T& operator=(const T& other) Does not comply with funct...
The C++ grammar is actually written in terms of tokens, which is consistent between all types of operator definitions. operators are special-purpose and fixed in terms of what tokens can follow after the operator keyword, but the whitespace that occurs is not mandated anywhere in the standard. As far as the C++ grammar...
68,340,779
68,340,919
Nested Conceptual Polymorphic Templates
Suppose I have compile time polymorphic inheritance structure: enum class Enum1 { Undefined = 0; /* ... */ }; enum class Enum2 { Undefined = 0; /* ... */ }; template<Enum1 A, Enum2 B> struct Base { int state; }; struct Derived : public Base <Enum1::Undefined, Enum2::Undefined>> { int statederi...
struct Derived : public Base <Enum1::Undefined, Enum2::Undefined>> { int statederived; }; This creates a mapping from Derived to Base<Enum1::Undefined, Enum2::Undefined>, but does not create a mapping the other way around. Now you could do this template<Enum e1, Enum e2, class D> struct DerivedExtra:Base<e1, e2> { ...
68,341,004
68,342,854
Needleman algorithm not working when matrix values are the same
I am trying to solve the "Longest Common Subsequence" question using needleman. Example: Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest common subsequence is "ace" and its length is 3. I am very confused on how the algorithm should work for the case where text1 ="ezu" and text2= "ubm". The Nee...
Each cell of the Needle matrix is actually showing which action is considered best when aligning two sequence: Insert a letter from both sequence and thus moving diagonally (Match or Mismatch) Insert a letter from one sequence and a gap instead of the other one and thus moving vertical or horizontally based on penal...
68,341,036
68,341,377
What loop size to multithread?
Imagine a simple loop: constexpr int N; // some big number #pragma omp parallel for for(int i=0; i<N; ++i) { // some not very demanding computation like // c[i] = a[i] + b[i] } How can I determine (approximately), if such loop is suitable for parallelization with respect to size N? For example, if I have a 20...
There is obviously no rule of thumb for choosing whether parallelization is suitable for a given piece of code, simply because it does depend on too many things: do you really need the extra performance? maybe your code is totally fine running in 147ms instead of 23ms? maybe you also care about code readability? power...
68,341,103
68,341,168
Does setting objects to null the same as garbage collecting in c++?
I have a question here that asks me that if setting the properties of class to null is the same as collecting a garbage in c++. And how this is related to memory management. Thanks
There is no garbage collection in c++. If you do not deallocate memory it will not be deallocated. Once an object is destroyed however all member objects are destroyed as well, BUT pointers are not the objects they are pointing to, therefore those objects would have to be destroyed manually. And to your question: If yo...
68,341,229
68,341,247
C++ Reference to non-static member function is required
I am making a simple browser using QT5. I have a QMainWindow with a QWebEngineView inside of it and I am trying to make it so that it auto accepts permission requests but I can't seem to get it to work... (Later I will make it prompt the user) I looked online and found something but the solution didn't work for me as t...
The connection syntax should be: connect(ui->view->page(), &QWebEnginePage::featurePermissionRequested, this, &MainWindow::onFeaturePermissionRequested); Fore more information read New Signal Slot Syntax. It is also better to use the enum value explicitly instead of the numeric value: ui->view->page()->setFeaturePermi...
68,341,232
68,343,612
What does 'target_link_libraries' do when the target is a static library and the target link is a static library too?
From the following example: CMakeList.txt file: include_directories(inc) # Grab all the cpp and h files to be compile. file(GLOB SOURCES inc/*.h inc/*.hpp src/*.cpp ) add_library(MyStaticLib STATIC ${SOURCES} ) target_link_libraries(MyStaticLib PUBLIC "${OPENCV_LIBS}/opencv_world410.lib" ) target_li...
In short When target_link_libraries is applied to the static library, it won't affect on the resulted library file. But it affects on the target in the similar way, as it would affect on the target of the shared library. So, you can use target_link_libraries both for static and shared libraries in the same manner. In d...
68,341,599
68,341,644
std::ws vs. std::skipws in C++
I'll start with a short piece of code to explain my question: #include <iostream> #include <string> int main(){ int val; string s; std::cin >> val; std::getline(std::cin >> std::ws, s); std::cout << val << s << std::endl; return 0; } I understand that using std::cin >> val will leave a ...
std::skipws (and std::noskipws) only apply to formatted input, ie operator>>, which uses the stream's sentry class (the sentry is the one doing the actual skipping). They have no effect on unformatted input, like std::getline(), which don't use the sentry. They set/clear the stream's inner skipws flag, which stays in e...
68,341,711
68,341,840
Is the AutoSeededRandomPool in crypto++ actually random? What does fork() in the documentation mean?
I was reading the documentation of AutoSeededRandomPool in crypto++ and I came across the detailed description as follow. You should reseed the generator after a fork() to avoid multiple generators with the same internal state. Does this mean AutoSeededRandomPool is actually not random? And also when is fork() called? ...
There is a posix API called fork() which is used for creating internal child process. The forked process is sometimes used in exchange of thread. When you use fork(), a lot of internal memory of process is copied. That's why they say that you need to call reseed. Because if you don't, this copied internal memory create...
68,341,741
68,344,956
What is google recommand method to import sqlite3 C++ in bazel project?
How to import sqlite3 C++ to bazel project? I find many sqlite3 encapsulation with bazel build of third_party project since sqlite3 does not support bazel officially, and they worked. How can I import sqlite3 or any other officially single-source-file project elegantly? Perhaps there are some google recommend docs?
Google internally hold everything in their repo. You don't want to do this, because you don't want to maintain each of external dependencies on your own. If you want to see how to use bazel with C++ I recommend an envoy project, because it is open source thus the used idiom are more applicable to the general usage than...
68,342,122
68,342,204
Include functions from other cpp(hpp) file with main()
I am using C++ for some sequence data analysis, and have found it hard to call functions across files. Say I have a file A.cpp with an associated header A.hpp. A.cpp has a Main() function and a function My_Func() that I hope to reuse in B.cpp, which also has a Main() function. My question is, how do I call My_Func() fr...
Create another header file, e.g. common.hpp and declare the function definition of My_Func() in that header file. Then, create another cpp file, common.cpp and implement the function inside there. Now, if you include common.hpp in both of A.cpp and B.cpp, calling My_Func() will work from both A.cpp and B.cpp.
68,342,632
68,348,721
(c++23 implicit move) Returning the moved local storage variable as an rvalue ref with only parenthesisses?
Regarding the proposal "Simpler implicit move" (P2266R1), I'm not sure if I understand this new "move-eligible" things correctly. Please correct these points if incorrect: [LIVE] std::forward becomes optional for perfect forwarding the rvalue ref received template<class T> T&& seven(T&& x) { return std::forward<T&&>...
All three of the points are correct. In all cases, the variable in question is an implicitly movable entity (except seven if instantiated with an lvalue) and thus is treated as an xvalue. The parentheses here: Widget&& h3(Widget t) { return (t); } don't actually do anything. They would if the function returned declt...
68,342,846
68,343,396
Access inner class variale on outer class
I want an array in outer class which a variable in inner class is the size of array: struct Outer { struct Inner { int size{}; int something_else{}; }; Inner inner; int data[size]; // size is not declared in Outer, hence compiler give an error }; How can i do something like this?
Since inner is defined before data, initialization works just fine: struct Outer { struct Inner { int size{}; int something_else{}; }; Inner inner; std::vector<int> data; Outer() : Inner(), data(inner.size) { } }; Yes, a struct can have a constructor too. It's just a by-default-public class.
68,343,114
68,343,517
Initialize the array of struct in c++11
I am facing a problem in initializing an array of struct. Below is the code: #include <iostream> #include <array> #include <string> #define NUM_ELEMENT 5 struct Person { std::string m_name; int m_age = 0; Person() = default; Person(std::string name, int age) : m_name(name), m_age(age) {} }; t...
You are trying to initialize personList which can only be done at construction - but personList is already constructed so that doesn't work. You should be assigning instead: personList = { Person("abc", 10), Person("cde", 20), Person("pqr", 30), Person("xyz", 40), Person("apple", 50), }; alternativ...
68,343,217
68,343,288
Nested vector<float> and reference manipulation
final edit: I got it! //Initialize each collection using pointers array<float, 3> monster1 = { 10.5, 8.5, 1.0 }; //coordinates and direction of first monster array<float, 3> monster2 = { 13.5, 1.5, 2.0 }; //coordinates and direction of second monster array<float, 3> monster3 = { 4.5, 6.5, 3.0 }; //coordinates and dire...
You can use std::array. No need to use raw pointers: #include <array> #include <vector> using Monster = std::array<float, 3>; void updateMonster(Monster& monster); int main() { std::vector<Monster> monsters; monsters.push_back(Monster{1.f, 2.f, 3.f}); monsters.push_back(Monster{4.f, 5.f, 6.f}); monsters.pus...
68,343,377
68,343,915
Pyramid number pattern doesn't print the correct output
This is the output I want to print for the input number 5: 1 11 202 3003 40004 #include<iostream> using namespace std; int main() { int n; cin>>n; for(int i=1;i<=n;i++){ for(int j=1;j<=i;j++){ if(i==1 && j==1){cout<<'1';} else if(i!=1 && i<=n && j<=i && j!=1){ cout<<i...
Try this code #include <iostream> using namespace std; int main(){ int row; cin >> row; if(row>=1) { for(int i =0; i<row;i++) { for(int j=0; j<=i;j++) { if(i==0) cout<<'1'; else if(j==0 || j==i) cout<<i; else c...
68,343,416
68,343,679
The inferior stopped because it received an error from the operating system SIGSEGV (Segmentation Fault)
analysismainwindow.h #ifndef ANALYSISMAINWINDOW_H #define ANALYSISMAINWINDOW_H #include <QPixmap> #include <QMainWindow> namespace Ui { class analysisMainWindow; } class analysisMainWindow : public QMainWindow { Q_OBJECT public: explicit analysisMainWindow(QWidget *parent = nullptr); ~analysisMainWindow(...
Since you don't initialize the chessboard::ui pointer variable it will have an indeterminate value, and using indeterminate values leads to undefined behavior. You need to initialize this pointer, by creating a chessboard constructor which takes it as an argument. Also, for Qt to work properly you need to dynamically c...
68,343,712
68,343,837
Access by type in std::tuple with duplicated types should produce compilation error
According to the standard (or at least to cppreference) the std::get for std::tuple shall: 5-8) Extracts the element of the tuple t whose type is T. Fails to compile unless the tuple has exactly one element of that type. So I interpret that sentence such that this code does not compile: std::tuple<int, int> my_record...
Looks like a GCC 11 bug, consider filing it. Here's the revelant part of the standard. You see it in Clang because on gcc.godbolt.org it uses GCC's standard library by default. If you add -stdlib=libc++ to use it's own standard library, it refuses to compile it.
68,343,993
68,347,116
Find total number of substrings with 1's greater than 0's, need optimization
Given and string we need to find out the total number of substrings in which 1's are greater than 0's. I approached this problem using Dynamic programming but I was not able to come up with a solution, I am successful in writing a naive-logic but I was not able to optimize the code (i.e time limit is exceeding) Any hel...
Treat respectively '0' and '1' as integers 1 and -1. Then the string becomes an integer array. Calculate its prefix sum array s, i.e., s[0] = 0 and s[i] = a[0] + ... + a[i - 1]. Now every substring with number of '1's > number of '0's corresponds to a pair (i, j) such that i < j and s[i] > s[j]. You can then use the tr...
68,344,056
68,344,225
How to insert into a map of vectors. map<int, vector<int>> map; I want to insert values into the vector one by one
I want to insert values into this vector, Not all at once but one by one. How will I do this? Like for e.g. I want to insert 1,{2}. Now I want to insert 1,{3} into the map of vectors again. The final value in the map should contain 1,{2,3}. How do I do this? If I use the insert function, then 3 won't be inserted or if ...
How would you insert elements to a vector when it is not in a map? Not like this: std::vector<int> v{2}; v = {3,4}; Because this replaces the whole vector with a different vector that has elements 3 and 4. But like this: std::vector<int> v{2}; v.push_back(3); v.push_back(4); It works the same when the vector is insid...
68,344,349
68,348,453
Android NDK values coming as empty sometimes
I am trying to use NDK for my android application. I am using the map to store some key values as follow: #include <jni.h> #include <string> #include <iostream> #include <unordered_map> class UrlHash { std::unordered_map<std::string, std::string> urlHash; public: std::string getUrl(std::string urlKey) { ...
The buffer returned from GetStringUTFChars is only usable as long as you do not call ReleaseStringUTFChars. Do the lookup while you the buffer is usable, instead: const char *NativeUrlName = env->GetStringUTFChars(urlName, 0); auto result = _debugHashtableInstance.getDebugUrl(NativeUrlName); env->ReleaseStringUTFChars(...
68,344,902
70,727,224
UE4 - Get children widgets from UUserWidget's pointer (UMG)
I got my non-UObject class holds an UUserWidget* Instance; So how do I get a children widget (Ex: UTextBlock) out of that Briefly, I want something like this: Instance->GetChildrenWidgetByName("UTextBlock_Name")
In 4.26.2 you can do this if you know the child's name Instance->WidgetTree->FindWidget(WidgetFName); or this if you just want to find it by type TArray<UWidget*> Children; Instance->WidgetTree->GetAllWidgets(Children); for(auto Child : Children) { if(UTextBlock* Block = Cast<UTextBlock>(Child)) { //ret...
68,344,981
68,345,468
What is the difference between "and" and "&&" in c++
Recently I found a code where is used the keyword and which working like &&. So are they both the same or is there any specific condition to use it?
The C++ standard permits the token && to be used interchangeably with the token and. Not all compilers implement this correctly (some don't bother at all; others require the inclusion of a special header). As such, code using and can be considered idiosyncratic. The fact that the equivalence is at the token, rather tha...
68,345,236
68,345,342
C++ function pointer to self
Is there a way to have a function pointer to the function that's getting it. It should work like this: void foo() { assert(<self-pointer> == &foo); } (moved form comment): I want a macro that can log something and add the place where the log came from to it. For this I want to use an id, which I thought I coul...
There are no equivalent of this (about class instance) for function/method.
68,345,277
68,345,545
C++ primer 5th exercise 7.52
Exercise Using our first version of Sales_data from § 2.6.1 (p. 72), explain the following initialization. Identify and fix any problems. My code: #include <iostream> #include <string> using namespace std; struct Sales_data { string bookNo; unsigned sold_units = 0; double revenue = 0.0; }; int main() { ...
Your confusion is caused by the fact that the use of initializers and initializer lists changed significantly between the C++98, C++11 and C++14 standards. The code you have shown is badly-formed according to C++98 (the in-class initializers are not allowed) or C++11 (the brace-enclosed initializer list is not allowed)...
68,345,704
68,346,546
C++ Register Constexpr Callbacks
Hi Stackoverflow community, i have the following requirement: I want to have a base class called PeripheralBase which has a constexpr constructor. Now i want to inherit from this base class with multiple other classes like Adc or Timer. #include <stdint.h> #include <array> #include <iostream> class PeripheralBase { ...
I will start with some observations from your code: You have a kind of container functionality in your Base class. This means, the base class is also containing the element pointers of its own type. For me it is bad design as a container is not the base type itself. For that I personally want to split the container typ...
68,346,409
68,346,475
c++ - no matching function for call to
My terminal messages zo@laptop:~/Desktop$ g++ stack.cpp stack.cpp: In function ‘int main(int, char**)’: stack.cpp:50:19: error: no matching function for call to ‘boyInitial(Boy [boyNumber])’ boyInitial(boy); ^ stack.cpp:17:6: note: candidate: template<class T, int N> void boyInitial(T (&)[N]) ...
The key error message is the following note: variable-sized array type ‘long int’ is not a valid template argument You declared a variable length array (the size of the array is not a constant expression) int boyNumber = 0; cout << "how many boys do you want?" << endl; cin >> boyNumber; Boy boy[boyNumber]; that i...
68,346,661
68,346,856
Reassigning CComBSTR, memory leak?
As it's written in the MSDN documentation CComBSTR::operator= creates a copy of src. So when I write someCComBSTR = std::to_wstring(someVal).c_str(); I will have a copy of the temporary and everything is ok. But I haven't found what happens with the previous value, will it be freed or rewritten, or I first should manu...
CComBSTR is defined in the header atlcomcli.h in Visual Studio's atlmfc/include directory. All assignment operators (operator=) release the currently owned data by calling SysFreeString (with some exceptions that aren't interesting here). The line of code posted in the question will not leak any resources. It is invoki...
68,346,874
68,347,306
How can I solve the "empty response" error using nghttp2?
I'm using nghttp2_asio. I compiled it using ./configure --enable-asio-lib. Then, I added /usr/local/lib to /etc/ld.so.conf file. The code is as follows: #include "bits/stdc++.h" #include "nghttp2/asio_http2_server.h" using namespace std; using namespace nghttp2::asio_http2; using namespace nghttp2::asio_http2::server;...
It looks like your browser refuses to do HTTP/2 over an unencrypted connection. The Wikipedia page has the following to say: Although the standard itself does not require usage of encryption,[51] all major client implementations (Firefox,[52] Chrome, Safari, Opera, IE, Edge) have stated that they will only support HTT...
68,347,088
68,348,988
Overload rvalue and lvalue reference for template deduced type with return value and its implementation
There are a lot of similar questions here on SO (e.g.: How to get different overloads for rvalue and lvalue references with a template-deduced type?), but not exactly this one. In particular, no questions are concered with value returning functions. Furthermore, I am not sure (euphemestically spoken) whether I understo...
Through the magic of reference collapsing... template<class T> [[nodiscard]] std::decay_t<T> unique(T&& t) { std::decay_t<T> vec=std::forward<T>(t); std::sort( vec.begin(), vec.end() ); vec.erase( std::unique( vec.begin(), vec.end() ), vec.end() ); return vec; } works for both cases. DR...
68,348,035
68,381,621
How can I tell which fullscreen Keynote window is the presentation?
When there are multiple displays and a Keynote presentation is started, it creates a fullscreen window on each display. Only one of these is the presentation and the other(s) contain e.g. a timer, but all have the same CGWindowName. How can I find which CGWindowID corresponds to the presentation? Ideally in C++ please,...
The best way I've found so far is by comparing the CGWindowLayers. The presentation appears to always have the higher window layer, although I don't know if that's guaranteed.
68,349,027
68,349,083
Is it possible to extract data from std::vector without copying it? (and make the vector forget it)
I have a std::vector<byte> object and I want to extract data from it without copying. It may contain megabytes of data. So, if I copy data I would lose performance. Is it possible to extract the data from the vector and make it forget about data, that is, that it doesn't free memory for the data after destruction? Hope...
No, It is not possible to extract part of data from vector as far as I know. It is not compatible with structure of vector that provides its data in a continuous part of memory. std::vector memory is continues, so if it was possible to move part of its memory to another place, you need to shift reminder of memory to ke...
68,349,417
68,350,566
use popen without blocking
In C++ I am running a bash command. The command is "echo | openssl s_client -connect zellowork.io:443" But if this fails I want it to timeout in 4 seconds. The typical "/usr/bin/timeout 4 /usr/bin/sh -c" before the command does not work when run from the c++ code. So I was trying to make a function that uses popen to...
Use std::async to express that you may get your result asynchronously (a std::future<ExecuteCmdReturn>) Use std::future<T>::wait_for to timeout waiting for the result. Here's an example: First, a surrogate for your executeCmdWithTimeout function that randomly sleeps between 0 and 5 seconds. int do_something_silly() {...
68,350,094
68,350,171
Android CMake: how to check if cppFlags and arguments are taken into account at compile time?
I have a Android/NDK/JNI/Java/C++ project. I have a Gradle file that looks like this: .... cmake { cppFlags "-std=c++11 -fexceptions" arguments "-DANDROID_STL=c++_static" } .... My question is: how to check that these flags and arguments are well taken into account when my ...
I have a big cmake file with parts like this: cmake { arguments "-DANDROID_TOOLCHAIN=clang", "-DANDROID_STL=c++_static" cFlags "-D__STDC_FORMAT_MACROS", "-fno-integrated-as", "-fvisibility=hidden" cppFlags "-fexceptions", "-frtti", "-fno-integrated-as", "-fvis...
68,350,458
68,350,583
How to correctly make a nested custom linked list in C++
I'm trying to create a nested linked list like this (list<list<list<Object> > >) with a custom singly linked list for an assignment. the problem is that I tested it and the program returns a "memory could not be read error" and terminates. This is the code I used to test it int main (){ List<List<List<int> > > thir...
You copy the inner list by value when you push it into the outer list: bool push_front(const T &Valor) { // ... newNode=new node<T>; newNode->info=Valor; but your List does not have a copy constructor. That means it will use the default generated copy construct...
68,350,667
68,351,130
Why this C++ program results wrong outputs for some unknown testcases, I'm unable to debug?
I'm getting correct result for my inputs(I have tried 30+ inputs manually and got correct output for all), but after submitting on a practice portal, some testcases are resulting wrong output and I'm unable to debug! Question for reference: Chef likes to play with cards a lot. Today, he's playing a game with three card...
bbboxx would fail since you first filter out card with b You can try separate cards into categories card with o and b card with only o card with only b card with neither (no use) then compute the result
68,350,961
68,351,151
Run ninja without rules
I have a build where it would be easiest for now to just have unique build rules for each build target (eg object file and library). Is it possible to specify in the build.ninja-file what to do without first specifying a rule for it. For example (toy syntax) build this_file: depends_on_this.o depends_on_that.o - gcc a...
As usual I found out a way to do this a minute after asking. We could just forward the whole command as a variable rule run command = $cmd build log.txt: run cmd = echo $hello >> log.txt
68,350,992
68,351,811
How can I have CMake compile the same input file in two different languages?
I have a file named foo.bar. I want to compile it once as a C++ file, into a mycpplib library target, and once as a C file, into a myclib target; and I want to do it in the same build, with the same CMakeLists.txt. Now, I know I can arbitrarily set a source file's associated language, like so: set_source_files_properti...
You could create library targets mycpplib and myclib in the different directories (in the different CMakeLists.txt). That way you may call set_source_files_properties in the directory where mycpplib library is created, and that call won't affect on myclib. There are also DIRECTORY and TARGET_DIRECTORY options for comma...
68,351,041
68,351,877
How can I replicate R's functionality with multiplying a matrix by a vector element-wise in Rcpp or Armadillo?
In R, multiplying a matrix by a vector is element-wise by default, and works like this: A <- matrix(c(1,2,3,4,5,6), nrow=2) b <- c(1,3) A * b [,1] [,2] [,3] [1,] 1 3 5 [2,] 6 12 18 Essentially, each element of the matrix is multiplied by an element of the vector round-robin. I want to recreate thi...
Here are a few options. I suppose the third is closest to what you want -- documented at http://arma.sourceforge.net/docs.html#each_colrow #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] // looping through each column and element wise multiplication // [[Rcpp::export]] arma::mat matTimesVec(arma::mat ma...
68,351,284
68,353,006
Find the largest Magic Square
Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid. The question can be found here on leetcode I first wanted to see if a naive brute force approach would pass, so I came up with the following algorithm Iterate through all values of k (...
The calculation of antiDiagSum is wrong: it actually sums the values on the same diagonal as diagSum, just in reverse order. To traverse the opposite diagonal, you need to increment the Y coordinate and decrement the X coordinate (or vice versa), but your code decrements both of them. It is probably easiest if you fix ...
68,351,441
68,352,112
Why is std::sort complaining about a deleted copy ctor?
Let's say we have a simple class that holds a std::string: class StringWrapper { public: const std::string s; StringWrapper(const std::string s) : s(s) {} // We want this to be moveable but not copyable ~StringWrapper() = default; StringWrapper(const StringWrapper&) = delete; StringWra...
This has already been covered in the comments, but it's worth noting for posterity, the use of the default keyword does not guarantee that the compiler is always going to attempt to create a default implementation of a special member. This is (as usual) well-explained in the section on move assignment operators on cppr...
68,351,589
68,356,314
Serialization of Unordered Map Using Fstream
I need to serialize an unordered map. The method below uses fstream to read and write data into the map in binary mode. However, it prints 0 instead of 5 after clearing the map and loading it back in. These functions work correctly when modified to be used with a vector instead of an unordered_map. #include <iostream> ...
Containers serialization is a trivial problem, for unordered_map it's implemented as a hashtable, its implementation is somewhat complex, you may get a glance from this picture. In your code, you are expected that the unordered_map have a beginning address (char*) p_map_ptr and a fixed size sizeof(*p_map_ptr) and with ...
68,352,072
68,352,089
The variadic template with automatic return type argument deduction
I implemented simple code to add all the numbers together, but when inserting one floating number everything gets weird! How to analyze the behavior of the compiler to deduce the return type? #include <iostream> template <typename N> auto summer(N n) { return n; } template <typename N, typename... Args> auto summ...
Problem is that return type of summer() is double, but you are printing it with %d. Result is similar to when you run a code like this: printf("%d", 100.1); This is UB (Undefined Behavior). Quote from cpp ref: If any argument after default conversions is not the type expected by the corresponding conversion specifie...
68,352,697
68,353,310
input in C++ -> Python platform
#include <iostream> int main(){ int CurrVal = 0, val = 0; // read first number and ensure that we have data to process if (std::cin>> CurrVal){ int cnt = 1; // store the count for current value we're processing while (std::cin >> val) { // read the remaining numbers if (val =...
2 things: My questions is: How can I convert if (std::cin>> CurrVal) from C++ to Python code? Answer: You cant explicitly convert code one from another. They are different languages, with different way of working, arthmetic semantics, way of operator works. (there is some project which do "similar" thing, but it is o...
68,352,718
68,353,059
Is it necessary to call destroy on a std::coroutine_handle?
The std::coroutine_handle is an important part of the new coroutines of C++20. Generators for example often (always?) use it. The handle is manually destroyed in the destructor of the coroutine in all examples that I have seen: struct Generator { // Other stuff... std::coroutine_handle<promise_type> ch; ~G...
This is because you want to be able to have a coroutine outlive its handle, a handle should be non-owning. A handle is merely a "view" much like std::string_view -> std::string. You wouldn't want the std::string to destruct itself if the std::string_view goes out of scope. If you do want this behaviour though, creating...
68,352,743
68,353,594
How to use `std::unordered_map` in a thread-safe way?
What I have done I had the idea to wrap std::unordered_map, and the to lock it for every operation. And it looked something like this (I will just leave one operation to not clutter the question): template<class Key, class T> class thread_safe_unordered_map { public: T &operator[](const Key &key) { std::...
Now, because operator[] returns a reference, and they both will act on the same reference, I think that this could still be a data race. Is this right? This is right assuming T isn't a thread-safe type. This isn't a data race in the operation of the container, but a data race in the use of the object of type T. I ha...
68,352,968
68,369,630
Compile a C++ program (LANShare)
I'm having problems compiling LANShare's sourcecode. I need to compile this program because i need to use it on a 32-bit unix machine and there's no .deb or appimage release file. This is LANShare. As you can see there's no config file and i don't know how i can proceed with compilation. I compiled from source many tim...
Found a solution, thanks to n. 1.8e9-where's-my-share m. Theese instructions should be valid for any Debian 10 install. To install qt tools: sudo apt install qt5-qmake qt5-default then to compile: qmake -o Makefile LANShare.pro make
68,352,969
68,353,117
Using a templated function parameter type name to call a function
I am using a C API that defines some functions for different types. Something like: // defined in a header: extern "C" A* A_create(); extern "C" B* B_create(); Is it possible to call these functions from a templated C++ function such that the template type parameter determines the C function to call? Something like: /...
Since there's no parameter to use, I would probably just use a function with specializations: // generic version just calls new. template<class T> T* create() { return new T;} template<> A* create() {return A_create();} template<> B* create() {return B_create();} Then usage should be trivial: A* ptr = create<A>(); ...
68,353,051
68,353,250
Writing heapify function from scratch, getting a "stack-based buffer overrun"
I am trying to implement the heap sort algorithm for the first time, but I am getting an error with the heapify function. Unhandled exception at 0x0005369A in heapify.exe: Stack cookie instrumentation code detected a stack-based buffer overrun. The console does open, and the output is 999 10 5 11 1012398875 2 0 1. Coul...
Unhandled exception at 0x0005369A in heapify.exe: Stack cookie instrumentation code detected a stack-based buffer overrun. The console does open, and the output is 999 10 5 11 1012398875 2 0 1. Could someone help me understand what is going wrong here? Thank you. Stack of process (one of real-live uses of stack data ...
68,353,346
68,353,389
Why isn't my class recognizing the iostream class inside my main.cpp although I included iostream?
So I was practicing OOPS and was trying to understand private and public.For this I created a different file in sources folder of my project(btw I am using Code::Blocks) like this: +--Sources +--main.cpp +--student.cpp main.cpp : #include <iostream> #include "student.cpp" using namespace std; int main(){ Stu...
There are too many issues with the organization of this code that lead you to the problem. Here it is a list of things to fix: Never use naked using namespace std; (outside a well defined scope). Using it "globally" (like you did) breaks encapsulation (in some sense) by changing the meaning of code far away. The puzzl...
68,353,571
68,353,654
Do I have to write a copy constructor when writing a move constructor in C++?
I know about the rule of five which states that if you implement a destructor, you should most likely also implement a copy constructor, copy assignment operator, a move constructor and a move assignment operator. However if I implement a move operator, do I absolutely have to implement a copy counterpart, or is it jus...
The "Rule of Zero" may be applicable to your situation. Why are you providing a move constructor or move assignment operator in the first place? Is it because your class represents unique ownership of some resource? If so, it may be better to encapsulate ownership of that resource in a unique_ptr member or something si...