question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
74,256,801
74,259,525
C++ How do I get the next node to appear before the previous in a double linked list?
For example, my text file reads: A 1 A 3 B A 2 The goal is for the output to be 123, but I have gotten everything but that. #include <iostream> #include <string> #include <fstream> using namespace std; class Node { public: char letter; Node* next; Node* prev; Node(char cc) { letter = cc; ...
For the lack of implementation details in 'B', I'll just help you fix 'A' instead. You see, when moving the cursor back, you are now pointing to an element that already has a 'following node' (next is no longer nullptr) else if (command == "A") // Add char Done { input >> parameter; No...
74,257,055
74,257,072
Unable to delete instance variable array in C++
I am implementing a string class in C++, and I have come across an issue when trying to delete the char[] that contains the data of the string: class String { public: String(); String(char str[], int size); ~String(); void clear(); private: char *data; int size; }...
You are trying to apply the operator delete to this array with automatic storage duration char temp[] = {'a','b','c','d'}; due to the constructor String::String(char str[], int _size) { data = str; size = _size; } that just copies the address of the first element of the array in the data member data. You need...
74,257,106
74,257,269
C++ Calling a function inside a function
I try to call a function in secim() because I want to shorten this function, but it gives a c3861 error. I try a lot of things, but every time it gives a different error. I thought it would be best to share the function without splitting it, because I don't know which way is true. I am new to programming, I think it's ...
The compilator reads your code from top to bottom and will complain if it sees a function that isn't defined. For example: void foo() { bar(); // Error: What is bar()? Not declared yet. } void bar() { foo(); // OK: foo was declared and defined above. } The solution is to declare the function causing th...
74,257,345
74,313,643
Which SYCL buffer constructors cause host write back on destruction?
SYCL buffers have the fun effect where when they are destroyed they may write back into the host memory from which they were formed. This is specified in 3.9.8.1 of the sycl 2020 standard: Buffer destruction: The destructors for sycl::buffer, sycl::unsampled_image and sycl::sampled_image objects wait for all submitted...
Buffers are containers for data that can be read/written by both kernel and host. The destructor for a buffer can optionally write the data back to host memory, either by pointer or iterator. We can control the write-back of data using set_final_data() and set_write_back(). All the below buffer constructors can be used...
74,257,533
74,257,596
Difference between std::decay and std::remove_cvref?
Does std::remove_cvref replace std::decay after C++20? From this link, I cannot understand what this means: C++20 will have a new trait std::remove_cvref that doesn't have undesirable effect of std::decay on arrays What is the undesirable effect of std::decay? Example and explanation, please!
std::remove_cvref does not replace std::decay. They are used for two different things. An array naturally decays into a pointer to its first element. std::decay will decay an array type to a pointer type. So, for example, std::decay<const char[N]>::type is const char*. Whereas std::remove_cvref removes const, volatile ...
74,257,626
74,257,769
how do i display a grid of images (and have them them transparent until a keyboard key is pressed)
any language. im wanting to make a program that will show what ability's im using in a game and have the picture of the ability's in a grid like ortholinear keyboard keys. it would be cool if the abilitys where tansparent untill the key is pressed then go opaque until i let go. iv been trying to find out how to do it w...
I suggest you give this link a read: Monitor keypress in tkinter without focus You can refer to the answer that is not accepted, it shows how to accept key even if the program is not focus on. My suggestion is that, you create a "ability layout" in tkinter, then you assign the key of the ability layout to the actual ke...
74,258,394
74,258,971
How to install and call c++ library from folder other than /usr/local/include/
I have git cloned the package https://github.com/alex-mcdaniel/RX-DMFIT to a computing cluster directory. It requires the GNU computing library which I downloaded from https://www.gnu.org/software/gsl/ . The issue is make install gives cannot create directory '/usr/local/include/gsl': Permission denied as I don't hav...
This question contains two parts: How to install Gsl to a custom directory, and also how to modify the Makefile of RX-DMFIT to use Gsl from the custom directory. Install Gsl to a custom prefix To install Gsl into a custom directory, configure it to use a custom prefix before running make and make install. # Create a di...
74,258,595
74,261,478
Fixing vector issue - Finding middle element of vector - C++
I'm trying to code an efficient method to which : The maximum number of list values for any test case should not exceed 9. If exceeded, output "Too many numbers". I have the solution down for finding the middle number in a vector, but can't figure out a way to detect if the values received are more than 9. Obviously th...
I tried to reimplement your code so it will work as you want. Ask me if you feel that this code doesn't seems right to you. #include <iostream> #include <vector> using namespace std; int main() { vector<int> nums(10); int value=0; int numberOfElements=0; bool moreThanNine=false; while(cin>>value) ...
74,258,955
74,259,760
How to check if a particular overloaded function exists, using the decltype or declval
I wrote the following code, here as msg_hdr() function has 2 overloads, which makes decltype unusable. Instead of decltype, I have also tried invoke_result_t as well as result_of_t, but nothing seems to work. What changes should I make in the code to make it work. struct Header { int i; int j; }; struct Data {...
We can use this trick to detect particular overload function. template <typename T, typename... Args> class has_msg_hdr { template <typename C, typename = decltype( std::declval<C>().msg_hdr(std::declval<Args>()...) )> static std::true_type test(int); template <typename C> static std::fals...
74,260,053
74,260,139
Call a class's function template with function pointers as parameters
I'd want to use a function pointer in my template argument list. I do miss something of B even I am writing int in full main of both A and B. I have a class X.h like so, don't know which one it is now causing the error. struct X { int fun(int a) { return a; } template<typename A, typename B> ...
The problem is that the argument &X::fun is of type int (X::*)(int) while the parameter f is of type int(*)(int) (when B = int) and there is no implicit conversion from the former to the latter and hence the error. To solve this you can change the parameter f to be of type B(X::*)(int) as shown below. Note that the syn...
74,260,112
74,260,337
Why does std::views::split() compile but not split with an unnamed string literal as a pattern?
When std::views::split() gets an unnamed string literal as a pattern, it will not split the string but works just fine with an unnamed character literal. #include <iomanip> #include <iostream> #include <ranges> #include <string> #include <string_view> int main(void) { using namespace std::literals; // returns...
String literals always end with a null-terminator, so ":.:" is actually a range with the last element of \0 and a size of 4. Since the original string does not contain such a pattern, it is not split. When dealing with C++20 ranges, I strongly recommend using string_view instead of raw string literals, which works well...
74,261,052
74,261,151
Consider Vector of Child Pointers as Vector of Base Pointers
Suppose there are the following classes: class A { }; class B: public A { }; and the vector of unique_ptr to B: std::vector<std::unique_ptr<B>> bElements Is there a possibility to pass the vector to a function that accepts std::vector<std::unique_ptr<A>>& as a parameter
No. A std::vector<Foo> has no special relation to a std::vector<Bar> no matter what is the relation between Foo and Bar. They are two distinct completely different types. The fact that they are instantiations of the same class template is not relevant when you are asking for an exact type of argument of the function. T...
74,262,068
74,262,135
couldnt connect to active directory on windows 2019 server
I am working on active directory and was reading this https://learn.microsoft.com/en-us/windows/win32/adsi/setting-up-c---for-adsi-development and just used the mentioned code to connect to it but its not connecting to the server and says proccess exited with status code zero i used the below code. #include "stdafx.h" ...
ADsGetObject is for non authenticated connection that is the code should be performed inside the server. if you are trying to connect to a server hosted on seperate machine you should be using ADsOpenObject you may have the reference in the following link https://learn.microsoft.com/en-us/windows/win32/api/adshlp/nf-ad...
74,262,125
74,262,401
Difference between template argument deduction for classes and functions
What the problem is: I'm trying to implement a class that will have two specializations, one for integral types and one for all others. The first version that came to my mind: #include <type_traits> template<typename T, typename std::enable_if_t<std::is_integral<T>::value, bool> = true> class Test { }; template<typena...
Using std::enable_if in the template parameter list of a class is not guaranteed, since the standard only has SFINAE for functions, not for types. For types it may be available, but only as a non-standard compiler extension. C++20 adds concepts to the standard, which does work for template parameters on template classe...
74,262,202
74,289,802
How to add C++ QQuickPaintedItem in QML
I want to add C++ class like this notchedrectangle.hpp to QML: #ifndef NOTCHEDRECTANGLE_HPP #define NOTCHEDRECTANGLE_HPP #include <QtQml/qqmlregistration.h> #include <QQuickPaintedItem> class NotchedRectangle : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorC...
QML_IMPORT_NAME is not a name of class! It's the name of package and must be different. I use "Custom". Next you must include class in main.cpp And finally - you should make Recompile
74,262,609
74,263,152
Pass integer argument to slot function for QPushButton
I'm trying to pass an integer argument to a function using the connect() method in QtCreator. I'm creating a game where the user will be able to select one of three game setting options. They can click either button 1, button 2, or button 3, and an integer (1, 2, or 3) corresponding to the setting they picked should be...
First things first, why do you use the old SIGNAL and SLOT macros when you seem to already be aware of the new signal/slot syntax ? There is no such mapped() signal in QSignalMapper class (so obviously, it cannot work). Maybe QSignalMapper::mappedInt() is what you wanted ? If you used the proper signal/slot connection ...
74,263,199
74,263,521
Issue on using multiple structures by pointers cause crash on program executing
Hello I noticed this weird issue when using multiple pointer structures at the same time. Can somebody explain to me what is causing it ? #include <iostream> using namespace std; typedef struct A{ int x; }a; int main() { a *a1, *a2; a1->x = 3; cout << a1->x << endl; // display "3" a2->x = 2;...
Before assigning the values to your pointers, the pointers have to be initialized properly. a *a1, *a2; These pointers are not initialized. They point to some random location in memory. The "new" keyword allocates memory for your structure. You can use it like this: a *a1 = new A, *a2 = new A;
74,263,291
74,265,943
How to mesh a 2D point cloud in C++
I have a set of 2D points of a known density I want to mesh by taking the holes in account. Basically, given the following input: I want something link this: I tried PCL ConcaveHull, but it doens't handle the holes and splitted mesh very well. I looked at CGAL Alpha shapes, which seems to go in the right direction (...
The resulting triangulated polygon is about a two step process at the least. First you need to triangulate your 2D points (using something like a Delaunay2D algorithm). There you can set the maximum length for the triangles and get the the desired shape. Then you can decimate the point cloud and re-triangulate. Another...
74,263,416
74,263,681
Question about `has_const_iterator`/`has_begin_end`
The following code comes from cxx-prettyprint , which implements detecting whether type T has a corresponding member #include<iostream> #include<vector> #include<type_traits> using namespace std; struct sfinae_base { using yes = char; using no = yes[2]; }; template <typename T> struct has_const_iterator : private...
If you force a call the overload of has_const_iterator::test that returns true (by removing the other): #include <utility> #include <vector> #include <iostream> template <typename T> struct has_const_iterator { private: template <typename U> static constexpr decltype(std::declval<U::const_iterator>(), bool()) test...
74,263,795
74,273,834
Speed problems with realtime recording with libavcodec and libavformat
I am trying to use libavcodec and libavformat to write an mp4 video file in realtime using h264. I am using an approach heavily inspired by this answer here This works well as a non-realtime solution however, avcodec_receive_packet() starts running much slower after 20 frames or so (this is usually around the first tim...
I have solved this by not using h.264 encoding and instead using libavcodec's mpeg2video encoder. This leads to a much larger file size however the frame by frame encoding has a much more consistent processing time. Thanks to @G.M.'s comment for that. I have not yet tested any other encoders so possibly those could be ...
74,263,931
74,264,142
Why is there a difference between templated recursive calls and fold expressions with type cast or promotion?
#include <array> #include <type_traits> #include <iostream> template<class... Types> class Test { public: Test() : format_({ [&] { if constexpr(std::is_same_v<Types, int64_t>) { return "%ld "; } else if constexpr(std::is_same_v<Types, int32_t>) { return "%d "; } else if c...
You print double as an integer in the recursive call. That's a UB or some other nonsense. In the fold version you convert them to the appropriate types first.
74,263,987
74,264,156
Wrong cost adjacency matrix
I try to obtain the adjacency matrix of weights, and then use it in the calculation of the minimum weight path. There is a problem, when I try to display it, I get a wrong result : By logic, the diagonal must have only 0, and in the places where the vertices are adjacent, must be the weight of the edge //set the sourc...
for (i = 0; i < numberOfVertices; i++) { adjacency_matrix[i][i] = 0; for (j = i + 1; j < numberOfVertices; j++) { adjacency_matrix[i][j] = g->edge[i]->weight; adjacency_matrix[j][i] = g->edge[i]->weight; } } In this code you are setting every ed...
74,264,154
74,264,211
Does value-initialization use the implicit default constructor?
According to this site /link/: If the default constructor is explicitly declared but marked as deleted, empty brace initialization can't be used: and it also gives an example to this: class class_f { public: class_f() = delete; class_f(string x): m_string { x } {} // if it is deleted, there will be no errors....
There is a difference between the C++ 17 Standard and the C++ 20 Standard according to the definition of aggregates. According to the C++ 17 Standard this declaration class class_f { public: class_f() = delete; std::string m_string; }; declares an aggregate that you may initialize using braces. From the C++ 17...
74,264,539
74,265,249
Remove repeated code in function definition
this is my first question, so I may miss the "correct structure". Anyway, I have a header file, with a function. This function (void readFile()) is defined in a cpp file. Within this definition I have code which repeats itself a lot. If it was in main, I would simply declare a new function, define the repeatable in it,...
I don't know if this will exactly answer your question. If not, please post your entire code, especially the readFile function. Let's say you want a readFile function to: parse an input stream, and fill the fields ID (string) and price (float) of a list of object structs, the values in the stream being separated by a ...
74,264,990
74,265,056
Getting odd number between two number
The rule is I need to display the odd number between two number that the user inputted. But my code have problem. For example when i input: 3 and 11 The output is 5 7 9 11 11 should not be included because that's what the user input even it is odd number. The rule is between. 5 7 9 is my target. i'm thinking if it's be...
Your second attempt works if increment numOne before you start. numOne++; while (numOne < numTwo) { if (numOne % 2 == 1 || numOne % 2 == -1) { cout << numOne << " "; } numOne++; } But, you may wish to use a for loop. for (int i = numOne + 1; i < numTwo; i++) { if (i % 2 == 0) continue; ...
74,265,064
74,265,332
How to convert a std::string to const char* or char* at compile-time
Why yet another question on string to hash conversion My question is basically the same as the popular How to convert a std::string to const char* or char* question, but with a twist. I need the hash at compile time. Before rejecting my question, let me briefly explain my motivation. Motivation In my framework I am bui...
In C++17 a string_view can be constexpr so you can make your own hash function that takes one of those e.g. the hash function from someone's answer here would be like the following. #include <string_view> #include <iostream> constexpr size_t some_hash(std::string_view sv) { size_t hash = 5381; for (auto c : s...
74,265,827
74,266,125
Is there a significant performance gap bewteen native VulkanSDK and its C++ binding?
Recently I'm trying to learn vulkan, and I found that although nearly every tutorial or book I found teaches vulkan with C++, the API style of it is more C than C++. Naturally, I looked for its official C++ API, and that raised my question: Is there a significant performance gap bewteen native VulkanSDK and its C++ bin...
No C and C++ compilers and linkers are both well optimized at this point of life. Generally speaking - performance of code is the result of the whole programming process - from the initial design, to the programmer that codes, to the last step in the CI for deployment. So in general - are C bindings faster than C++? No...
74,266,694
74,267,203
Why operator= and copy constructor are treated differently in virtual inheritance?
It seems that in virtual inheritance, operator= and copy constructor are treated differently. Consider the following code: #include <iostream> #include <ostream> class A { public: A(int x) : x(x) { std::cout << "A is initialized" << std::endl; } A(const A& rhs) { std::cout << "Copy constru...
you're using compiler generated operator= (i.e C::operator=(const C&)), which calls operator= for all it's direct base class (and members) since A is not a direct base class of C, A::operator=(const A&) is not called. B is expected to copy A if it want, unlike constructor, you can implement assignment for B that doesn'...
74,266,896
74,267,153
Erasing multiple items from std::vector
I'm thinking about some different ways of erasing several pointers of a std::vector of pointers. I know that de erase/remove_if idiom is a good suit, but I'm thinking about a situation in which I have a container of pointers to remove from the std::vector that I have, something like this: std::vector<Object*> elementsT...
If you can sort both vectors then you need only a single pass through both for remove_if (erase is linear as well): #include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> X{1,2,3,4,5,6,7,8,9}; std::vector<int> remove{1,3,6,7}; auto first = remove.begin(); auto it =...
74,267,323
74,267,471
C++ Creating a unique pointer results in error "allocating an object of abstract class type" and "no matching constructor for initialization"
Edit: Turns out, in my Sunflower implementation, I named the function grow() instead of growImpl() so the compiler didn't find the implementation and was considering Sunflower as abstract. This question can be closed. I am trying to dynamically create an object of a class which inherits from an interface. I am trying t...
std::make_unique<T>() creates an instance of T, which means T can't be an abstract type. So, inside of Sunflower::spread(), calling std::make_unique<Flower>(...); will not work when Flower is an abstract type. You MUST instantiate a derived class instead in that case, eg return std::make_unique<Sunflower>(...); spread...
74,267,728
74,268,247
c++ 20 concepts in derived template class
for my test about CRTP I created this base class: template<typename Derived> struct Base { void print() const { std::cout << "print\n"; } }; And this class: struct A: public Base<A> { void printSub() { std::cout << "printSub from A\n"; } }; And I can use these classes without problem: A a1{}; a1.print(); a1.p...
You cannot meaningfully constrain the derived class template parameters of a CRTP base class for the same reason that you can't do this: template<typename Derived> class Base { using alias = Derived::SomeAlias; }; Derived isn't complete yet, and using a constraint usually requires completeness.
74,267,934
74,268,516
How to have inherited functions use local variables
I want to apply the functions from one class to the private variables from another derived class. I was hoping that this way I could avoid redefining the exact same function multiple times. I've added an example below. #include <iostream> class A { public: void print1(); void print2(); private: int array[3...
There are two solutions, related to design patterns called "Non-virtual interface" or "Template methods". Without virtual methods: add a member which will point to the private array: class A { public: A() : array(_array) {} void print1(); void print2(); protected: A(int array[3]) : array(array) {} ...
74,267,964
74,268,009
C++ Trying to pass arrays to functions
I am trying to make this code work on Visual Studio 2022, but it tells me that after the second void printArray(int theArray\[\], int sizeOfArray) it expected a ;. I am doing this code based on https://youtu.be/VnZbghMhfOY. How can I fix this? Here is the code I have: #include <iostream> using namespace std; void prin...
You should take the implementation of the function "printArray" out of the main. #include <iostream> using namespace std; void printArray(int theArray[], int sizeOfArray); int main() { int bucky[3] = {20, 54, 675}; int jessica[6] = {54, 24, 7, 8, 9, 99}; printArray(bucky, 3); return 0; } void printA...
74,268,106
74,269,451
File that requires elevated privileges
I want to create a file that is: Read-only accessible for all local users. Read-write accessible only when application runs with elevated privileges. I have found Windows-classic-samples here. I modified it a bit, so it gives the creator full access and everyone else GENERIC_READ: #include <Accctrl.h> #include <Aclap...
As @RbMm and @RaymondChen show in the comments, this can be done very cleanly: #include <Windows.h> #include <Accctrl.h> #include <Aclapi.h> #include <sddl.h> #include <filesystem> enum class FileAccess { ReadOnly, ReadWrite }; void grantAllAccess(const std::filesystem::path &file, const FileAccess access) { con...
74,269,148
74,270,185
Creating logical device in Vulkan returns -8, but only sometimes
While using a class to hold my window class and Vulkan class, this error VK_ERROR_FEATURE_NOT_PRESENT is returned when I use vkCreateDevice however, when I put the same code the class is running into the main class, it works completely fine. I also had a similar problem with getting the instance extensions via SDL_Vulk...
I think your problem is that requiredFeatures in XiEngine is not initialised. You set a few values to true, but I think you need a memset(&requiredFeatures, 0, sizeof(requiredFeatures)); or similar at the start of XiEngine::XiEngine to fix it.
74,269,200
74,269,238
Conditional operator not giving correct output
We have an issue that I have been able to recreate with this sample code: int main() { double d = -2; // ... cout << "d: " << d << endl; cout << "-d: " << -d << endl; cout << "Conditional Operator (expect value 2): " << (d < 0)? -d : d; cout << endl; return 0; } The output is as follows: d: -2 -d:...
It's a problem of operator precedence. Use: cout << "Conditional Operator (expect value 2): " << (d < 0? -d : d); Explanations: The reason is that << has a higher precedence than ? So your orignal statement does not mean what you expect, i.e. cout << "Conditional Operator (expect value 2): " << ( (d < 0)? -d : d ); ...
74,269,427
74,269,514
why when run my code the function doesn't work as expected
I made a function to get the larger number out of two when I run it it prints a random large number #include<iostream> using namespace std; int larger(int num1,int num2); int main() { int n1,n2,result; result=larger(n1,n2); cout<<"enter two number\n"; cin>>n1>>n2; cout<<"the larger number is "<<result<<endl;...
It's because you are calling the function before inputting 'n1' and 'n2'. result=larger(n1, n2) should come after the cin >>...
74,269,551
74,269,741
why does ranges::view_interface<T>::size require a move constructor
I don't understand where the requirement for moving comes from. I can't find it in forward_range and sized_sentinel... Basic example: #include <ranges> #include <string> #include <iostream> class vrange: public std::ranges::view_interface<vrange> { public: vrange(std::strin...
This has nothing to do with size specifically. view_interface is used to build a type that is a view. Well, the ranges::view concept requires that the type is at least moveable. And view_interface has a very specific requirement on the type given as its template argument: Before any member of the resulting specializat...
74,271,784
74,273,816
is it ok for arguments and expects go out of scope
I'm wondering is it ok if arguments and expects are going out of scope when they actually be matched later? like this: struct Object { // ... }; struct TestFixture : public testing::Test { MOCK_METHOD1(handle, void(Object obj)); }; TEST_F(TestFixture, Basic) { { Object obj; // = get different obj ...
From reference/matchers.html Except Ref(), these matchers make a copy of value in case it’s modified or destructed later. So you are fine.
74,272,161
74,272,392
How get name macros from value?
I write #define macros I want to have a function or a macro that prints its name when I give it a value for example : ` #define ten 10 string printName(int value); int main() { cout<<printName(10); } ` output : ten A solution or code sample
Use of macros should be avoided wherever possible. Instead you could use a std::map<int, std::string> for your purpose: int main() { const std::map<int, std::string> printName{{10, "ten"}, {11, "eleven"}};//add more if you want std::cout << printName.at(10) << std::endl; //prints ten }
74,272,713
74,280,169
Accessing raspberry Pi camera using C++
I am trying to run openCV in C++ and capture the camera input. The program looks like this: #include <iostream> #include <sstream> #include <new> #include <string> #include <sstream> #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #define INPUT...
Well I fixed it by rebooting. I already did do a reboot but I also now have some errors whenever I run the program. I did recompile the dlib library but so I do think that when you update the gstreamer library you need to reboot your machine to successfully use it.
74,272,874
74,275,145
preventing r-value references in variadic template
looking at std::ref and std::cref, the way I think it works is having two prototypes template< class T > std::reference_wrapper<const T> cref( const T& t ) noexcept; template< class T > void cref( const T&& ) = delete; and the T&& template function is deleted. But when I imitate this with a similar variadic template f...
Ordinary string literals are lvalues, so your test isn't testing what you want. Testing with literals that are rvalues, I found you need to have each variant of cv-ref qualifiers. #include<iostream> #include<utility> #include<string> template<typename ... Ts> void foo(const Ts& ... ts) { } template<typename ... Ts> v...
74,273,263
74,276,256
How can one write a multi-dimensional vector of image data to an output file?
Question: Is there a good way to write a 3D float vector of size (9000,9000,4) to an output file in C++? My C++ program generates a 9000x9000 image matrix with 4 color values (R, G, B, A) for each pixel. I need to save this data as an output file to be read into a numpy.array() (or similar) using python at a later time...
Use the old C file functions and binary format auto startT = chrono::high_resolution_clock::now(); ofstream outfile; FILE* f = fopen("example.bin", "wb"); if (f) { const int imgWidth = 9000; const int imgHeight = 9000; fwrite(&imgWidth, sizeof(imgWidth), 1, f); fwrite(&imgHeight, sizeof(imgHeight...
74,274,489
74,274,797
How can I simplify the For loop(c++)?
I found a code on the internet to encrypt user input with Caesar encryption. But in the code the loop head bother me, because we didn't have things like "message[i]" or "\0" in class. Is it possible to write this in a different way? But we had not used arrays as far as in this loop header. This is not homework or anyth...
To have a for loop closer to what you are used to, we need to know how many letters were input. The smallest change that does that is to use strlen to count them. for (i = 0; i < strlen(message); ++i) However it's better to use std::string to hold text, because that knows it's size. int main() { std::string messag...
74,274,552
74,276,978
Why use boost::bind instead of direct function call in boost.asio operations?
I've noticed 3 main options to call handler for async operations in Boost.Asio: class MyClass { public: void doReadFromSocket(); //implementation options provided below. private: void handleRead(const boost::system::error_code& ec, std::size_t bytesTransferred) { // ... handle async_read r...
Like others said, not all of your options are correct. Looking beyond that: bind (std or boost) has the added effect of returning a bind-expression templated on the original functor type. In C++ this means that the original associated namespaces for ADL still apply to the bound handler. This property is important when...
74,274,997
74,276,531
Move one more vector to the vector of vectors?
I have the structure vector<vector<x>> a and one more vector<x> v. I need to append this new vector to the existing vector of vectors (as new a item, not to concatenate), but it is long and I do not need it afterwards, so I would like to move the contents instead: As of the time of writing, the code is trivial: a.push...
Yes, this will definitely work. As you can read in the definition of std::move here, std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t. It ...
74,275,568
74,395,346
Is it possible to define preprocessor directives for an Unreal project at build time?
I am looking for a way to easily define macros / preprocessor directives at project build/cook time for an Unreal Engine project. For example, if I want a defined C++ macro MY_BUILDTIME_VAR to be 0 in certain builds, and 1 in others, without having to modify source code every time, in a similar approach to environment ...
Use an environment variable and read it in your build.cs file. Based on the environment variable set the value of your macro. This is a handy utility method I use for this purpose: private void AddEnvironmentVariableDefinition(string variableName, string defName, string defaultValue = "0") { string value = System.E...
74,275,656
74,276,361
How to virtual List control using a map data structure'?
I have a question while studying C++ MFC. void AnchorDlg::OnGetdispinfoListctrl(NMHDR *pNMHDR, LRESULT *pResult) { NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR); LV_ITEM* pItem = &(pDispInfo)->item; CString str; if(pItem == NULL) return; int nRow = pItem->iItem; int nCol =...
You don't seem to do anything with pItem->iItem (nRow), you just set it to the beginning of the list. You should instead search your data with this - requests may arrive in any random order. You don't have to iterate the list in OnGetdispinfoListctrl(), instead you should return the data to be displayed, given the iIte...
74,275,797
74,275,983
Nested template argument deduction
I have some function that is templated on output type. This function then accepts an input argument that in its turn is templated on the output type. I do not want to specify the output type twice as that just clutters the api. In my world, I have told the compiler everything it needs to know to deduce this correctly b...
The problem isn't with testFunc but with TestStruct{} as you're not passing a template argument and the corresponding template parameter of class template TestStruct doesn't have a default argument. I do not want to specify the output type twice As you want to specify the double only once you can do: template<typena...
74,276,942
74,277,035
Question regarding initialization of an array
My problem: I have the following piece of code that is a wrapper for 2D square matrices in order to transpose them and print them. I cannot understand why we can write this: arrayNN(T DATA[N][N]){ n = N; data = DATA; } In particular this line of code:data = DATA;. My thoughts: As far as...
T (*data)[N]; # a vector of N elements of pointers to datatype T = 2d matrix No, data is not a vector or an array. Instead it is a pointer to an array of size N with elements of type T. This means that when you wrote data = DATA; you're actually assigning the pointer DATA to the pointer data. Note that the function p...
74,277,117
74,277,722
How do i make it so that a certain input lists the functions and a certain input calls one of them?
You know how this shows up when you choose a directory in the terminal? Is there a way I could create my own version of this, but when the user chooses one of the choices, it calls a function? i mean nothing about the terminal or directory, i am using it as an example user types "menu" and there'd be a list of words t...
I have understood that you want to see a list of functions in your program, not files on your hard disk. There's no built-in way to do this, and although I can think of some more clever ways to do it, they are beyond your current level of understanding. Therefore, I recommend doing it the simple and stupid way: while(t...
74,277,297
74,293,070
Statically include large binary file in C++ executable in Visual Studio
I have a large binary file, ~1gb in size. I'd like to include this statically in a C++ executable compiled in Visual Studio 2019. The executable is built for Windows. I'd like to access the binary file at runtime, but don't want to ship it alongside the application. So reading at runtime from a file is not an option. I...
Can be done with Resource files. Right click project > Add > Resource File > Import > Select file > Choose a resource type name freely. #include <Windows.h> #include "resource.h" ... # IDR_SOMETHING is the resource identifier, can be found in the autogenerated resource.h HRSRC res = FindResource(NULL, MAKEINTRESOURCE(...
74,277,675
74,277,741
How to resolve compilation terminated and g++ : fatal error in cpp on Ubuntu O.S
I wirte the code right why does it show's me fatal error ? I think i didn't miss anything then why my code shows me error where i didn't do anything wrong ? And what is the meaning of fatal error why it's occurres and how solve it ? The code is #include <iostream> using namespace std ; // Function call by reference...
Don't put & in file names it confuses things as that character in Unix says to put the command into the background. Change Call_By_Value_&_Referance.cpp to Call_By_Value_And_Referance.cpp and anywhere else you have them. Don't post images, and reformat your question correctly.
74,277,767
74,278,577
VScode debugging: /dev/gpiomem Permission denied
Goal: I want to set up the VScode debugging on Ubuntu with a Raspberry Pi 400. What I have done: I am able to compile and run the program using sudo ./program_name. I have to run sudo otherwise I get permission denied error. I would like to not run VScode with root privileges as its generally discouraged. The problem: ...
gdb does not have permission to open /dev/mem or /dev/gpiomem. There are two approaches you can go forward with. Option 1 -- Elevate GDB's permissions Instead of running vscode as root (which was already suggested, and you rightfully pointed out this is generally a bad idea), you can run gdb from within vscode as root,...
74,277,870
74,278,462
Parallizing loading from a model in file
I have a model mesh that I want to load its vertices, indices, in parallel. The problem is I had to remove return statements if eof is catched for each block, reading vertices, reading faces. also I'm not sure if that's correct approach. MVP Code is here. std::ifstream inp(file_name, std::ios::in | std::ios::binary...
To load data fast, make your class structure exactly match the file format. If the file contains repeated binary data: float float float int then your vertex class should be class Vertex { float x, y, z; int index; }; and reading it will be as easy as this Vertex *data = new Vertex[numVerts]; fread(data, size...
74,278,732
74,278,967
How to get the real value of variable declared outside the loop, after using that varible in loop
I was working with loops and stuck with this problem. I had declared a variable outside the main code and then used it in the loop, but when I am returning the value of that variable after that loop, I am unable to get that value again. int n; int main () { // Sum of N natural numbers using FOR LOOP // 1st M...
Can I declare a universal variable and use it in a loop and at the same time after loop quits it does not change the value of that variable and gives the output as declared. Let me rephrase that as: "Can I modify something, and at the same time, ensure it is not modified?" No, you can't. What you can do is copy somet...
74,278,907
74,279,273
Winsock Received buffers caracters
I am currently trying to create an application to send messages from a server to a client after initiating the connection by sending filters from the client to the server (like a subscrition). The entire application is done but I found out that the messages I send contain special caracters and dont have the size they a...
std::cout << recvbuf is treating recvbuf as a null-terminated char* string, but there is no null terminator being sent by the client, and no null terminator being inserted by the server after the data received. So, operator<< ends up reading past the valid data, which is why you are seeing extra garbage being printed. ...
74,279,284
74,280,459
Add a panel when a button is clicked? (beginner)
I want to add a panel to my main window, when a button is clicked (Like a menu where you can switch between home and e.g. settings). I'm still learning wxWidgets, so I don't know most of the things. I searched the Web but found nothing that really helped me. Here's me Code: ` #include "MainFrame.h" #include <wx/wx.h> ...
SOLUTION: In the Header-File create the wxPanel with wxPanel* panel; (also create any controls you want to add/remove later on the panel. In the Eventmethod, use: panel->RemoveChild(exampleButton); panel->Refresh(); to remove Child "exampleButton"m which you created in the Header-File.
74,279,366
74,279,469
How to guarantee that std::cout always uses n width
I have output that looks like this: BTC-USDT [FTX] 20460.91 20470.09 BTC-USDT [BINANCE_US] 20457.34 20467.28 BTC-USDT [BINANCE_US] 20457.50 20467.28 I would like it to look like this: BTC-USDT [ FTX] 20460.91 20470.09 BTC-USDT [BINANCE_US] 20457.34 20467.28 BTC-USDT [B...
If you want a given value to have certain output characteristics, like width, alignment, etc, you need to apply the appropriate I/O manipulator(s) before you output the value, not after. In your example, you want pair to be left-aligned with a width of 9, and exch to be right-aligned with a with of 10, so apply std::se...
74,280,091
74,280,122
C++ read "enter" in command line
I have a very simple question. I have a project like below: #include <iostream> #include <fstream> using namespace std; int main(){ string file_name; cin >> file_name; ifstream file(file_name); if(file.good()){ cout << "File can be loaded"; } else{ cout << "Default file will be ...
operator>> discards leading whitespace first (unless the skipws flag is disabled on the stream), and then reads until whitespace is encountered. Enter generates a '\n' character, which operator>> treated as whitepace. For what you want to do, use std::getline() instead, eg: #include <iostream> #include <fstream> using ...
74,280,456
74,280,636
Sorting by the last and first digit of numbers in an array (c++)
I need to sort an array of numbers by looking first to their last digit first (and also comparing if another number in the array has the same last digit) and first digit second from minimum to maximum like bubble sort but with a twist. For example: () array = {22,32,76,45,95,31,10,28,79,21} return should be: {10,21,31,...
This example shows how code can cleanup if you use tested standard libary containers and algorithms. Use std::vector for variable input length arrays. For sorting use std::sort with a custom compare function. And you will end up with code with a lot less (potentially buggy) index managment. #include <algorithm> #includ...
74,280,858
74,281,983
How do I use Legacy OpenGL calls with QT6?
I'm new to Qt and am trying to import some older C++ openGL code. I'm currently using Qt 6.4. I've subclassed my OpenGL-using class to QOpenGlFunctions. Many of the glFoo calls "work" but the class also uses calls like glEnableClientState, glVertexPointer, glNormalPointer, glTexCoordPointer, glDisableClientState, glCol...
This question was answered by Chris Kawa over at the Qt Forums and it worked for me! Here is his answer: OpenGL 3.1 introduced profiles. Core profile does not support these old functions and Compatibility profile does. So first you have to make sure you have a context in version either lower than 3.1 (which does not s...
74,281,083
74,281,350
Overloading the stream extraction operator - Invalid operands to binary expression
trying to overload the extraction operator in this class class Mystring { private: char* cstring; size_t size; public: friend std::istream &operator>>(std::istream &is, Mystring &str); the function: #include <iostream> #include "mystring.h" std::istream &operator>>(std::istream &is, Mystring &...
You get the error because the overload reading into a CharT*: template< class CharT, class Traits> basic_istream<CharT, Traits>& operator>>( basic_istream<CharT, Traits>& st, CharT* s ); was removed in C++20. In C++20, the closest you can get is to read into an array of known extent, using the new overload: template...
74,281,528
74,282,049
How to nest and combine a bunch of functions?
Like I have a bunch of functions, f, g, h.... How to easily combine them to new_func(x) = f(g(h(x)))? For convenience, we can assume that the last function has no parameters and that the other functions can be called nested. Could the template parameter package achieve this? update: Actually, I want a way can give me a...
you can merge the function recursively something like this template <typename F> F combine(F f){return f;} template <typename F, typename...Fs> auto combine(F f, Fs ...fs){ auto rest = combine(fs...); return [=](auto arg){ return f(rest(arg)); }; } https://godbolt.org/z/EzqjKr4q5
74,281,612
74,281,708
How to remove duplicates entries, sum them and assign to a new vector?
I have a std::vector<std::tuple<int, int, double> triplets that is sorted by the first term of the tuple. It looks like triplets = { {0, 0, 1}, {1, 2, 5}, {2, 2, 1}, {2, 2, 3}, {3, 0, 2}, {4, 4, 2}, {4, 4, 5}, {5, 5, 6} } I need to remove the duplicates tuples that have the same first and second entries, keep j...
If sorted, loop through vector and check each element if it has same first and second value with the next element.If so, add the third value to this element and remove the next element. If not sorted, build an hash table and make {first,second} as key. loop through your vector, if key already exist, add the third to cu...
74,282,126
74,287,613
Bug or compilation error with some compilers for simple std::ranges code
I have a piece of code that uses the ranges library of C++20, taken from this SO anwer. The code is rejected by some compiler (versions) and some older GCC versions return garbage. Which compiler is right? The code is supposed to print the elements of the first column in a std::vector<std::vector>. #include <vector> #i...
GCC 11.2, 11.3, 12.1, 12.2, MSVC 19.33 are correct. Clang up to 15 does not support libstdc++'s <ranges> at all, and with libc++ the program works correctly. GCC 10.1, 10.2, 10.3, 10.4 and 11.1 mishandle std::views::drop(i) which is used in ith_element(i). Here's why std::views::drop(i) is complicated, and how old GCC ...
74,283,791
74,283,829
Why is the dynamically allocated memory released multiple times?
I use mutex and static variable to make sure the dynamically allocated memory to be released only once. But they are still released multiple times. Why? Thanks. I have read some threads saying it's not necessary to explicitly release static pointers. But It would be good to understand why that happens. // use C++-20 #i...
Because when you use such codes for (int i = 0; i < 3; ++i) { b.push_back(B()); } You will create three B objects, they are temporary variables, and they will destruct after push_back execute, so you allocate A pointer and delete it three times.
74,284,237
74,284,406
Rounding converting from string to double/float
I am trying to extract a number from a string and convert it into a double or float so I can do some numerical operations on it. I am able to isolate the variable I need so the string consists only of the number, but when I try to convert it to a float or double it rounds the value, ie from 160430.6 to 160431. //Helper...
You were almost there. The rounding was occurring on output, so that's where you need to use setprecision. That and always use double instead of float to ensure you have enough precision in your variables. #include <vector> #include <ranges> #include <iomanip> #include <iostream> #include <string> using std::string;...
74,284,796
74,458,692
standalone version of folly::Synchronized
Is there a functional equivalent of https://github.com/facebook/folly/blob/main/folly/docs/Synchronized.md that is self-contained and preferably header only so I don't have to pull in entire folly library into my project?
There is a dicussion on reddit where folly::Synchronized also has been mentioned and some other solutions are provided. Probably you're searching for something like this: https://github.com/copperspice/cs_libguarded A snippet of there test code: shared_guarded<int, shared_mutex> data(0); { auto data_handle = data.lo...
74,285,711
74,313,052
WinUI3: Unable to access UIElement defined programmatically inside a event delegate function
I'm creating the UI in WinUI3 with C++ programmatically. In XAML we can access an UIElement from all event delegate functions by its x:Name property, but when I define everything programmatically in c++ I was not able to set something like that. I want to make the UIElements defined programmatically accessible from Eve...
Found the issue. The issue was because of App.xaml.cpp file. void App::OnLaunched(Microsoft::UI::Xaml::LaunchActivatedEventArgs const&) { make<MainWindow>(); } I was getting the crash in this case, I was not able to access UIElement defined programmatically inside an event delegate function, because the window is init...
74,286,806
74,287,054
Pass derived class members to base class constructor
I have the following piece of code that is working but I don't understand why it works (inspired by a real life code base): Base class definition: class Pointers { private: int* Obj1; double* Obj2; public: Pointers(int* Obj1_, double* Obj2_) : Obj1{Obj1_}, Obj2{Obj2_} {} }; We now derive a class from our b...
It works, because at the moment when you call your base class constructor, the derived class members int Obj1{69}; double Obj2{72}; are not yet initialized, but their addresses are already known, and you are using their addresses to initialize pointers in the base class. Note that it has little to do with shad...
74,286,823
74,286,912
Conversion to string if input may be a string with spaces and line breaks
I am trying to convert any input of arithmetic type or char or string (including spaces and or line breaks) to a string. I tried using to_string which works for any input but string. I then tried void dataToString() { std::stringstream ss; ss << cryptedData; ss >> dataString; } which works even for strings...
To get the contents of a stream as string, you can simply use the str member function: std::string dataToString() { std::ostringstream ss; ss << cryptedData; dataString = std::move(ss).str(); }
74,287,539
74,287,993
Why is the move ctor not called, in this std::move case?
If build and run this short example #include <memory> // for class template `unique_ptr` #define LOG() std::printf("[%p] %s\n", this, __PRETTY_FUNCTION__) class bar_t final { public: bar_t(int val) : m_val(val) { LOG(); } ~bar_t(void) { LOG(); } bar_t(bar_t&& dying) : m_val(std::move(dying.m_val)) { LOG();...
It is widely recognised that std::move has a misleading name: it does not actually perform a move. Instead, it performs a cast, similar to static_cast<T&&>1. To perform a move, you need to invoke a move constructor or a move assignment operator. This doesn’t happen in your #if 1 code branch, but it does happen in the o...
74,288,310
74,288,349
C++ How to create and return an iterator inside a function?
I tried to write a function that receives a list and an index and returns an iterator to the list that starts at that index. The function: template<class T> typename std::list<T>::iterator begin_it_at_index(list<T> list_to_iterate_on, const int index) { return next(list_to_iterate_on.begin(), index); } When I called...
You need to pass the container by reference to begin_it_at_index. Otherwise a value copy is taken, and the returned iterator is invalidated as the local list_to_iterate_on in the function goes out of scope. That is, template<class T> typename std::list<T>::iterator begin_it_at_index( list<T>& list_to_iterate_on, ...
74,288,827
74,288,937
Optimizing class layout by minimizing padding safely
I have the following type and my goal is to optimize the size of Storage: struct Inlined { int data[9]; }; // sizeof => 36 struct Allocated { int* data; size_t capacity }; // sizeof => 16 union Data { Inlined inlined; Allocated allocated; }; // sizeof => 40 struct Storage {...
This is very much well-defined. From [class.mem] In a standard-layout union with an active member of struct type T1, it is permitted to read a non-static data member m of another union member of struct type T2 provided m is part of the common initial sequence of T1 and T2; the behavior is as if the corresponding membe...
74,288,908
74,289,315
Accessing a 2D vector using push_back()
I am currently declaring my vector as follows std::vector<std::vector<int>> test(5, std::vector<int>(2,0)); I then access it like this ` for (int i = 0; i < 5; i++) { std::cin >> test[i][0]; std::cin >> test[i][1]; } ` Since the vector is static (5 Rows, with 2 columns), I would like to make i...
You know how to push a vector into the vector of vectors. You wrote this: nns.push_back(std::vector<int> {i}); You do not have to specifiy the size i here, you can push an empty vector nns.push_back({}); Now nns has a single element. nns[0] has 0 elements. Pushing elements to nns[0] works exactly the same, just tha...
74,289,725
74,289,898
Can there be an array made out of strings pointing to the same Memory Adress
I have 3 strings. I need to create an array out of those 3 strings, when I do it, it gets shown to me that the memory adresses of the strings are different than the ones of the array. Meaning that they dont point to the same thing. But I want that if I change the strings out of which I made the array, after the array c...
So here some code using pointers, that does what you want std::string* xp = new std::string("x"); std::string* yp = new std::string("y"); std::string* zp = new std::string("z"); std::string* letters[3] = { xp, yp, zp }; *xp = "X"; // changes *xp and *letters[0], since xp == letters[0] Now raw pointers are a bad idea...
74,290,006
74,290,404
Passing values to a Constructor which takes pointers parameter
I am very new to C++ and I am trying to initialize an object called GameObject, in a class called Room, which holds a gameObjects array. The constructor of the GameObject class takes pointers as the parameters to initialize the fields. But I keep getting the error saying that there is "No matching constructor for initi...
Well, you in the GameObject constuctor: GameObject::GameObject(string* _name, string* _description, char* _keyWord): name(_name), description(_description), keyWord(_keyWord){} You are accepting the two strings and a char by pointer. So maybe you meant to accept them by reference instead like this: GameObject::GameObj...
74,290,411
74,290,505
How to set `rpath` with gcc?
I have an executable that uses some shared objects. These shared objects have other shared objects as dependencies, and I want to set my main executable's rpath to include the directories for those dependencies, since runpath is not used for indirect dependencies. I'm trying to bake rpath into my ELF, however when usin...
To get a DT_RUNPATH entry you need --enable-new-dtags. To get a DT_RPATH entry (which is deprecated) you need --disable-new-dtags. In your case, something like this: gcc -std=c++20 -o main main.cpp -lstdc++ -L./lib -Wl,--disable-new-dtags,-rpath,./lib I'll suggest to use an absolute path with rpath, I'm not sure from...
74,291,350
74,296,888
Python cannot find Boost.Python module
I try to create a simple C++ module for python with Boost, but python gives me ModuleNotFoundError: No module named 'MyLib'. The .py file is in the same location as MyLib.dll. UPD: if i change dll to pyd or replace add_library(MyLib MODULE MyLib.cpp) with PYTHON_ADD_MODULE(MyLib MyLib.cpp) I get another error: ImportEr...
You mention that your binary module is named MyLib.dll. That is the first problem.[1], [2] On Windows, CPython expects binary modules to have extension .pyd. Either rename the DLL manually, or (as you mention) use PYTHON_ADD_MODULE instead of add_library to achieve the same automatically. Once you do this, another prob...
74,292,315
74,430,470
thread_local storage, constructors, destructors, and tbb
It's my understanding that tbb may maintain pool threads for reuse... is there a way to ensure that data that I have declared using a modern C++ implementation as thread_local and with a non-trivial (default) constructor and destructor, which is initialized whenever the data is first used from a new thread is destroyed...
Program logic context and threads should be considered as another concept. Threads are used by your program context. Your program context might need one thread which is created and destroyed mutually with you program context, or might run on a thread provided from pooled thread, or might run on multiple threads which a...
74,293,348
74,293,466
Right bit shift in body of lambda used as a template argument doesn't compile on GCC
GCC doesn't compile this code, while other compilers (clang, msvc) do template<auto T> struct S { }; int main() { S<[]{int x,y; x<<y;}> s1; // compiles fine S<[]{int x,y; x>>y;}> s2; // error } error: error: expected ';' before '>>' token | S<[]{int x,y; x>>y;}> s2; | ^~ |...
g++ is actually correct here. From [temp.names]/3 (C++20 Draft N4860): When a name is considered to be a template-name, and it is followed by a <, the < is always taken as the delimiter of a template-argument-list and never as the less-than operator. When parsing a template-argument-list, the first non-nested > is tak...
74,294,181
74,294,258
redefined virtual function call
#include <iostream> class Base { public: virtual void foo() { std::cout << "Base::foo()\n"; }; }; class Derived : public Base { public: void foo() override { std::cout << "Derived::foo()\n"; Base::foo(); } }; int main() { Derived obj; obj.foo(); return 0; } Hello th...
"why compiler doesn't delete Base::foo in class Derived after redefine" Because that isn't what virtual and override do. When you provide an override to a base class function, you do not replace it. You are defining a new version for that function. The base class's implementation continues to exist and to be accessible...
74,294,427
74,294,507
Wrong results when assigning to int array in c++
#include <iostream> using std::cout; using std::cin; using std::endl; int main(){ int v[5]; int a[5][5]; int i = 0, j = 0; for (i = 0; i < 5; i++){ v[i] = 0; for (j = 0; j < 5; j++){ a[i][j] = 0; cout << "A[" << i << ", " << j << "] = " << endl; cin ...
Initializing a value in c++ like int v[5]; just reserves space. It does nothing to initialize the values to 0 or something. Anything could be in those five indices. Whatever happens to be in that address space.
74,294,494
74,294,589
cleanQueue - cleanup function. C++
Hi so I have a task to create a full queue with integers I need to do a clean function like that: `void cleanQueue(Queue* q); ` The Queue form is that: typedef struct Queue { int * arr; } Queue; Thanks alot!
Well if you need the implemenatation to be like: typedef struct Queue { int * arr; } Queue; you could simply do: void cleanQueue(Queue* q) { delete q->arr; } or if you initialise the arr data member as an array like {1, 2, 3, 4}you would do it like this; void cleanQueue(Queue* q) { delete[] q->arr; } So you'r...
74,294,590
74,294,753
why we use two conditions in head!=nullptr && head->next != nullptr in floyd cycle detection algorithm?
i want to know that why we use two conditions i am confused.. while head and head->next are not equal to null which means head and head's next will point to null ho is that possible int detectCycle(Node *& head) { Node * fast = head; Node * slow = head; while(fast!=nullptr && fast->next!=nullptr) // i am con...
while head and head->next are not equal to null which means head and head's next will point to null ho is that possible From the code presented, I guess you mean fast where you wrote head. If fast is null then fast!=nullptr evaluates to false. In that case it would produce undefined behavior to evaluate fast->next, ...
74,294,744
74,294,793
Displaying results of methods on the screen
My task is to practice inheritance, putting all the classes in separate files. I have a base class Circle and a derived class Cylinder. What I'm stuck on is trying to display on the screen the result of my calculated area and volume for an object B of a Cylinder type. I found a way to do that for a Circle, though it do...
In your getArea() function, instead of saying: cout << "Area = " << endl; Just say: cout << "Area = " << area() << endl; Then in your main.cpp, just call B.getArea(). Hope this helps!
74,295,014
74,323,347
Compile a .cpp file for an Arduino project
I'm trying to start an Arduino project with Arduino IDE and I'd like to use external C++ code outside the .ino main file. In particular, I have the following file: arduino.ino <- main .ino file /HeartSensor HeartSensor.h HeartSensor.cpp /oledScreen oledScreen.h oledScreen.cpp To import the two files...
Lay out your project as: arduino.ino <- main .ino file /src /HeartSensor HeartSensor.h HeartSensor.cpp /oledScreen oledScreen.h oledScreen.cpp To import the two files in the folders, do the following: #include "src/HeartSensor/HeartSensor.h" #include "src/oledScreen/oledScreen.h"
74,295,100
74,296,946
What's a good alternative to PAUSE for use in the implementation of a spinlock?
I am working on making a fiber-based job system for my latest project which will depend on the use of spinlocks for proper functionality. I had intended to use the PAUSE instruction as that seems to be the gold-standard for the waiting portion of your average modern spinlock. However, on doing some research into implem...
I'm guessing is due to the other often quoted factoid that using PAUSE somehow signals to the processor that it's in the midst of a spinlock. Yes, pause lets the CPU avoid memory-order mis-speculation when leaving a read-only spin-wait loop, which is how you should spin to avoid creating contention for the thread try...
74,295,182
74,295,368
How to fill QAbstractTableModel with another's class attribute (2D array)
I have class, which reads data from file to 2D array. So i need to display that array in qml TableView. I have QVector<QVector> table; to display it as data in my TableModel. The OperatingFiles object creates in main.cpp it contains functions to encode/decode passwords and save them to file. Functions for this object i...
The easiest modification would be to add a Q_INVOKABLE to your TableModel which allows to set the table class TableModel : public QAbstractTableModel { ... Q_INVOKABLE void setTable(const QVariant& value) { //inline for briefity beginResetModel(); table = value.value<QVector<QVector<QString>...
74,295,185
74,295,626
What is the difference between an "enumeration type" and an "enumerated type" in C++?
The Standard "apparently" defines "enumeration type" in [dcl.enum]/1. The term "enumerated type" is defined here.
The first link (http://eel.is/c++draft/dcl.enum#1) explains what an enumeration type in C++ is. This is where C++ officially defines it. The other link (http://eel.is/c++draft/enumerated.types) is about the C++ standard library. This link explains how you have to read the description of the standard library, that comes...
74,295,409
74,295,422
Why is my variable jumping in value when I add an "if" condition?
The code below, without the if statement, count's up from 1 to infinite and shows this in the console as intended. If I add the if statement, I get what's shown in the screenshot below. Why does this happen? #include <Arduino_MKRIoTCarrier.h> MKRIoTCarrier carrier; int a; int r,g,b; void setup() { // put your set...
In c++, comparison is ==, so you need to write if (a == 10). When you write, a = 10, that's an assignment: a will have the value of 10 and the evaluation value is also 10 (to be precise, reference to a which is 10), thus in if() it evaluates to true.
74,295,761
74,296,011
Changing the text of the "static text" control and its color at once (a bad behavior occurred)
I am trying to change the text of the "static text" control and its color at once, and I have done that, but the problem is when changing the text first and then changing the color of that text, it takes a little noticeable time between changing the text and its color. bool IsGameOpen = false; INT_PTR CALLBACK Dialog...
As stated in comments, the Static control is likely being repainted immediately, and thus sending WM_CTLCOLORSTATIC to you, while SetDlgItemTextW() is being processed, but you haven't updated your IsGameOpen variable yet, so the new color doesn't take effect until the next time the Static control has to be repainted. T...
74,296,129
74,296,221
RAM, Memory cell and address
I am trying to get a sound understanding about how RAM works in most computers. I am watching videos and reading online but haven't got a straight clear answer. I just have two questions: Is Memory cell the same as memory address? Is there a difference? What is the smallest unit of addressable memory -> Here I am get...
The smallest addressable unit is a byte (in most current computers that you will come accross) To set a variable to 0 or 1 will require that variable to be at least one byte. But you can use individual bits in one byte for different bits You do that using bit fields in structs in c or by bit level operations on bytes (...
74,296,345
74,299,202
How to remove a Python function from a module using C++?
Creating an application in C++, I integrated CPython to facilitate the development of certain top-level logics. The application has a plugin subsystem, which can loaded/unloaded plugins at runtime, this implies to add and remove Python definitions at runtime. I found that I can add functions with PyModule_AddFunctions,...
You can use PyObject_DelAttr C-apis. int PyObject_DelAttr(PyObject *o, PyObject *attr_name) Delete attribute named attr_name, for object o. Returns -1 on failure. This is the equivalent of the Python statement del o.attr_name Reference. So you could do something like this to remove log function void PluginRemoveAFunc...
74,297,266
74,297,898
How do I change the font weight of a specific control on a dialog based window?
I have a dialog-based window that has a "static text" control. I want to change the font weight of that "static text" control. I have read several subjects talking about that subject but I still don't understand how do I achieve that. This is what I have come up with so far: INT_PTR CALLBACK DialogProc(HWND hDlg, UINT...
Unlike static control colors, which come from the parent dialog, each control is responsible for remembering its own font. Use WM_GETFONT to get the font the control is currently using: HWND hwndCtl = GetDlgItem(hDlg, IDC_STATIC); // replace with your control ID HFONT hCurFont = reinterpret_cast<HFONT>(SendMessage(hwnd...
74,298,299
74,298,323
compiler reports const instead of const&
Tried to compile following code, can't understand error message. #include<iostream> #include<string> using namespace std; struct S { string a{"abc"}; const string& data() { return a; } }; int main() { S s; int a = s.data(); // error: no viable conversion from 'const std::string' to 'int' return 0; }...
data() returns a reference to a const std::string object, yes. But, you are not converting the reference itself to an int, you are converting the std::string object that it refers to. A reference is just an alias, once a reference has been bound to an object, any access of the reference is really accessing the object i...
74,298,412
74,302,716
Using boost graph library to obtain induced subgraph reachable from vertex v with distance d
I'm having problems in filtering the subgraphs using boost libraries, I want to obtain induced subgraph reachable from v with distance d. Here is the python code using networkx library: def reachable_subgraph(G, v, d): E = nx.bfs_edges(G, v, depth_limit=d) N = set([n for e in E for n in e]) return nx.induce...
You might use the filtered_graph adaptor. I like to push c++20 features to get as close to Pythonesque as I can: #include <boost/graph/filtered_graph.hpp> template <typename Graph, typename Nodes, typename V = typename Graph::vertex_descriptor> auto induced_subgraph(Graph& g, Nodes nodes) { std::function f{[n = st...
74,299,443
74,343,338
Convert YUV frames to RGB
I'm trying to convert YUV file(UYUV, YUV 422 Interleaved,BT709) to RGB with C++. I've took the example from here: https://stackoverflow.com/a/72907817/2584197 This is my code: Size iSize(1920,1080); int iYUV_Size = iSize.width * (iSize.height + iSize.height / 2); Mat mSrc_YUV420(cv::Size(iSize.width, iSize.he...
The problem was that UYVY is 2 bytes, so I have to double the size of the image. Now with thelines int iYUV_Size = iSize.width * iSize.height * 2; Mat mSrc_YUV420(cv::Size(iSize.width, iSize.height),CV_8UC2); it works well. Thanks, @micka for the help!
74,299,737
74,304,129
How to compile and migrate to DPC++
I have cloned a github repository which has some C++ and OpenCL project to my devcloud account. Is there a way to migrate these opencl files to DPC++? I want to work with jupyter notebook will it be possible?
Yes, you can migrate OpenCL applications to DPC++ because DPC++ includes SYCL, which is a higher-level abstraction layer that builds on OpenCL, when comparing DPC++ and OpenCL, most fundamental concepts are the same with an easy mapping of equivalent constructs between OpenCL and DPC++. Here is the article which gives ...