question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
65,049,168
65,049,412
Magick++ Image.GetPixels return nullptr after many succesful iterations
I'm trying to make steganography with C++ using Magick++. Here is my code for now #include <iostream> #include <fstream> #include <string> #include <Magick++.h> #include <bitset> #include <vector> int main() { using namespace Magick; using namespace std; int wd = 0, ht = 0; InitializeMagick(nullptr); ...
You're probably encountering undefined behaviour as you're not using getPixels correctly. Please see the documentation PixelPacket* getPixels ( const int x_, const int y_, const unsigned int columns_, const unsigned int rows_ ) I.e. you want to use src.getPixels(j, i, ...
65,049,297
65,049,354
Perspective projection inverting x axis (glm::perspective)
When I use a perspective projection in OpenGL, my X axis gets inverted as seen in the image below. The code below might not be valid because I changed it a lot in order to make it less obscure. It might not work, so just keep that in mind. Here is the code and vertices: typedef struct{ float x; float y; float...
The x-axis doesn't get inverted because of the projection matrix, but it get's inverted because of the view matrix. glm::vec3 position = glm::vec3(0, 0, 0); glm::vec3 look_at = glm::vec3(0, 0, 1); glm::mat4 viewMatrix = glm::lookAt(position, look_at, glm::vec3(0, 1, 0)); The view space is a Right-handed system, wher...
65,049,468
65,049,554
C++ rule of 5 - segmentation fault on custom destructor
I have been learning C++ for some time and started writing a larger project just to realise that whatever I was thinking about C++ is wrong. Basically I have a class called DenseVector which holds doubles. I want to move, copy construct etc that vector to use it with vectors etc. The class looks something like this: D...
I can see at least two problems: DenseVector &DenseVector::operator=(const DenseVector &other) { this->size = other.size; memcpy(values, other.values, size * sizeof(double)); return *this; } You are not checking whether you have enough space in this->values. If this->size is smaller than other->size, you n...
65,049,479
65,054,162
Which compiler is right about inline static members of template parameter type using a Singleton CRTP?
I made a very simple Singleton base class that can be used with CRTP to make any class that derives from it a singleton. I found something strange though. Different compilers disagree on whether the code is ill-formed or not. Here it is: template <typename Derived> class Singleton { public: inline static Derived in...
GCC and Clang are correct. temp.inst/3: The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions, of the non-deleted class member functions, member classes, scoped member enumerations, static data members, member templates, and fri...
65,049,662
65,051,820
If another pointer (p) points at a class that was allocated to another pointer (head), will the former (p) invoke a destructor?
If another pointer (p) points at a class that was allocated to another pointer (head), will the former (p) invoke a destructor? And if it's so, then should I equate (p) to NULL to prevent double destruction of objects? int main() { node* head = new node(1); find (head); //smth delete head; return 0;...
delete ptr does two things. First, it invokes the destructor, based on the type of the pointer ptr. Then it returns the storage used for the object to the free store (aka heap). In your code you call delete once, so only one destructor is called. If you called delete twice on the same pointer (or a copy of the point...
65,050,084
65,053,907
C++ Polymorphism : Is it possible to use a function from a double derived class into the base class?
I'm new to polymorphism and I'm trying to learn how this exactly works . I want for example to get the print() function of class Y and use it in the base class . Is this possible to do ? class A { public: A() = default; virtual void print() { //Is it possible to get the print() function of class Y here ? };...
Your main() is creating an A object directly, not a Y object. That is why you are not seeing the output you want. Polymorphism only works when accessing derived class objects via base class pointers/references, eg: int main() { Y y; A *a = static_cast<C*>(&y); a->print(); return 0; } int main() { Y y; A ...
65,051,200
65,051,474
Convert initializer_list of pointers to vector of unique_ptr
I created this class, which represents a set of shapes: class CompoundShape : public Shape { private: std::vector<std::unique_ptr<Shape>> shapes; public: CompoundShape(std::initializer_list<Shape *> shapes) : shapes(shapes) {} void draw() { for_each(shapes.begin(), shapes.end(), [](auto &s...
Sad that we cannot use std::initializer_list<std::unique_ptr<Shape>>. You can still use constructor of vector taking 2 iterators to do the (not so explicit) conversion: CompoundShape(std::initializer_list<Shape *> shapes) : shapes(shapes.begin(), shapes.end()) {} Demo vector constructor would do something similar to t...
65,051,365
65,051,597
Intercept the function call to add a argument before an if
I made a console.log function to mimic the javascript console.log function. The problem i have is to line break after all argumets because i'm unable to detect when is a single argument call or is the last argument being called due to function overload. The solution i thougth off is to add a new argument on functions f...
You should probably use different name: template <typename ...Ts> static void log(Ts&&... ts) { (do_log(ts), ...); std::cout << "\n"; } // private: template <typename T> static void do_log(const T& arg) { std::cout << arg; } template <typename T> static void do_log(const std::vector<T>& v) { std::cout...
65,051,740
65,053,381
How do I clamp __m128i signed integers into non-negative unsigned integers in SSE
I can't figure out how to convert 4 x 32 bit signed integers stored in a single __m128i into "unsigned" counterparts. The conversion should be done with value truncation, clamping negative numbers to 0 but leaving non-negative numbers unchanged. E.g: -100 should turn into 0, while 100 should remain 100 #include <stdio....
Use SSE4.1 _mm_max_epi32 as: my = _mm_max_epi32(my, _mm_setzero_si128()); Or without that, @chtz's elegant a & ~(a >> 31) can be implemented using SSE2 as follows: my = _mm_andnot_si128(_mm_srai_epi32(my, 31), my); Replace <....missing code....> with the above line. Generated assembly for both methods.
65,051,949
65,052,114
How do I correctly pass a reference of a class object into another class-object in C++
Attempting to post an easier to read/debug example of a question I posted earlier. The A-object in main.cpp, which is passed by reference into a B-object seems to end up being a copy of the original A-object; that is to say operations performed on the A-object within the B-object do not affect the instance of the A-obj...
The member a in B should be some kind of reference or pointer. Here is a sample implementation with pointer usage in B: #pragma once #include "A.h" class B { public: void setA(A &aObj) { a = &aObj; } void changeNumber(int num) { a->setNumber(num); } int getNum() { ...
65,052,614
65,075,150
I can't maintain state of a base class amongst subclasses
Summary My goal is to write a rendering engine using DirectX 11. I plan to write it in an OOP fashion. The plan is to write separate classes. Specifically one class for shader where I can load, compile, bind and set it for usage. Second class for creating vertex buffer, where I can load vertices, bind buffers and set i...
Inheritance is built upon a is-a relationship. What most people get wrong is that it's not a in perspective of the object itself, but upon the functionality that the object brings with it. In your case, the functionality of the D3D class is to initialize and allocate the 3D engine context. Right? The Demo and Shader cl...
65,052,665
65,052,814
OpenGL nvoglv32.dll error after resizing window
I have the following function: void introMenu(unsigned int texture,Shader shader, unsigned int VAO){ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); shader.use(); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); } I call it after the following function: int bu...
In GLFW, the GL context is tied to the window, and when you destroy the window, you destroy the GL context - and all the GL objects with it: textures, buffers, shaders, VAOs, whatever. And all the GL object names your code still holds become invalid. If you re-create the window, you have to re-create all of your GL obj...
65,052,702
65,052,855
ERROR! invalid operands of types 'float' and 'const char [2]' to binary 'operator<<'
I'm trying to make a program that is an equivalent of a four function calculator for two fractions.. The Error comes up in each of the switch cases within the cout statements. The Error is: [Error] invalid operands of types 'float' and 'const char [2]' to binary 'operator<<' I tried googling, nothing found but I did ...
check your parentheses: cout<<"Addition of Given Fraction is: ("<<N1<<"/"<<D1<<") + ("<<N2<<"/"<<D2<<") = " <<(((N1*D2)+(N2*D1))<<"/"<<(D1*D2))<<" = "<<(((N1*D2)+(N2*D1))/(D1*D2))<<endl; ^ ^ Try this: case '+': cout<<"Addition of Given Fraction is: ("<<N...
65,052,731
65,052,755
Equivalent code in C for the following call by reference in c++
What will be the equivalent code in C for the following C++ code? int main() { //... int count=0; fun(++count); //function call //... } void fun(int &count) //function definition { //... fun(++count); //Recursive Function call //... } Here count variable is used to keep ...
You might use pointer: int main() { int count = 0; ++count; fun(&count); //function call // ... } void fun(int *count) //function definition { // ... ++*count; fun(count); //Recursive Function call // ... }
65,052,867
65,052,971
Expect four printouts from while loop, getting only one
I'm trying to write a program using a while loop that gives an output based on range of input variable declared. #include <iostream> using namespace std; int main() { float fahren = 0; float celsius; while (fahren < 400) { // convert fahreneheit to celsius // Subtract 32, then mu...
You print 4 values but without separator, you might add std::cout << std::endl; while (fahren < 400) { // convert fahreneheit to celsius // Subtract 32, then multiply it by 5, then divide by 9 celsius = 5 * (fahren - 32) / 9; std::cout << celsius << std::endl; // added new line here fahren +=...
65,053,029
65,053,087
My program does not print the correct output
When I run this program and enter "1" on woodtype and "S" on the size, "try again appears. what could be the problem? ps. the input for Wood Type are 1,2,3 input for size are S,L #include <iostream> using namespace std; int main() { int woodType; int L; int S; int size; cout<<"Furniture Co...
From the description you gave, S and L should be char literals. Right now you're inputting size as an int, and then comparing it to other uninitialized ints. Additionally, as @bloody noted in the comments, you should use && (logical AND) instead of & (bitwise AND): int woodType; char size; cout<<"Furniture Company\n ...
65,053,089
65,053,110
what is the diff between creating object and object()
class A{ public: A(){cout<<"Constructor called"<<endl;} ~A(){cout<<"Destructor called"<<endl;} }; int main(int argc, char const *argv[]) { A x; A y(); return 0; } what is the difference between x and y as x prints while y doesn't print'
A x; This is declaration of a variable. A y(); This is declaration of a function.
65,053,142
65,053,177
Custom Compare Function for Priority Queue
I was implementing a custom compare function for priority queue and saw a difference between the compare function of sort and priority queue STL. Suppose, we have couple of points(x, y) and for those points we have a user defined class. class Point { int x; int y; public: Point(int _x, int _y) { x = _...
std::priority_queue Note that the Compare parameter is defined such that it returns true if its first argument comes before its second argument in a weak ordering. But because the priority queue outputs largest elements first, the elements that "come before" are actually output last. That is, the front of the queue co...
65,053,185
65,053,242
Garbage values are being initialized as the values of my hash table even though I specifically code all indices to -1
I don't know if I'm missing something very simple but I'm having trouble initializing all values of my empty hash table to -1. I have an another array with the ID numbers (that I will hash). I'm initializing all values to -1 because I can check later if the value of my hash array is -1 then I can insert without quadrat...
In your constructor: int arr[bsize]; //creating an array to hold hash values This is non-standard C++. Variable-length arrays are not standard C++. In standard C++ all array sizes are constant which are determined at compile time and not runtime. But, more importantly, is that this is a local variable in the construc...
65,053,295
65,053,324
overloading socket.h method in a template
I am trying to use templates to make a generic interface type class. As such, I want to have a "connect()" function in the template class. When I make an implementation of the template for a socket interface, however, the compiler thinks I mean the connect() function of the parent and not the connect() function that ...
You might full qualify the call: ::connect(sockfd, p->ai_addr, p->ai_addrlen);
65,053,517
65,053,683
What line is causing the 'operator==' error
This program allows for a user to add an items storage location and search for an item by name to find it later. I am getting a weird error when I try and run my code. Everything was working fine until I added in a search function for the vector. Any ideas on what is going wrong since I don't see a line item issue? Th...
Error messages for the algorithm library are indeed terrible. I hope with concepts we get better error messages for the standard library in the future. Let's look at the documentation of std::find. There it says that the signature of std::find is template <class InputIterator, class T> InputIterator find (InputItera...
65,053,816
65,053,886
**How to solve gmock void signature**
So i got a mock method, with void signature: ***MOCK_METHOD(int, GetMaxCrossSectionNumber, (void), (const, override)); And it gives me this error: This method does not take 1 arguments. Parenthesize all types with unproctected commas
You should not pass void: MOCK_METHOD(int, GetMaxCrossSectionNumber, (), (const, override));
65,053,911
65,059,842
How should I change the IMAGE(doesn't matter the type) of the button in the toolbar in MFC applications?
I know that this is stupid problem but I am stuck with it for the past 4 days. Why it is so complicated to just modify the toolbar in the MFC apps? I create New Visual studio MFC application that is dialog based. I create new Toolbar resource. And then how should I set images(png, bitmap, jpeg...) or whatever type to b...
I answered this recently and can no longer find my answer. You can use PNG images for your toolbars. Under the hood you still use the BMP version for the resource editor to create your event handlers etc. But you can then add your PNG as a resource and then load it into your dialog. For example, I call this in my OnIni...
65,053,970
65,054,917
Troubles with printing functions in Binary Search Tree
My exercise is to Insert Elements in BSTree and Find the Max element of it. After I did that, It is not printing anything and always return 0. I tried with Print Function but it was same i don't know the reason . Please help. Thanks in advance .................................................
First, you have to include the comments in your code then others can understand. And I found a lot of bugs in your code. The first thing to note is if you have a non-void function it should return something. And using namespace std; pollute the namespace. Hence, use using std::cout; using std::endl; And it is no need ...
65,054,509
65,054,755
.cpp file not seeing .h file at compile time
I am trying to compile a unit for a class, which I have split into a .hpp and .cpp file. The files are called player.hpp and player.cpp. I used the command g++ -c player.cpp. Here is player.hpp #define PLAYER #ifndef PLAYER #include <string> #include <iostream> class Player { private: char symbol; ...
In your player.hpp, the order of lines in the include guard is incorrect. It should be: #ifndef PLAYER #define PLAYER
65,054,753
65,054,802
C++ read memory faild
I have 2 classes: class b_class { public: int time_viewed; int parent_course; b_class()=default; b_class(int parent_course):time_viewed(0), parent_course(parent_course){ } }; and: class b_course { public: int course_id; int num_of_classes; b_class **classes; b_course(int course_...
You are allocating an array of pointers that don’t point at any valid objects. And you are allocating more space for the array then you actually need. b_course::b_course(int course_id,int num_of_classes) { this->course_id = course_id; this->num_of_classes = num_of_classes; classes = new b_class*[num_of_cla...
65,054,882
65,058,652
Visual Studio 2019 C++ external dependencies are missing
I installed the Desktop development with C++ for Visual Studio 2019 latest version. When I create a new Console App project and the "Hello World" code opens, the editor shows compile errors on #include and std::cout, as shown below: What I noticed is that the External Dependencies folder of the project is empty. Do y...
I solved by just installing the Windows SDK from Visual Studio Installer. I did not install it at first because it was in the optional extensions.
65,054,958
65,057,694
Interger representing a Array value is increasing within a for loop when trying to assign characters to a 2D Character array
in my program I am attempting to input characters from a .txt file and assign them to a 2D Char array to form a Maze. The expected outcome of this code is: xxxxxxx xA...Bx xxxxxxx However I am instead warned that Column is greater than size (defined as 30) when I believe it should be 0 at the start of every loop. No m...
rows is used uninitialized in readMaze so the program has undefined behavior. Also, cout << maze << endl; makes the program have undefined behavior by reading out of bounds. Consider making maze a std::vector<std::vector<char>> or even a std::vector<std::string> to make it simpler. Example: #include <algorithm> #includ...
65,055,168
65,055,569
How do I create a manipulator with a parameter?
I can't create a manipulator with the parameter, tell me how to implement it. Writes errors: The initial value of a reference to a non-constant parameter must be a left-hand value. Too few arguments in the function call. #include <iostream> using namespace std; char s[] = "Hello, world!\n"; ostream& endp(ostream& st...
In order to create a stream manipulator that accepts parameters, you need an extra step that your code is currently lacking - you need the manipulator function to not take an std::ostream (or std::istream) as input, but rather to return a proxy object, and you then need to overload operator<< (and/or operator>>) to acc...
65,055,195
65,055,608
Can I delete array element by element?
I'm trying to create custom list. This is the node structure: struct Node { ListNode* prev; ListNode* next; void* data; }; One of constructors creates list from array. So I decided to allocate nodes in consecutive part of memory to make algorithm a little bit faster. auto elements = new Node[size]; element...
What you are trying to do is the most hacky implementation of linked list you can possibly think of. For all real life purpose you should stick with STL and it looks like std::vector does what you want. That being said, if you are trying to implement your own linked list to learn how it works, let me start by saying th...
65,055,233
65,055,346
How, if possible, can I use variadic templates to make a function that prints multiple std::vectors of any type side by side?
I am trying to write a function printV() that takes some number of vectors (probably less than six) of any built-in type printable with cout, passed as const reference and prints them side by side, so that compareV(v1, v2, v3) would produce the output: v1[1], v2[1], v3[1] v1[2], v2[2], v3[3] v1[3], v2[3], v3[3] Here...
You can do this: template <typename firstT, typename... T> void printV(const std::vector<firstT>& first, const std::vector<T>& ... vec) { for(int i = 0; i < first.size(); i++) { std::cout << i << ": " << first.at(i); ( (std::cout << ' ' << vec.at(i)), ... ); std::cout << std::en...
65,055,400
65,055,511
Need to find the sum of all even numbers in 2D array (then divide it on the amount of all even numbers to get the average value)
I think there's some stupid mistake of mine when I initialized two-dimensional array in 'while' or something #include <iostream> #include <iomanip> using namespace std; int sumOfEvenNumbers(int arr[], int Rows, int Columns) { int s = 0; for (int i = 0; i < Rows; i++) { for (int j = 0; j < Columns; j++) ...
Replace while (arr[i][j] % 2 == 0) with if (arr[i * Columns + j] % 2 == 0) As has been commented, you could also just use one loop: for (i = 0; i < Columns * Rows; ++i)
65,055,459
65,055,532
create 2 functions that read and display data
I'm trying to create a function read() and display(). They should read 3 values and print those 3 values using another function which is the display(). I tried doing this: #include<iostream> int read(void); void display(int n1, int n2, int n3); using namespace std; int main() { int n1, n2, n3; n1, n2, n3 = read...
C++ does not allow multiple retruns like you're attempting. There are multiple ways of doing this. Solution one: passing pointers to values and setting them in read function: #include <iostream> using namespace std; void read(int* n1, int* n2, int* n3); void display(int n1, int n2, int n3); int main() { int n1,...
65,055,620
65,055,674
How to run a test for a single function on a hdf5
I am trying to test tarray.cpp. I know you can use cmake, but I need to use G++ for a project. I just need to test the tarray portion and its dependencies. I put the tarray and all its dependencies in the same folder. However, when I try to compile it, I get this error: $ g++ tarray.cpp -o tarray In file included from...
Change #include <hdf5.h> to #include "hdf5.h". See What is the difference between #include and #include “filename”?. The quotes around the #include will check in the current directory, while the angle brackets will check the include path.
65,055,650
65,055,881
A program that gives the longest time (In minutes) a person spends in the bank
Input: The first line of the standard input contains the count of events (1≤N≤100) and a time (1≤X≤23). The next N lines contain the data of events: in the form of 4 integers separated by a space. The first number is the hour part of the time of the event (0≤H≤23), the second is the minute part of the time (0≤M≤59). Th...
This is a possible implementation of finding the longest time a customer has spent in the bank. int max_time = 0; for (int i = 0; i <= row; ++i) { // find entry event if (time[i][2] == 1) { // loop over following events for (int j = i; j < row; ++j) { // find fitting exit event if (time[j][3] ==...
65,055,864
65,055,877
Construct `std::string` from dynamically allocated char array in an owning way
I am working with a library which returns a dynamically allocated null-terminated character string const char* dynamically_allocated_string(); so I am responsible for calling delete on the returned value later. My first instinct is to wrap the value in a unique_ptr so that all the memory management is done automatical...
There is no interface in std::string to take ownership of externally allocated buffers, unfortunately. One option is to provide an oversized std::string buffer to the function that fills the buffer (if there is such an interface) and then trim that string to the actual size. Otherwise, if you'd like to stick with std::...
65,055,929
65,056,046
How to animate snowman without third party libraries?
I have the following code that is just some cout statements that output an image of a cool snowman This is something i like to show to novice programmers to show them how cool programming can be. I wanna take this a step further and show some animation, but after some research, i realized i'd need to download some exte...
Here's a quick program I wrote that I think does what you want: #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <vector> #include <thread> using namespace std; bool update(vector <string> &snowman){ bool ret = false; int row_len = snowman[0].size(); for(int i = 0; i <...
65,056,159
65,056,230
I don't know why this static_assert() code doesn't work
This is the code: #pragma once #include <stdint.h> namespace Detours { static_assert(sizeof(uintptr_t) == sizeof(void *)); } I'm getting this error message: Error (active) E2783 expected a comma (the one-argument version of static_assert is not enabled in this mode)
The static_assert declaration allows the message parameter to be omitted since C++17. (cppreference) You need to enable C++17 in your compiler, or complete the message parameter this way: static_assert(sizeof(uintptr_t) == sizeof(void *), "The message you want to show."); See also How to enable C++17 compiling in Vis...
65,057,010
65,057,046
Why does std::map code compile when operator < is not defined for its data type?
I've learned that passing a user-defined type to a std::map (as well as many other STL data structures) requires the definition of the operator <. Doesn't that mean, however, that the compiler would be able to verify whether declarations of a std::map are correct at compile-time? The below code, which declares a std::m...
In C++(footnote) templates don't have static constraints on their type-parameters (unlike C#'s where constraints). Instead the correctness of C++ template parameter arguments is only determinable when each template member is instantiated by the compiler (compile-time type instantiation, not runtime object instantiation...
65,057,620
65,057,673
Determine CPU on which the calling thread is running?
I'm new to Pthread. I have written an example to check which CPU my thread is running on. I have used sched_getcpu() to get the number of the CPU on which the calling thread is currently executing. Here is my code: #include <pthread.h> #include <stdio.h> void* a(){ printf("1st child thread in CPU %d\n",sched_getc...
Your computer has 2 cores and 4 "logical processors" (CPUs). Because you have 4 CPUs the ID numbers are from 0 to 3. The main problem here is terminology - how "CPU" (and "thread") is defined. You're assuming "CPU" is defined as "core", but most people define it as "logical processor" or "(hardware) thread"; and with h...
65,058,020
65,058,305
Tree being replaced by junk values, when printing tree info
So this is a problem I noticed with a small project I'm working on and I can't figure out what's going on, or what to search to fix it, so I wrote this small program to recreate the problem. I haven't worked with c++ in a few years so apologies if this is a really obvious problem. #include <iostream> #include <vector> ...
The problem is that you are taking pointers to local variables in this line: Cell cell = Cell(c1.getScore() + c2.getScore(), &c1, &c2); The members next_l and next_r are pointing to variables c1 and c2 that are on the stack which is not ok. These values are invalid the moment the function terminates and are overwrit...
65,058,147
65,063,197
update <deque> element by <set> C++
i wanna do this, but i think set::iterator does not return reference of element (just value of element) inside of deque list front {A - B - C - D - E - F - G} back i get element 'C' by this code book& temp = list[2]; and i insert this inside of my set set_list set_list.insert(temp); and in the same local function, i ...
First of all, this code: set_list.insert(temp); doesn't store a reference in your set even though you are using a reference to an object in your std::deque. A copy of the object is made when you insert into the set because STL containers don't allow you to store references. However, you can store pointers in them, a...
65,058,425
65,058,658
C++ Trying to copy several smaller, differently sized, blocks of data into one larger block of data
I have a bit of a strange issue. My audio engine (FMOD) is asking for data in different sized chunks, and my file streaming service (Theoraplay) is providing it's audio data also in variable sized chunks. What I would like to do is push in the audio samples back to back, with the last one likely being only partly press...
As @Retired Ninja says in the linked answer, you need to cast pData to a char * so that you can do pointer arithmetic on it, like this (I am using a C-style cast for brevity): memcpy_s(((char *) pData + nCurrentOffSet), nSize, ((pCurrent->pRawAudio->samples) + pCurrent->nOffset), nSize); Also, just something that stri...
65,058,686
65,058,739
How to loop if statements in C
So i have this if statement if (c[1] < c[0] && c[2] < c[1] && c[3] < c[2] ...) I dont know exactly how many statements it will be, it can be from 1 to 8: if (c[1] < c[0]) if (c[1] < c[0] && c[2] < c[1] && c[3] < c[2] ... c[8] < c [7]) And i need to automate this code, but I have no idea how Here is what i tried to d...
You can declare a counter and increment it every true condition end of while you can check it is equals to the number of statements or not int i = 0; int n; // number of statements int counter = 0; while(i < n) { if(c[i+1] < c[i]) counter++; ... i++; ...
65,058,881
65,058,971
Class and member destructors called twice
class A { public: ~A() { std::cout << "A destroyed" << std::endl; } }; class B { public: A a; ~B() { std::cout << "B destroyed" << std::endl; } }; int main() { B b; b.~B(); } Output: B destroyed A destroyed B destroyed A destroyed Can someone explain to me what's ...
Any object that was created in a limited scope would be destroyed when the scope is exited. Meaning, that if you have created an object on the stack, it will be destroyed when the stack will fold back, along with any other variables declared in that scope. The only exception to this is when you are using dynamic alloca...
65,059,149
65,064,809
What Vulkan swapchain does to the window system default framebuffer
I have few confusions about vulkan surface and its relation to swapchain and window system. As i have understood VkSurface is an abstraction of window and VkSwapchain is a frame buffers collection that we can present on this window. But as far as i concerned, X11 window system creates a default frame buffer along with ...
IIRC there is no "default framebuffer". The swapchain just creates the number of pixmaps you ask for, and with Present X extension it is similar to how Vulkan abstracts it. You present any of them at will, and X will give you an event when the image gets "idle" and can be used again by you. You can look this stuff up i...
65,059,455
65,059,534
Cant print an 2d array in function c++
I have a problem with printing isSymmetric function, I don't know how to print it correctly. And I couldn't find a solution for this in google. #include <iostream> #include <iomanip> using namespace std; const int MAX = 100; void transpose(int mat[MAX][MAX], int tr[][MAX], int N) { for (int i = 0; i < N; i++) ...
Your functions require int mat[MAX][MAX] in their arguments, where MAX is 100. You pass them int a[col][row] where row and col are 99. This creates this problem, as an array with 100 elements is not the same as array with 99 elements...
65,059,630
65,059,976
Macro for C++ to read and output from files
So I do competitive programming and I often need to use files, so I usually do it like this: ifstream fin ("fileName.in"); ofstream fout ("fileName.out"); But I want to make a macro to do this in one line, something like this: #define file(name); {ifstream fin(#name".in"); ofstream fout(#name."out");} Is there a way ...
If you use that pattern so much that you want to make a macro out of it, you probably also check that opening the file works, so I suggest adding that check to the macro too. The curly braces around the expanded macro limits the scope of the variables so you can't use them after the macro has been expanded. Concatenati...
65,059,706
65,059,708
How to implement blocking mock function with gmock?
In my project I need to mock a blocking function that runs on a thread, I need it to release the thread few times during the tests with my control, on my command, I want it to be blocked most of the time as the read func is in while loop. class BlockFuncsIf { public: virtual bool Write(const Msg& msg) = 0; virt...
The solution I found is to wrap the mocked functions and add a semaphore to control the blocking. In this solution I control the semaphore (sem_init, sem_post) from the tests. Note: I wanted to use std::semaphore but it is available only on c++20 so I used semaphore.h insted, there some other implementation for cpp se...
65,060,014
65,061,031
C++ class public function that returns a pointer but doesn't allow deleting that pointer?
template<typename T> class SmartBuffer { int capacity; MyArray<T> *data; public: SmartBuffer() { capacity = 0; data = nullptr; } void alloc(int nbElements) { if (nbElements > capacity) { cout << "Allocating smart buffer\n"; if (data!=nul...
A natual solution would be to declare the destructor of MyArray as private and add friend class SmartBuffer<T> to its definition to allow only SmartBuffer to delete it. However as you stated in a comment you're using MyArray in different contexts and want it to act "normally". Why won't you just implement another type....
65,060,394
65,061,070
Matrix condition not outputting result C++
For every column that contains the minimum number of the whole matrix, I want to replace the column entirely with the minimum number. e.g: input 8 3 3 7 2 1 6 1 8 1 3 1 9 1 7 1 /////// output 8 1 3 1 2 1 6 1 8 1 3 1 9 1 7 1 I came up with this idea: step 1: find minimu...
You asked about the solution in C++. You tend to use static arrays that are more C practice. I took freedom and rewrite your code to a solution that is more of C++ nature. #include <iostream> #include <vector> int main() { std::vector<std::vector<int>> v = { {8, 3, 3, 7}, {2, 1, 6, 1}, {8, ...
65,060,455
65,060,623
Multiplying different types in AVX512
I am currently trying to multiply a __m512d value with a __m512i value. The __m512d value is ln(2), so the result is saved in another __m512d variable. However, I am not able to find any intrinsics for multiplying a double with an integer in avx512. When I use the _mm512_castsi512_pd intrinsic on the __m512i, I get a w...
Thanks to @Peter Cordes for pointing out the mistake regarding the difference between casting and converting. The following code allows the multiplication: __m512d a; __m512i b; _mm512_muld_pd(a,_mm512_cvtepi64_pd(b));
65,060,476
65,060,765
What are "names which are not lvalues"?
There's an entry in the errata of Effective Modern C++ which says that not all names are lvalues What are these names? Specifically, is Scott just referring to the nullptr and this named prvalues? Are there any others? In case the answer to 1 is yes, then what makes nullptr special with respect to true and false? Th...
An expression X where X is the name of an enumerator (declared e.g. as enum E { X };) has rvalue value category. Similarly for non-type template parameters (hat tip to @PasserBy), as in template <int X> int f() { return X; /* X is an rvalue */}
65,060,697
65,060,741
Read lines from named pipe in Winapi
I am creating a named pipe connection between a .NET C# server app and a Win32 client app. In .NET C# it is possible to create a System.IO.StreamReader object from named pipe server/client stream. Is anything similar available in Winapi to read from named pipe line by line??
Named pipes are special files, as such you read from them using the file IO API, namely ReadFile, etc. The MSDN has a complete example for opening and reading from a named pipe.
65,060,761
65,061,948
how to detect and handle unsupported locales in algorithms?
I have a function with the following signature: template <typename Container> void write_cards_as_xml(const Container& cards, std::ostream& os); Internally it calls: boost::property_tree::ptree root; ... boost::property_tree::write_xml(os, root); The write_xml function does not know anything about encodings. By def...
The Standard library has no platform independent way to detect if a locale is UTF-8. There's only a name method which returns a platform dependent name. Even if it is a POSIX name there's no guarantee that the encoding is part of the locale's name. Boost.Locale offers an additional facet called boost::locale::info hold...
65,061,300
65,061,532
How not to print zeros at the beginning of the binary representation of a usigned short int?
I have a code like this that converts a short integer to binary, but zeros are printed at the beginning. So here's how to make sure that these zeros are not displayed, and the output starts from the first one? At the same time, using standard language operators and bitwise operations. int main() { unsigned short in...
With recursion, you might do: void print_binary(unsigned int n) { if (n >> 1 != 0) print_binary(n >> 1); std::cout << (n & 1); } Demo
65,061,873
65,062,340
Sorting a QString list by numbers C++
I'm using Qt and I created a ranking scene which contains all the players list with their score, so I have a QList<QString> list, every QString contains a name and a score, separated by a space like this Mario 50. Now the problem is: how can I sort the list by the lowest score?
You can use std::sort() with a lambda like this std::sort(str_list.begin(), str_list.end(), [](const QString &lhs, const QString &rhs) { int num_lhs = lhs.split(' ').last().toInt(); int num_rhs = rhs.split(' ').last().toInt(); return num_lhs < num_rhs; });
65,061,918
65,817,449
Read 'Extended' file properties (C++)
Is there a way to get all the properties and values of any file under the details tab using only c++ Code? All extended file properties: link I have seen solutions for c# but not c++. link I have already looked into the fileapi.h function GetFileAttributesA() which gave me access to the file attribute constants like F...
Here is some sample code from Microsoft for reading/writing file properties. It's using the WinAPI to read the file properties. You can find a list of available properties here. Depending on what you want to do, you may also take a look at these PROPVARIANT functions. For example, when you want to store the value of a ...
65,062,227
65,062,639
Why is my brute force substring search returning extra counts?
Doing some work with timing different algorithms, however my brute force implementation which I have found numerous times on different sites is sometimes returning more results than, say, Notepad++ search or VSCode search. Not sure what I am doing wrong. The program opens a txt file with a DNA strand string of length 1...
The difference might be because your algorithm also counts overlapping results, while a quick check with Notepad++ shows that it does not. Example: Let dna be "FooFooFooFoo" And your pattern "FooFoo" What result do you expect? Notepad++ shows 2 (one starts at position 1, the second at position 7 (after the first). Your...
65,062,305
65,064,888
Setting pixel color of 8-bit grayscale image using pointer
I have this code: QImage grayImage = image.convertToFormat(QImage::Format_Grayscale8); int size = grayImage.width() * grayImage.height(); QRgb *data = new QRgb[size]; memmove(data, grayImage.constBits(), size * sizeof(QRgb)); QRgb *ptr = data; QRgb *end = ptr + size; for (; ptr < end; ++ptr) { int gray = qGray(*pt...
First of all you are copying too much data in this line: memmove(data, grayImage.constBits(), size * sizeof(QRgb)); The size ob Qrgb is 4 bytes, but according to the documentation, the size of a Format_Grayscale8 pixel is only 8 bits or 1 byte. If you remove sizeof(QRgb) you should be copying the correct amount of byt...
65,062,368
65,062,662
How to find a char in a map
I need to create a dictionary using map .I need to create a function that display every word that start with a specific char. I create that function(start_with()) and it works ,but I want to ask if I can make it using find() and to find and display only the words that start with that char. class Dictionary { std::m...
std::for_each from <algorithm> is the solution: std::map<std::string, std::string> map {{"a","a"}, {"b", "b"}, {"c", "b"}}; char ch = 'b'; std::for_each (map.begin(), map.end(), [ch](auto e) { if (e.first[0] == ch) std::cout << e.first << " " ...
65,062,552
65,070,649
Eigen Matrix-Vector multiplication w/ noalias
I've been going through the Eigen documentation for using noalias to avoid unnecessary temporary allocations when doing Matrix-Matrix products, but I was wondering if it's possible to use noalias in the following situation: Eigen::VectorXf x(3); x << 1, 2, 3; Eigen::MatrixXf A(3, 3); A << 1, 2, 3, 4, 5, 6, 7, 8, 9; ...
After testing with Clang trunk and Eigen trunk, with optimizations turned on, the case with noalias produces incorrect results. GCC trunk has the same behaviour. The outputs: Program returned: 0 .noalias 0 0 0 alias 14 32 50 Code: #include <iostream> #include <Eigen/Dense> auto no_alias() -> Eigen::VectorXf { Ei...
65,062,636
65,062,697
Why do C++ bit fields require me to specify a type?
Why do I have to specify a type for a bit field? struct MyBitField { unsigned int i : 4; } struct MyBitField2 { unsigned char i : 4; } What's the difference between those two? Why do I need to specify a type at all?
Bitfields are an "overlay" around normal members, and every member has a type. Recall that integer types in C++ are largely inherited from types in C, which were designed to map neatly to whatever primitives exist on the target architecture. This is a convenient feature to have. Bitfields sit on top of that logic; they...
65,062,642
65,065,295
Boost::GIL: reading *.png image with alpha channel is missing antialiasing
I'm using boost 1.74. So, without exception catches and rest stuff my actual code looks like: typedef std::vector<int32_t> FlatINT32TArr; using PreviewImageT = bg::rgba8_image_t; using PreviewViewT = bg::rgba8_view_t; using PreviewPixelT = bg::rgba8_pixel_t; void read_pixel_arr(FlatINT32TArr r_preview_flat_arr, const...
There seems to be something wrong after the conversion shown. When I save the preview data as PNG: bg::write_view("output.png", preview_view, bg::png_tag{}); I get the expected output: That's the preview buffer (buff1) precisely as you copy it in the flat int32 vector. Note also the return parameter was passed by ...
65,062,713
65,062,888
Why is .push_back(x) faster than .push_back(std::move(x))
I have a large .txt file that I need to load and store in a vector. The file is around 5MB in size, 500 000 lines, and every line is around 10-20 characters, delimited with '\n'. I was doing some benchmarking on the time needed to read the whole file using a sample code below: #include<iostream> #include<vector> #inclu...
If you invoke g++ -E you can ogle the relevant code: Copy construction: basic_string(const basic_string& __str) : _M_dataplus(_M_local_data(), _Alloc_traits::_S_select_on_copy(__str._M_get_allocator())) { _M_construct(__str._M_data(), __str._M_data() + __str.length()); } Move construc...
65,063,117
65,064,330
Hash table - adding a rehash to resize method
I'm doing hash table with chaining and can't figure out how should I rehash whole table while resizing. I was thinking about inserting all elements with new hashcode in resize method, but I have no idea how to... Could you give me a hint or something? Here is rehash (I mean resize, without rehashing yet) method: void r...
When you increase the size of your hash table, the associated buckets may change for some keys. Your code just copies the lists from the front part, which means that some values can no longer be found in the table. (For example a key with hash code 13 will have the index 1 in a table of size 4, but the index will chang...
65,063,622
65,064,425
boost::variant apply static_visitor to certain types
I have the following variant: typedef boost::variant<int, float, bool> TypeVariant; And I want to create a visitor to convert a int or float type to a bool type. struct ConvertToBool : public boost::static_visitor<TypeVariant> { TypeVariant operator()(int a) const { return (bool)a; } TypeVariant...
Just include the missing overload: Live On Coliru #include <boost/variant.hpp> #include <iostream> using TypeVariant = boost::variant<int, float, bool>; struct ConvertToBool { using result_type = TypeVariant; TypeVariant operator()(TypeVariant const& v) const { return boost::apply_visitor(*this, v); ...
65,064,303
65,065,738
Trying to subtract a std::chrono::duration from a time_point (C++), but my code isn't compiling. Any suggestions?
I asked this question yesterday, but my thread got shut down, so I'm talking into the void. So, my code is not compiling, but I would very much like it to. Here's is my snippet: float numSeconds = 50; std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now(); auto duration = std::chrono::durati...
float numSeconds = 50; The following line: std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now(); could be more concisely written as: auto startTime = std::chrono::steady_clock::now(); Both syntaxes are equivalent and correct. The reason this doesn't compile: auto duration = std::chrono:...
65,064,347
65,064,524
How to make a switch statement with a vector string?
vector<string> cmdV = split(_cmd, " "); switch (cmdV[0]) { } For some reason it gives me the error: "The value must have an integral or enum type" in cmdV[0]
If you really want to make a switch statement with values from a vector<string> you can use either atoi() or std::stoi(). More described in this answer: How can I convert a std::string to int?. The following code should work: #include <iostream> #include <vector> #include <string> int main() { std::vector<std::st...
65,064,642
65,065,990
Inputting data to stringstream with hexadecimal representation
I am attempting to extract a hash-digest in hexadecimal via a stringstream, but I cannot get it to work when iterating over data. Using std::hex I can do this easily with normal integer literals, like this: #include <sstream> #include <iostream> std::stringstream my_stream; my_stream << std::hex; my_stream << 100; s...
First, the std::hex format modifier applies to integers, not to characters. Since you are trying to print unsigned char, the format modifier is not applied. You can fix this by casting to int instead. In your first example, it works because the literal 100 is interpreted as an integer. If you replace 100 with e.g. stat...
65,064,900
65,064,984
Is there any reason to use extern for constants anymore?
In my earlier days I often had constructs like: // .h extern const int MY_CONST; // .cpp const int MY_CONST = 5; Is it true that this is completely superseded by: // .h inline const int MY_CONST = 5; Is there any reason to use the first variant nowadays? Note that the latter has higher readability because the value ...
Certainly. For the same reasons as one might want to define anything in separate translation unit. Same reasoning applies to function definitions for example. For example, a reason may be to remove the need to recompile everything depending on the variable in case you want to change the initialiser. Another reason may ...
65,065,063
65,071,747
Extending lifetime of Boost log core
I want to extend lifetime of the boost::log::core for termination process. I know that this is not recommended in the documentation. But I tried to use Schwarz counter for core to keep it until last destructor of global variable used it. Core uses the shared pointer with Meyer's singleton. is it possible to implement S...
The core::get() method returns a shared_ptr to the core, which is what implements the Schwarz counter. You can call this method during the normal operation of the program (i.e. while main() is executing) and save that pointer in your data structures that are guaranteed to be present during termination. While the shared...
65,065,142
65,065,253
remove element of struct from vector of struct with erase-remove-idiom
I have a vector of structs and I want to remove an element from the vector with specific values.I know how it can be done for for example a vector of int values using erase remove, but now sure how to do it for a vector of structs: #include <algorithm> #include <string> #include <iostream> using namespace std; struct...
As the error message says, the compiler doesn't know how to compare two file_line objects. You can provide this comparison yourself by writing: bool operator==(file_line const & a,file_line const & b) { return a.pcounter == b.pcounter and a.optype == b.optype; } Here's a demo.
65,065,612
65,065,791
How to assign object's parents to QObjectList?
I can use this code for the assign children. QObjectList boxes = this->children(); But i can't use this code. QObjectList boxes = ui->checkBox_2->parent(); How can i obtain parents?
There is no default method to get parents so you have to iterate using the parent() method: QObjectList parents(QObject *qobject){ if(!qobject) return {}; QObjectList parents; const QObject *o = qobject; while (QObject *q = o->parent()) { parents.push_back(q); o = q; } re...
65,065,645
65,065,716
How does conversion from string to char array work in C++?
I just started learning C++ and I was trying to output a string through printf. It wouldn't work because I had to convert the string into a char array first. I googled it and it seems that the best solution was this: char *a = &b[0]; I somewhat understand it: It's getting a reference to the first character and setting...
The thing to note is that operator[] returns a reference. cppreference: reference operator[]( size_type pos ); Returns a reference to the character at specified location pos. This is important because it means that b[0] is essentially an alias to the first character in the string. Taking its address will then give yo...
65,065,729
65,079,804
Is there a way to test nontype templates using Boost Test?
I am using Boost Unit Test to perform unit test for my project. I need to test some non-type templates, however seems that using the macro BOOST_AUTO_TEST_CASE_TEMPLATE(test_case_name, formal_type_parameter_name, collection_of_types) I can test only typed templates. I want to use a collection_of_types not composed by {...
You can always wrap static constants in a type. For integral types there is std::integral_constant or indeed the Boost MPL analog: Live On Coliru #define BOOST_TEST_MODULE sotest #define BOOST_TEST_MAIN #include <boost/mpl/list.hpp> #include <boost/test/included/unit_test.hpp> template <int> struct test_template {}; ...
65,066,025
65,066,086
Why do libraries create macro aliases for c++ keywords?
Often in large libraries I see code similar to the following: #define MY_CONSTEXPR constexpr #define MY_NOEXCEPT noexcept #define MY_NODISCARD [[nodiscard]] etc. What is the purpose/benefit to creating aliases for these keywords? I see this fairly commonly but couldn't find anything regarding the practice. If I had to...
What is the purpose/benefit to creating aliases for these keywords? I see this fairly commonly but couldn't find anything regarding the practice. If I had to guess, the reason is so you can conditionally compile whether you want these keywords present in your compilation. Yes, generally so. You may also see similar ...
65,066,060
65,066,074
fstream gives me wrong file size
I wrote simple function that read whole file into a buffer. #include <iostream> #include <fstream> int main() { std::ios_base::sync_with_stdio(0); std::ifstream t; t.open("C:\\Users\\sufal\\Desktop\\test.txt"); t.seekg(0, std::ios::end); long length = t.tellg(); t.seekg(0, std::io...
On Windows the newline character is "\r\n", which consists of two bytes. So, if your file does not end with a newline, 7 is indeed its size: 1 <-- 1 byte for '1', 2 bytes for CRLF 2 <-- 1 byte for '2', 2 bytes for CRLF 3 <-- 1 byte for '3' To read the file correctly on a byte level you need to open it in b...
65,066,582
65,066,634
Uninitialized local variable c4700
https://www.programiz.com/cpp-programming/structure-function I'm learning how to pass structures to functions using the website above, I spent 2 hours of trying to figure out what was wrong with my program, I decided to copy and paste the code on the website to see if they did it correctly and the same error came up. I...
If you just want to make the compiler happy and avoid the warning, initialize p before doing anything with it: Person p = {}; // zero's out all the members (default initializes) But the real issue is that you are passing an uninitialized instance of Person by value (a copy of p) into getData. The compiler wants to as...
65,066,608
65,066,682
I have a segmentation fault in c++, where did I go wrong?
Trying to traverse a 2d vector in order to find index(es) of a certain key value which is the number 1. I looked up what a segmentation fault was and it said that it happens when you try to access too much memory, but I don't get how I'm doing that. #include<iostream> #include<algorithm> #include <vector> #include <cma...
To fix the segfault, you have to change the declaration of your vector to vector<vector<int>> matrix(5, vector<int>(5)); Now it has enough capacity to store the elements. The first parameter is the number of elements that the vector supports initially, which is 5. The second parameter is the default object the vector ...
65,066,997
65,067,094
Calculating test grade averages without using arrays or min/max in C++
Could anyone give me some pointers of the use of functions here? The assignment is as follows: *> Write a program that calculates the average of a group of test scores, where the lowest score in the group is dropped. It should use the following functions: void getScore() should ask the user for a test score, store i...
What i'm failing to discover is how i can use a void function to pass data back to int main. One first step is to use a void function with reference: #include <iostream> void getScore(double& score) { score = 4.0; } int main() { double score = 0.; getScore(score); std::cout << score << std::endl; } ...
65,067,324
65,069,480
Writing QString to Excel produce extra Tab?
After working with my initial Data.CSV, I want to save it again as Data.CSV, while that works already amazingly well, it somehow writes in the wrong Column when I open it in Excel. Somehow wrongly written Data: That is how I write it to the File: QFile file(fileName); QString DataFullConvert; DataFullConvert = DataFul...
You should get rid of the semi-colons after the newline characters. When Excel sees the newline character, it assumes a new row starts, and then it sees the semi-colon, which creates the first empty column. DataFullConvert.replace(QString("\n;"), QString("\n"));
65,067,403
65,067,576
Concept not being recognised
I am using the following version of clang: Apple clang version 12.0.0 (clang-1200.0.32.27) Target: x86_64-apple-darwin20.1.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin I am getting this error with the following code: error: unknown type nam...
According to the cppreference compiler support page no version of Apple Clang supports concepts yet.
65,067,413
65,070,087
How to swap smart pointers when one is const
I have the following problem Buffer buffer1; Buffer buffer2; std::unique_ptr<const Buffer> hotBuffer; std::unique_ptr<Buffer> backBuffer; I want to fill the back buffer while the hot buffer is being read, and want the hot buffer to be un-writable and const for this reason, but at some point after it has been read and...
To swap, you need compatible const qualification because otherwise a pointer to const would need to be cast to a pointer to non-const. To get compatible const qualification, you have to create a temporary and cast as Igor's comment suggests. So... something like this: template<typename U, typename T> std::unique_ptr<U>...
65,067,467
65,067,533
What is the return type of address-of (&) operator?
int main(){ int i = 0; int *p = 123; return 0; } The error message is: invalid conversion from 'int' to 'int*' [-fpermissive] int *p = 123; I know int *p = &i; could make this work, but how the complier convert the &i type to int * type (what return type of & is)? Thanks for anyone explaining this to me!
From the reference: For an expression of the form & expr If the operand is an lvalue expression of some object or function type T, operator& creates and returns a prvalue of type T*, with the same cv qualification, that is pointing to the object or function designated by the operand. So, the type of the expression &i...
65,069,043
65,070,162
Is there a template way of storing and retrieving interfaces in a container?
If we want to implement the the command pattern in C++ we normally have something like this - struct Command { virtual void execute() = 0; virtual ~Command() {} }; struct Invoker { void enq(std::unique_ptr<Command> command) { commands_.push_back(std::move(command)); } void invoke_all() { for (con...
If you want to store different type in your container, you need interface or type-erasure. The call to execute would call then virtual method or equivalent. So you can indeed not require that class provided from user inherit from Command as long it satisfies some interface: With std::function template<class T> concept ...
65,069,895
65,069,957
How to delete singleton instance from separate module before system killed running threads
I have a C++ Windows (compiled with Visual Studio 2019) program that uses shared libraries. A shared library uses a singleton on a class that creates a thread. The class destructor kills the thread cleanly, so there should be no memory leak. However, I see that the destructor is being invoked after the system actually ...
No. Multithreading, automatic cleanup, and DLL unloading are basically a huge mess on Windows once they interact. The solution is to not have singletons, or any static lifetime variables (globals, local statics, class statics) with non-trivial destruction semantics. Make an instance of your thing in main()/WinMain(). P...
65,070,036
65,070,266
How to write optimized constructor in a class >
I wrote writing an email class, but I am not sure if this is the best way to write this... here's the code for it... class email { string value; string domain; string com; string username; string encrypted; bool state ; public: email(const string& val) :value{ val}, state{false},com(...
You could break the for loops, if you have done your stuff. First for: after you found '@' you do not have to loop to the end Third for: after you found an error, you could throw immediatelly
65,070,155
65,157,924
why my code is not working for input greater than 12?
There is no problem when I input a number smaller than 12 but when I input something bigger the code returns with no output without any error. What's the problem? Sample output I am getting - Sample 1 - 1 13 Press any key to continue.... Sample 2 - 1 12 27720 Press any key to continue.... Sample 3 - 1 10 2520 Press ...
What was going wrong - The data was growing so quickly because of recursion, that it was overflowing the stack. What I did - Found a better algorithm that's not using recursion - #include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ long n; ...
65,070,355
65,078,857
Set custom EntryPoint for a simple application
I have this simple hello world c++ application: #include <windows.h> #include <iostream> using namespace std; void test() { cout << "Hello world" << endl; } I want to use test as my custom entry point. So far I tried to set Linker -> Advanced -> Entrypoint to test But I got lots of lnk2001 errors. Is it possible...
Using a custom entry point in a Windows app bypasses the entire CRT startup and global C++ initializations. Because of that, it requires not using the CRT, and turning off compiler features that depend on the CRT such as /GS buffer checks and other /RTC run-time error checks. The following is an example of a minimal ap...
65,070,389
65,071,038
Wrong answer in Abbreviations problem using DP
Can someone explain what is wrong with my code? I am getting "Abort called" in 7 test cases. Rest are successful. I have a 2d dp array with of size: n+1 x m+1 were n and m are sizes of a and b respectively. So, the row represent string a and columns represent string b. First, I set dp[0][0] to 1 since it is possible to...
The error in the code is "Segmentation fault". Because of the following loop: for (int j = 1; j <= i; ++j) As the loop is iterating till i(which could be greater than m i.e. the size of b). That's the reason for the Segmentation fault. Now the following code passes all the test cases. #include <bits/stdc++.h> using na...
65,070,830
65,154,648
Cmake FindBoost error-POP without matching PUSH
I am trying to install LightGBM-gpu on Centos. It seems boost 1.56 can be find, but this error occurred.I google it all day but can not solve it. Here is the Message $ cmake -DUSE_GPU=1 -DOpenCL_LIBRARY=/usr/local/cuda/lib64/libOpenCL.so -DOpenCL_INCLUDE_DIR=/usr/local/cuda/include/ .. -- The C compiler identification ...
This question was cross-posted to the LightGBM issues page as microsoft/LightGBM#3613. The issue was solved there. Updating CMake to at least version 3.14 fixes this issue.
65,070,998
65,071,341
Convert int vector to float vector C++
I tried the C cast style as shown below but to no avail #include <iostream> #include <vector> using namespace std; int main() { std::vector<int> intVec = { 1, 2, 3 }; std::vector<float> floatVec; for (int i = 0; i < intVec.size(); i++) { float new_num = (float)intVec[i]; floatVec.push_...
Use std::fixed with cout, like this: #include <iostream> #include <vector> using namespace std; int main() { std::vector<int> intVec = { 1, 2, 3 }; std::vector<float> floatVec; for (int i = 0; i < intVec.size(); i++) { float new_num = (float)intVec[i]; floatVec.push_back(new_num); ...
65,071,233
65,071,465
How do I return another object with operator overloading?
I have a class that contains an array data. I need to write an overloaded operator that returns an object of the class with the addition of two class arrays. For example: Container x({1,2,3}) + y({1,2,3}). I tried the following and numerically it works, but it doesn't return a new object. I also included the constructo...
What you implemented modifies this and then returns a reference to it. Thats an operator+= with a misleading name. If you expect your code to create another instance and return that you need to go some steps back and read about basics such as references. Fortunately, once you have a operator+= and a copy constructor, u...
65,071,836
65,072,433
Template argument deduction for implicit pair
Consider the following code: #include <utility> #include <initializer_list> template <typename T> struct S { S(std::initializer_list<std::pair<T, int>>) {}; }; int main() { S s1 {{42, 42}}; // failed due to implicit `std::pair` from `{42, 42}` S s2 {std::pair{42, 42}}; // ok } s1 instance failed...
Sadly no. The reason is that template arguments cannot be deduced through nested braces (std::initializer_list) because they occur in non-deduced context. See the link for more examples of this behaviour. To not drag CTAD into this, your example is equivalent to: #include <utility> #include <initializer_list> template...
65,071,961
65,073,877
OpenMP for loop with specific threads
I'm new in parallel programming. I'm trying to make point cloud processing process parallel. I share with my program structure below. Firstly, I separate the point cloud into the partial clouds. My aim is that every thread must call the fillFrustumCloud() function separately. int num_threads = 12; std::vector<CloudCol...
This #pragma omp parallel constructor will create a parallel region, with as many threads as you have set it up. Hence, when you do: #pragma omp parallel { for(int i=0; i<num_threads; i++) { ... } } every thread in the parallel region will execute all the iterations of the loop. That is why you hav...
65,073,159
65,073,212
How do I fix the Werror=parentheses (suggest parentheses around assignment) error?
I have a line of code which does both assignment and condition. I could split it into two lines but I'm just curious about the error message thrown. if ( parameters->__size = m_Elements.size() ) Got this error: suggest parentheses around assignment used as truth value [-Werror=parentheses] I tried: if ( (paramet...
To convince the compiler that the assignment is really what you want, you need to enclose the whole expression in parentheses, like this: if ( ( parameters->__size = m_Elements.size() ) ) //... Without this, the compiler thinks that you may have made a mistake, using assignment (=) instead of the comparison (...
65,073,276
65,074,770
Do the multiple postfix-expression(subscripting) evaluations result in UB
#include <iostream> int main(){ int arr[7] = {0,1,2,3,4,3,2}; arr[0]++[arr]++[arr]++[arr]++[arr]++[arr]++[arr] = 5; //#1 for(auto i = 0;i<7;i++){ std::cout<<i<<" : "<< arr[i]<<std::endl; } } Consider the above code, Is this evaluation at #1 would result in UB? This is a example I have saw in twitt...
I believe your understanding is fine and the code is fine in C++ from C++17. Is there anything I misunderstand? No. Whether the code is UB or not? No. If it's not UB, what's the result? arr[0]++[arr]++[arr]++[arr]++[arr]++[arr]++[arr] = 5; Side effect: arr[0] := 0 + 1 = 1 0[arr]++[arr]++[arr]++[arr]++[arr...
65,073,494
65,073,614
Is the size of an std::string always the number of printed characters?
I'm trying to understand what std::string::size() returns. According to https://en.cppreference.com/w/cpp/string/basic_string/size it's the "number of CharT elements in the string", but I'm not sure how that relates to the number of printed characters, especially if string termination characters are involved somehow. T...
In the case of str1 ... the behavior is undefined if this character is modified to any value other than CharT(), so I assume I've walked into undefined behavior here. Your assumption is wrong. There is no UB for two reasons: You did assign the element to '\0' which happens to be same as CharT() and thus it would be...
65,073,996
65,074,109
Differrent function signatures C++
Found some C++ tests, one of a questions: what is diff between function signatures. Am I right with following answers? void f(data); // 1)calls copy constructor of data to pass in function void f(data*); // 2)data passes to function by ptr, no copy constructor called void f(data const*); // 3)same as 2, but not allowed...
Not quite: Not necessarily copy. Other constructors can be used to initialise the parameter. and 4. are wrong way 'round. There is no such thing as "reference to a reference". That is an rvalue reference. No constructor is called when binding a reference to a value.