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
64,725,302
64,725,601
What is difference between begin() and data()
begin() and data() both returns iterator pointing to the first element. But, the definition of data() says it Returns a direct pointer to the memory array used internally by the vector to store its owned elements. I can also use them to access any element. So, how both of them are different? consider the following exam...
All container types have an iterator, but only some container types are contiguous and support data(). For example, vector<int> v; copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n")); v.data(); // ok list<int> l; copy(l.begin(), l.end(), ostream_iterator<int>(cout, "\n")); l.data(); // no It is true that the ...
64,725,416
64,747,778
Finding sum of only deepest leaf nodes in the binary tree?
I was solving a question given above and deepest meant only the leaf nodes which are at level = height of the tree. I solved it through an approach which is giving wrong output and i cannot find why while debugging it. int deepsum(TreeNode* root,int h,int sum,int l) { if(root==NULL) return 0; ...
well, well, well.. the problem lies in method where you calculating height. your "height" method needs this modification. int height(TreeNode* root) { if(root==NULL) return 0; int ls=height(root->left); // int rs=height(root->right); return max(ls,rs)+1; }
64,725,543
64,725,708
Im including <iterator> but get unknown type name 'iterator'
I feel like this has to be an issue with namespace pollution, otherwise I dont know my compiler thinks iterator is an unknown type name In a previous coding project I had a class with the exact same method declaration with no issues, which is why I dont understand why it doesnt work here. The full error is In file incl...
I was able to solve this by changing my header file to be class AlgoContainer{ private: std::vector<Task> allTasks; void sort(); public: AlgoContainer() = default; void addTask(const Task); ~AlgoContainer(); //CHANGE HERE using iterator = decltype(allTasks)::const_iterator; iterator begi...
64,725,631
64,725,789
Cannot generate Mandelbrot matrix to save it to file in c++ threads
I'm starting with my c++ threads and don't understand some basic stuff. That's Mandelbrot example, it generates fractal image. It's not my code, I just did some changes (here's original: https://rosettacode.org/wiki/Mandelbrot_set#PPM_non_interactive) I have this function which generates matrix with colors to save to f...
This: rows[Index] = color; Is assigning the unsigned char * in your vector to the same array every time! In other words it's like if I sell you ten cars and deliver the keys but they are all identical keys to the same car. Wouldn't you be upset? Change your variables to use std::array: using Color = std::array<u...
64,726,435
64,726,636
stackoverflow for empty function
Look at this code : void f() { f(); } I know that because so many f() ​​functions are called, StackOverflow occurs. But my question is what is exactly stored in the stack that causes this error, return address for each f() function call? Because this function has no variables, so why does StackOverflow occur?
As the other answers already said, it's because of the return addresses. void f(){ f(); } compiles to f: call f #Let's assume f has the address 0x1000 for later purposes ret But what does call do? It does two things: Push the current address to the stack Call the specified address. It's essentially: f: push...
64,726,797
64,726,832
Why can't I use this 'void' type in a range based for loop?
for(auto i: {{1,2,3}, {4,5,6}, {7,8,9}}){ /* loop body */ } I know I have other ways to get my work done. But I was just wondering why we cannot use such type of list in this loop. It is giving me this error: cannot use type 'void' as a range
{..} has no types, so it is problematic for deduction needed for inner type, you might help by explicitly provide the type: (I used CTAD from C++17 here, before add <int>) for (auto i: {std::initializer_list{1,2,3}, {4,5,6}, {7,8,9}}){ /* loop body */ } Demo
64,727,165
64,728,578
Is it OK for a class constructor to block forever?
Let's say I have an object that provides some sort of functionality in an infinite loop. Is is acceptable to just put the infinite loop in the constructor? Example: class Server { public: Server() { for(;;) { //... } } }; Or is there an inherent initialization problem in C++ if ...
It's not wrong per standard, it's just a bad design. Constructors don't usually block. Their purpose is to take a raw chunk of memory, and transform it into a valid C++ object. Destructors do the opposite: they take valid C++ objects and turn them back into raw chunks of memory. If your constructor blocks forever (emph...
64,727,904
64,727,985
Why is Nested while loop not working in 2nd try c++?
This is guessing game So what I am trying to do is ask user after every game completion whether they wanna play again. 2nd last line of code the program run but while(guessedNumber != secretNumber && guessCounter != 0 ) does not get executed 2nd time What should I do ? #include <iostream> #include <cstdlib> #include ...
Relevant parts of your code are: int guessCounter = 3; //number of times user have guesses left char wannaPlayAgain = 'y'; while(wannaPlayAgain != 'n'){ while(...blablabla.. && guessCounter != 0 ){ guessCounter--; } if(guessCounter == 0){ cout << "\n\n YOU LOSE\n\n" << endl; ...
64,728,521
64,728,594
Deleting a max element in an array in c++
As you can see I wrote a simple program to find the highest/max element in int array and deleting it from the array and print the remaining array. It giving me an error. I do not want to use STL; #include<iostream> using namespace std; int findmax(int a[],int size,int max) { for(int k=0;k<size;k++) { if(a[k]>m...
void ddlj(int a[],int size,int z); to void ddlj(int a[],int size,int z) you should install a checker of syntax-error like vs(windows) or ycm(linux). and welcome to C++
64,728,527
64,728,748
how to make a reverse half pyramid pattern on c++ using for loops
The following photo should illustrate what my output should result. This is the code I've tried but it gives out a full triangle instead. #include<iostream> using namespace std; int main() {int n; cin>>n; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(j<=n-i) { cout<<" ";} else { cout<<"...
The only thing you should change in your code is the if condition. #include<iostream> using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { //row for (int j = 1; j <= n; j++) { //column if (n-j>=i) cout << " "; else cout << "*"; } c...
64,728,560
64,728,652
C++ linked list- class implementation
Hey I have build an implementation of linked list in c++ using List class and inner node struct. everything works fine except removing node from tail function: void List::remove_tail() { Node* runPtr= new Node; runPtr = this->head; while(runPtr->next->next !=nullptr) //this loop is not stopping! { ...
Do not allocate new Node for the runPtr. It's a pointer that should point to an already allocated element in the list. Here you're just leaking memory. Do not dereference pointer without validating it's not null. runPtr might be null, runPtr->next might be null too. In both cases you'll perform unauthorized memory acc...
64,729,027
64,736,376
How to require the existence of a function in a constraint?
I have a file vector.h with a custom Vector class, where the data type of the vector entries should be restricted to types for which a function f is implemented: template <typename T> concept Vector_Type = requires (T a) { f(a); }; template <Vector_Type T> class Vector {}; Additionally, I have multiple files wher...
I am not sure how workable this design is, but the crux of the issue is that int is a builtin type. If you have a special type that is used to invoke f, you'll be able to delay the lookup of f until instantiation. For example: struct enabler{}; template <typename T> concept Vector_Type = requires (T a) { f(a, enab...
64,729,369
64,729,510
How to repeat a loop without using any bool?
How to repeat switch statement using cin and without using of any bool and loop statements if it is possible. I need a very simple solution for this. I can do it on complex ways but I believe that it can be achieved in a very simple way if I am not wrong. Code: #include <iostream> using namespace std; void add...
The natural way to repeat code is a loop. If for some reason you do not want to use a loop you can put the code you want to repeat inside a function: void foo() { // code goes here } and then call that function as often as you like: foo(); foo(); foo(); However, its not simple to decide at runtime how often the fu...
64,729,742
64,729,790
C++ How do you solve namespaces in headers becoming undefined?
So I am currently making a small prototype for a bigger project I'm working on and I've gotten completely stuck on it. I am rather new to c++ and haven't worked with headers or namespaces before ever. The issue is that when i try to use my created namespace it fails completely and the compiler (clang) returns undefined...
In the implementation file, this definition: void woof() { // ... } defines a function woof in the global namespace. So when you make the call: bark::woof(); in the main function, there is no bark::woof defined, and the linker will refuse to link the program. To correctly define the woof from namespace bark, you ...
64,730,045
64,763,570
How to detect Created Exe's created another exe is closed?
For example, we have 2 executable files on windows. (EXE_1.exe, EXE_2.exe) EXE_1.exe is calling EXE_2.exe with arguments. I want to detect when EXE_2 Closed(Terminated, killed etc.) I can't use WaitForSingleObject in C++ or Psutil process wait in python. Because it is returns when First executable its closed. (Remember...
info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = EmreWin32Con.SW_MINIMIZE EXE = subprocess.Popen([EXE_KONUM], cwd=KLASOR_KONUM_EXE, creationflags=subprocess.CREATE_NO_WINDOW, startupinfo=info, stder...
64,730,205
64,730,464
Be careful: the "unsigned" specifier changes the size of the wchar_t type in Visual Studio
Adding the unsigned specifier to the wchar_t type in Visual Studio changes the type size from 2 to 4 bytes. By running the following two lines of code in Visual Studio 2008, or in the latest Visual Studio 2019: cout << "wchar_t: " << sizeof(wchar_t) << endl; cout << "unsigned wchar_t: " << sizeof(unsigned wchar...
I think visual studio is correct here, there is no provision in the standard for unsigned wchar_t (or signed wchar_t) so it is up to compilers how they handle it. Whilst an error would be nice (as raised by GCC and Clang) a warning is OK too. Presumably the 4 bytes is because Visual Studio has to decide to discard one ...
64,730,492
64,731,153
Why are virtual assignment operators "a can of worms"?
My textbook says that virtual assignment operators "opens a new can of worms beyond the scope of the tutorial". It is possible to make the assignment operator virtual. However, unlike the destructor case where virtualization is always a good idea, virtualizing the assignment operator really opens up a bag full of worm...
Let us take the classic shape example: class Shape { public: virtual bool operator==(const Shape & s) const = 0; }; class Rectangle : public Shape { public: bool operator==(const Shape & s) const { /*...*/ } }; class Circle : public Shape { public: bool operator==(const Shape & s) const { /*...*/ } }; No...
64,730,812
64,732,214
MSVC Output filename of file being compiled
I'm using Visual Studio 2019. When I Build Solution I sometimes get an error like this: C2825 'TContainer' must be a class or namespace when followed by '::' MyProject MyHeaderFile.h As MyHeaderFile.h is a template file I want to know which file is including it as that is where the error is. How can I get the bu...
Tools -> Options -> Projects and Solutions -> Build And Run: "MSBuild project build output verbosity:" - whe I set it to Quiet - the file names are gone, together with #pragma message
64,730,822
64,730,859
If I use a pointer in a function to populate a list, do I have to delete that pointer at the end of the function in c++?
If I use a pointer in a function to populate a list, do I have to delete that pointer at the end of the function, or the list's destructor will do the work in c++? For example: void populateList() { Human* human; List<Human> myList; for (int i = 0; i < 5; ++i) { human = new Human(); myList.push_back(*hum...
In this line: myList.push_back(*human); you are making a copy of the dynamically allocated object pointed at by the human pointer, so the myList destructor will only clean up that copy. You do need to manually free the dynamically allocated memory pointed at by human, to avoid leaking that memory. However, in this ca...
64,731,103
64,731,122
Lambda closure cannot be converted to std::function
Why does the second call to f() result in a compilation-error: lambda closure cannot be converted into std::function<int(int)> #include <vector> #include <functional> void f(std::function<int(int)>f1, int x) { f1(x); } int g(int x, int y) { std::cout << x + y; return x; } int main() { f([](int x, i...
Because you forgot a return: f([](int x, int y = 10) { return g(x,y); }, 20); Without return, your lambda doesn’t return a value, and C++ infers a void return type.
64,731,159
64,733,156
Making a function that prints any variable given as parameter in c++
I love debugging by printing, since you can print lots of things and investigate your code. But I don't like cout<<ing all the time, since it is a bit hard to write, and you have to add new line to cout, which means if you want to print something you have to cout<< something<<"\n"; I was writing a function in Javascrip...
You can create a templated function. This would look like: template<typename T> void p(const T& t) { std::cout << t; } What this does, is that when you hit compile, it automatically create functions using this template, with T replaced with the types you have used in your program. So if you were to write: p("Hello...
64,731,843
64,731,876
What does this cycle do?What is the point?
int myDrawOrder = sprite->GetDrawOrder(); auto iter = mSprites.begin(); for(;iter != mSprites.end(); ++iter) { if(myDrawOrder < (*iter)->GetDrawOrder()) //what does this line mean? { break; } } GetDrawOrder() returns the position of the sprite in the queue.
The loop iterates over the sprites, and breaks when it finds a spite that should be drawn before the sprite. You didn't share the rest of the code, but presumably something is then done with that sprite (e.g., it's drawn).
64,732,232
64,732,270
Return type of assignment operator in C++
imagine I have a class like this: public: A(const int a); A& operator = (const A&); }; Why does the return type of the "=" operator have to be "A&" and not simply "A"?
The return type doesn't have to be A&; the standard only says: A user-declared copy assignment operator X​::​operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X&, or const volatile X&. We do that by convention. The oft-cited argument is that...
64,732,260
64,733,133
Does c++ chrono have a normal round function that rounds away from 0 on tie?
std::chrono::round rounds to the nearest even number when it is exactly between numbers instead of rounding away from 0. std::chrono::round<std::chrono::seconds>(3500ms) // = 4 std::chrono::round<std::chrono::seconds>(4500ms) // = 4 (instead of 5) (Side question: Why would they do that?). I was wondering if their is a...
In practice, fair rounding is not very useful for engineering, graphics, DSP, etc... You'll have to roll your own. Here is the standard rounding used in engineering. This will give you the most consistent rounding for engineering-related tasks. auto rounded_to_nearest_s = std::chrono::floor<std::chrono::seconds>(time +...
64,732,273
64,732,503
c++ header files (General Question about redundancy)
I am new to c++ so forgive me if this question doesn't make much sense, but I have the follow files: // main.cpp #include <iostream> #include <fstream> using namespace std; #include "second.h" int main () { string filename; cin >> filename; ifstream fileIn; if( !openFile(fileIn, filename) ) { ...
The general issue The reason you have to include relevant headers in each .cpp file is because such .cpp files are compiled separately and independently; in more formal parlance: They constitute different "translation units". See also: What is a "translation unit" in C++ Sometimes, when multiple translation units must ...
64,732,342
64,732,752
CMake & CodeSynthesis Header-only library not compiling
I have been trying to implement the runtime library which is a header-only library of CodeSynthesis. But I only get a linking compiling error whenever I try to run the generated files which are made by the XSD executable. Here is the error to show you that I have a linking problem with the runtime library: [100%] Linki...
Thanks to 'Asteroids With Wings' I figured out that a header-only library should not be added as a library in CMake. Including the library and linking the XercesC library was enough. CMake solution cmake_minimum_required(VERSION 3.17) project(XercesGebeuren) set(CMAKE_CXX_STANDARD 20) set(Xsd_DIR ./cmake) find_packag...
64,732,555
64,734,024
Priority of friend function and class method that overload the same operation
Here is my code: #include <iostream> using namespace std; class RationalNumber { private: int num; int den; public: RationalNumber(int a):num(a),den(1){} RationalNumber(int a, int b):num(a),den(b){} void parse() { cout << num << "\\" << den << endl; } RationalNumber oper...
I'll present a simplified view. For this, you will play the role of the compiler. Suppose you are busy compiling some code and come across an operator that was given a RationalNumber and an int as operands. What to do? Well, the compiler's job description includes matching operators to implementations, so you grumble a...
64,732,748
64,732,771
Getting the colour of a pixel at specified coordinate on the screen
I need to get the colour of a pixel in the specified location. After some research this is what I have. #include<windows.h> #include<iostream> int main() { HDC dc = GetDC(NULL); COLORREF color = GetPixel(dc, 100, 100); ReleaseDC(NULL, dc); std::cout << GetRValue(color); std::cout << GetGValue(col...
This is just a matter of the way you are printing the values. Try this instead std::cout << static_cast<unsigned>(GetRValue(color)) << '\n'; GetRValue(color) etc returns a byte value, which cout << is interpreting as a character. By casting to unsigned it forces cout << to print the integer value instead.
64,733,105
64,733,124
My seconds variable is not storing properly
As the title says my seconds variable is not storing properly and im unsure as to why. I tried inserting a cout statement after the user inputs on line 8, but for some reason it's not storing i.e the output would be -1.75474e+4. Thank you :) #include <iostream> #include <iomanip> #include <fstream> #include <cmath> usi...
You used equivalent operator(==), instead of assign operator(=) seconds == readSeconds(); // bad seconds = readSeconds(); // good
64,733,158
64,733,602
Template type alias visibility compiler disagreement
The following example compiles with gcc but not with clang. Which compiler is right, and why? #include <utility> struct Foo { private: template<typename T> static int f(); public: template<typename U> using T = decltype(f<U>()); }; int main () { static_assert(std::is_same_v<Foo::T<float...
This is a clang bug, where clang doesn't resolve the correct access control for names used in member alias templates. This question is an example of the bug, where the access control for names of members of friend classes is resolved incorrectly. In your example, you have a static member template f, and for that we onl...
64,733,215
64,733,297
How to create matrix output pattern with array 2D in C++
I have a little difficulty in programming in C ++ to make patterned output using 2D arrays, I make the output like a matrix like this: input 4 (for column 4 & row 4) I I I I 0 0 I 0 0 I 0 0 I I I I I've tried this my programmed. For the top and bottom rows I've managed to change the value to 1 #include <iostream> u...
Try this for(i = 0;i < n;i++){ for(j = 0;j < n;j++){ if (i == 0 || i == n-1 || i == n-j-1) elemen[i][j] = 1; else elemen[i][j] = 0; ... } ... } i = 0 gives you the top row i = n-1 gives you the bottom row i = n-j-1 gives you re...
64,733,333
64,733,344
Why does this very simple and little C++ program terminates with -1073741819 (0xC0000005)?
I have a simple class with a destructor. If I instantiate an object from it with default constructor, then the program terminates succesfully, but if I instantiate it with a constructor that has any parameter, it terminates unsuccesfully. #include <iostream> #include <list> class MyClass { public: std::list<int>* ...
MyClass graph1(); doesn't create an instance of MyClass, whether initialized with the default constructor or otherwise. Rather, it's a declaration of a function taking no parameters and returning MyClass. See also: most vexing parse MyClass graph2(3); does create an instance of MyClass. Its constructor leaves myList po...
64,733,661
64,733,942
Dynamic conversion from integer value to type (C++11 template metaprogramming?)
I am trying to reduce code duplication through templates. I already moved most code to this helper iterate_function_from_CSC_helper which is now a template. However, this function still repeats a lot of code just to call a different specialization of a template: std::function<std::pair<int, double>(int idx)> IterateFun...
Turning runtime value to compile time value requires indeed some if/switch like you did. You might avoid some duplication by additional split: C++17 might help reduce verbosity with std::variant, some utilities: template <typename T> struct type_identity { using type = T; }; // type should be an enum std::variant<type...
64,733,969
64,733,998
How do I specialize a member function of a template class?
template<typename _TChar> struct simplestring { void show_tstring() { throw "no implement"; } void simplestring<char>::show_tstring() { cout << "char string\n"; } void simplestring<wchar_t>::show_tstring() { cout << "wchar_t string\n"; } }; void test() { ...
Move the specializations outside the class body: template<typename _TChar> struct simplestring { void show_tstring() { throw "no implement"; } }; template<> void simplestring<char>::show_tstring() { std::cout << "char string\n"; } template<> void simplestring<wchar_t>::show_tstring() { std...
64,734,077
64,734,090
While loop creating infinite loop
So I'm creating a program for a C++ class, and I created a while loop to stop invalid inputs. Every time I do test it with an invalid input it goes into an infinite loop. I'm new to coding, so I really don't know how to fix it. cout << "Enter weight in ounces (Max: 1800)" << endl; cin >> pkgweight; while (pkg...
If nothing changes inside that loop, the exit condition will never be tripped. Maybe you mean: int pkgweight = 0; cout << "Enter weight in ounces (Max: 1800)" << endl; cin >> pkgweight; if (pkgweight < 0 || pkgweight > 1800) { cout << "Weight out of range. Program terminating.\n" << endl; } You'll want to use whil...
64,734,228
70,485,079
How to run c++ in atom with the atom script package?
I have a windows 10 computer with atom version 1.52.0 and g++ (MinGW.org GCC Build-2) 9.2.0. I can run c++ programs in Atom with the gpp-compiler, but I don't like how the program output is in a new window rather than at the bottom of the Atom window. I'm trying to set up c++ with the script package, but when I run the...
A bit late to reply. But for those to come here from Google, on the script package page, it clearly says: +---------+------------+-----------------+------------------+--------------------+---------------------------------------------------------+ | Grammer | File Based | Selection Based | Required Package | Required i...
64,734,694
64,734,765
Why do dynamic arrays have to geometrically increase their capacity to gain O(1) amortized push_back time complexity?
I've learned that dynamic arrays, such as std::vector, double their capacity when their capacity is reached to make the push_back operation O(1) amortized time. However, why is this needed in the first place? Isn't allocating space for one element at the end of the vector and copying the new element there already O(1)?...
If you want to allocate space at the end of the array, that only works if the memory at that location is available. Something else could already be there, or that memory could be unusable. So the way that resizing an array works (in general): Create a new, bigger array, Copy the elements from the original array into ...
64,734,695
64,742,641
What does it mean when gltf does not specify a skeleton value in a skin?
Reading the source code of tinygltf I see this: struct Skin { std::string name; int inverseBindMatrices; // required here but not in the spec int skeleton; // The index of the node used as a skeleton root std::vector<int> joints; // Indices of skeleton nodes Value extras; ExtensionMap extensi...
From the glTF specification, skin.skeleton is "the closest common root of the joints hierarchy or a direct or indirect parent node of the closest common root." Not all engines or authoring tools have a concept of a "root" in the joint hierarchy, so it isn't required, but if your loader needs one you can simply choose a...
64,734,987
64,735,003
Why str.length() is output as a char?
Here is my c++ code: #include<bits/stdc++.h> using namespace std; int main() { string str1; cin>>str1; int j=-1; cout<<typeid(str1.length()).name()<<endl; cout<<(j>str1.length())<<endl; int len=str1.length(); cout<<len<<' '<<(j>=len); } I input: abc And the outcome is: j 1 3 0 As can be s...
I wonder why this is the case typeid(str1.length()).name() is j Because that is how your language implementation happens to mangle the type name. On my system it is m. To be clear, the type is same as std::size_t which is alias of an unsigned integer type. and -1>str1.length() This is because, being a negative numb...
64,735,071
64,735,801
How to separate variadic template arguments while printing to the standard output inside a function
#include <iostream> template <typename ...T> void print(T ...args) { (std::cout << ... << args); } int main() { print(1, 2.5, 3, "Hello, world!"); } Output: 12.53Hello, world! I want the output to be 1 2.5 3 Hello, World!, any help would be appreciated
You might do: template <typename ... Ts> void print(const Ts& ... args) { [[maybe_unused]]const char* sep = ""; (((std::cout << sep << args), sep = " "), ...); } Demo
64,735,149
64,735,198
Difficulty Understanding the Do-While Loop on C++
I am a few weeks into programming in C++, and I am having a hard time understanding the Do-While Loop. Specifically, I do not understand this piece of code #include<iostream> using namespace std; int main() { int sum = 0; int y = 0; do { for ( int x = 1; x < 5; x++) sum = sum + x; y = y+1; } whi...
From that, what I see, the the code goes into the do block, it sees the for loop, executes that loop 4 times, you then proceed to increment y, and then the process is done 2 more times. #include <iostream> using namespace std; int main() { int sum = 0; int y = 0; do { // the cod...
64,735,191
64,735,733
How do I turn the if else statements in this program to switch statements? Visual Studio 2019 C++
I've looked up examples of doing this but when I try to format the code like it, it doesn't work. Here is the program I want to convert. #include <stdio.h> double comp_tax(double salary); int main(void) { double salary, tax; printf("Input your annual salary >$ "); scanf_s("%lf", &salary); tax = com...
The sequence of if/else cases is the more natural representation. If the code must be coerced into a switch statement for whatever reason, the following could be one such possible obfuscation. double comp_tax(double salary) { double tax = 0; double ks = salary / 1000; switch((ks > 0) * ((ks < 15) + (ks < 3...
64,735,444
64,741,404
trying to draw Pac-man
I'm trying to draw Pac-man as part of an assignment using the convex shape class in SFML and I always get an extra piece drawn from the point 0,0 #include <SFML/Graphics.hpp> #include <iostream> using namespace sf; using namespace std; #define PI 3.14f #define Deg2Rad PI/180 ConvexShape Pac(float radius, Vector2f cente...
Your for loop only iterates 270 times (315 - 45), therefore only setting 270 out of 315 vertices. The other 45 vertices are at the default position of (0, 0). Your next issue is that you do not create a vertex at the center. So you need one extra vertice for the center. Once those two issues are sorted, the result is: ...
64,736,037
64,736,466
Faster way to extract close pairs from two arrays?
Suppose I have two random arrays of ints, say: int A[] = {484, 834, 591, 23, 174, 248, 147, 765}; int B[] = {659, 805, 12, 180, 771, 386, 354, 568, 710, 312, 6, 848}; I wish to find all close pairs respectively from the two arrays, where the difference between two ints are not greater than some fixed k like 50: (from ...
You might do in O(N log N) (+ number of resulting pairs (which might exceed N log N)): std::sort(std::begin(A), std::end(A)); // O(N log N) std::sort(std::begin(B), std::end(B)); // O(N log N) auto begin = std::begin(B); auto end = begin; for (auto v : A) { while (begin != std::end(B) && *begin < v - 50) ++begin; ...
64,736,944
64,744,924
Using Waitable Timers with an Asynchronous Procedure Call
I have used MSDN's example from Using Waitable Timers with an Asynchronous Procedure Call to check how APC works in action. However, when I try to compile this source code, it doesn't compile, it gives me the following error: C4700: uninitialized local variable 'MyData' used What is wrong with this code?
If you use the sample in the link directly in C++, the following code will have an error (because C++ strictly matches the type of string). MyData.szText = TEXT("This is my data"); C2440 '=': cannot convert from 'const wchar_t [16]' to 'TCHAR *' So maybe you use the lstrcpy (or strcpy) function like this: lstrcpy(My...
64,737,881
64,738,090
Converting struct c ++ programs to c language
I'm working on a problem on the e-Olymp. I have solved the problem using c ++. Here is a program that I have created: #include <iostream> using namespace std; int m, MOD = 1000003; struct Math //Deklaraasi struct dengan MOD { long pow_mod(long a, long p) { if (a >= m) a %= MOD; if (a == 0) re...
To translate your C++ code to C, you mainly need to change the member functions to regular functions, which take the struct they would act on as an argument instead. On example would be changing void reset() to void reset(BST* bst) and inside that function root by bst->root of course you can use references instead of...
64,737,903
64,738,985
How to find if there's a cycle within selected nodes in a directed graph?(C++)
I'm currently working on a problem of finding cycles consisted of selected nodes in a directed graph. For the instance described here: there's a cycle within node 1, 2, 3, and no cycle is found within 1, 2, 4. I've tried to implement the algorithm myself with the following operation: Start with the first node within ...
Your implementation is a DFS, but will fail for "side nodes" that do not create a cycle: Consider the graph with 3 nodes (A,B,C): A / \ / \ V V B <---- C Your algorithm will tell that the graph has a cycle, while in fact - it does not! You can solve it by finding Strongly Connected Compone...
64,737,937
64,738,418
Bad code readability when using callbacks for network async receiving data
I'm developing the client protocol in C++ using my own network library. I created the method for asynchronous receiving data from server. It's method gets callback to call when data receives. But I need to call async reading data nested in this callbacks. Example: this->Send(some_data1, some_data_length1); this->Async...
First, since this is tagged C++, make your API function accept a wide range of data range rather than the old C idom of pointer + length. Make it possible for the user code to be as wild as the following: std::vector<unsigned char> v; std::array<unsigned char, 42> a; std::string str; std::span<int> s; // ... your_api.S...
64,737,968
64,738,022
Issue with template template parameter in function template
I am trying to use a template template parameter and my code will not complile. template<class DataType, template<class T> class Container> void foo(Container<DataType> test) { } int main() { std::vector<int> testVec{1,2,3,4}; foo<int, std::vector>(testVec); } The error message is "No matching funct...
Suggestion: try with // ...............................VVVVVVVVV template<class DataType, template<class ...> class Container> void foo(Container<DataType> test) { } The problem is that std::vector accept two type template parameters; the second one with a default value. If you write // .............................
64,738,049
64,738,089
Segmentation fault by using MPI_Scatter and MPI_Gather
I was trying to calculate elementwise multiplication of matrix elements. But I've got this error and don't know what to do. =================================================================================== = BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES = PID 16855 RUNNING AT kevlinsky-PC = EXIT CODE: 13...
I think this is your error: for (int j = 0; j < n; i++) { arrayA[i][j] = (rand() % 1000) - 500; } You need j++ in this loop. And you have this error in two places. j is never incremented and stays 0, and i is incremented indefinitely (because the condition for the loop is based on j), so very soon you go out of bo...
64,738,453
64,739,345
C++ makefile does not compile
Apologies for such a beginner question, but I have been stuck on making Makefile work on my c++ files for quite a while My makefile contains two .cpp files and one .h files and are as follows example.o: example.cpp example.h g++ -c example.cpp main.o: main.cpp example.h g++ -c main.cpp main: main.o example.o ...
Please show the output of make including the compiler lines that were invoked, not just some of the error output. Also it would be helpful if you provided at least SOME of the symbols that were not found so we could get an idea of what is missing. There is no reason from the info you've provided why this should happen...
64,738,610
65,061,851
How to match only variadic templates with a template template parameter?
Consider the following code: #include <iostream> template <template<class...> class C> struct foo { foo() { std::cout << "base case\n";} }; template <template<class> class C> struct foo< C > { foo() { std::cout << "single param case\n";} }; template <template<class,class> class C> struct foo< C > { foo()...
We can determine whether a class template that can be instantiated with 0 template arguments is genuinely variadic or (merely) has defaults for all its non-variadic template arguments, by counting the arguments to an 0-argument instantiation: template<class> constexpr unsigned argc_v; template<template<class...> class ...
64,738,644
64,738,877
Why doesn't my singleton implementation compile? (C++)
I am new to C/C++ I tried to implement singleton-pattern. why doesn't following code not compile. In javascript there is no problem implementing the singleton pattern in a similar fashion. (https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript) I thought that when I declare the poi...
There is no need to explicitly declare your static instance as a member variable. you could also do : class Grammar { public: Grammar() {} Grammar(const Grammar&) = delete; Grammar& operator=(const Grammar&) = delete; static Grammar& Grammar::getInstance() { static Grammar instance; retu...
64,738,830
64,738,987
Assign different values to different struct variables using loop
I have a struct of Examinee like below (each has 1 id and their scores of different subjects): struct Examinee { string id; float math, literature, physic, chemistry, biology, history, geography, civic_education, natural_science, social_science, foreign_language; }; Now i want to write a function tha...
I'd change the design of Examinee. Something along these lines: struct Examinee { enum Subject {kSubjMath, kSubjLiterature, ..., kSubjForeignLanguage, kSubjCount}; string id; float scores[kSubjCount]; }; This way you can access scores in a loop, e.g. for (int subj = 0; subj < Examinee::kSubjCount; ++subj) { exa...
64,739,274
64,739,403
What is the difference between std::invocable and std::regular_invocable concepts?
What is the difference between std::invocable and std::regular_invocable? Based on the description from https://en.cppreference.com/w/cpp/concepts/invocable I would expect that the std::regular_invocable concept doesn't allow to change the state of of the function object when it is called (or at least the result of the...
From the reference: Notes The distinction between invocable and regular_invocable is purely semantic. This means that there is no way for the compiler to enforce the distinction through the concepts system, since that can only check syntactic properties. From the introduction to the concepts library: In general, onl...
64,739,491
64,739,752
How do we understand the Iterator for a set<pair<int,int>>?
So I have declared a set which will hold a pair of integers. What is temp ? Does it mean that temp will point to a pair<int,int> ? set<pair<int, int>> myset; pair<int, int> temp = *(myset.begin()); How is the code below different from the code above? Can I please have a definition of what exactly these codes are doing...
In this code: set<pair<int, int>> myset; pair<int, int> temp = *(myset.begin()); the variable temp is a pair, holding two int's. myset.begin() returns an iterator, pointing to the first element in the set of pair's named myset. It gets dereferenced by * and the value (the pair) gets copied into temp. In this code: pa...
64,739,869
64,739,993
Why is the output 0 (=false)?
I'm exercising opreators in C++ and I don't understand the output of the code bellow int x = 21, z = 33, y = 43; cout << (!(z < y&& x < z) || !(x = z - y)) << endl; I wrote it with the thought to be true and I understand it as "it's not the case z is less than y and x is less than z (which is false) or it's not the ca...
The part that you misinterpreted: !(x = z - y)) x = z - y is assignment. It yields -10 as result. -10 is not 0, hence negating it yields false. Now, first part of the expression: !(z < y&& x < z) !(33 < 43 && 21 < 33) !(true && true) !(true) false Putting it together: (false || false) == false
64,739,961
64,741,336
How can I impose my own custom style on function parameter wrapping and alignment in clang-format?
Following on from How can I align function parameter names in clang-format?, I'd like to be able to do the opposite. In other words, this: void ReallyLongFunctionNameWithLotsOfParams(Type param1, Type param2, Type param3, Type param4, Type param5, Type param6, Type param7, Type param8, Type param9) { ...functio...
Add the following setting, AlignAfterOpenBracket: DontAlign, to your .clang-format file. If you want to control the size of the indent (for example, using 8 instead of 4), you would also need to provide a value to ContinuationIndentWidth.
64,740,020
64,740,229
Returning Vs. Pointer
How much would performance differ between these two situations? int func(int a, int b) { return a + b; } And void func(int a, int b, int * c) { *c = a + b; } Now, what if it's a struct? typedef struct { int a; int b; char c; } my; my func(int a, int b, char c) { my x; x.a = a; x.b = b; x.c = c; return x; } And void...
If the function can inline, often no difference between the first 2. Otherwise (no inlining because of no link-time optimization) returning an int by value is more efficient because it's just a value in a register that can be used right away. Also, the caller didn't have to pass as many args, or find/make space to poi...
64,740,021
64,740,050
Interdependent classes in C++
Say I want to implement two classes in C++, where each class contains a function returning an instance of the other class: class A { ... B fun1() { B b; return b; } } class B { ... A fun2() { A a; return a; } } How can I do it? I have tried forward declaring both classes and having prototy...
You need to forward declare the classes and the member functions that return them (since you can't return an incomplete type) class B; class A { ... B fun1(); // Cannot define since B is not a complete type yet }; class B { ... A fun2() { // A is complete, so you can declare and define the member functio...
64,740,098
64,740,811
Exercise to verify if a word == it's reverse
I've come into some problem with my code. At a first glance, it seems that I've done everything right and the code should work. But, it isn't. This exercise asks me to verify if a word is equal to it's reverse. This is my code: #include <iostream> #include <cstring> using namespace std; int main(){ char cuv[255], ...
This method works fine, I've gave up trying to compare the words, so I compared the word's letters from start with those from the end. #include <iostream> #include <cstring> using namespace std; int main(){ char cuv[255]; cin>>cuv; int n = strlen(cuv); int k = 0; for(int i = 0; i!=strlen(cuv)/2;i++) ...
64,740,101
64,740,173
How to subtract smallest element from sum of array elements
For each test case t, I need to input n, the number of elements in an array, and input those elements. Then I have to subtract the smallest element in the array from the sum of all the other elements. Here is my code, but I keep getting TLE: #include <bits/stdc++.h> int main(void) { int t; std::cin >> t; w...
In this if statement if (a < k) { you are comparing each entered value with the current value of k and if it is less than k you are not adding it to sum. For example for this sequence of numbers 20 16 8 2 13 20 is less than the initial value of k. So now k is equal to 20 and the number is not added to sum.. The next ...
64,740,256
64,740,282
Recursion in the main function
I tried recursion in the main function, but why 'i' variable is not getting updated, it only gets updated till i=1 and then remains constant. Below is the code:- int main(int i = 0) { std::cout << "i value" << i << std::endl; if (i == 3) return 0; std::cout << "hello" << std::endl; main(i++); } ...
See for example cppreference/main_function: The main function has several special properties: It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken [...] You cannot call main recursively. Also your signature is not correct. Correct signatures are...
64,740,268
64,743,191
how to search a QString in QVector
I have been trying search an id a string saved in QVector like this QVector<QString> logMessages; logMessages.append("1- Message"); logMessages.append("2- Message"); logMessages.append("3- Message"); logMessages.append("4- Message"); I have tried to use the find but it didn't work with me, the IDE doesn't show any...
The problem The iterator not being accessible, probably means the iterator points to the end of the vector, i.e. the element is not being found in the vector. The solution The problem is that std::find, searches an exact match, i.e. it uses the QString::operator == (const char *) (see Comparing strings). You are lookin...
64,740,749
64,740,961
reference to 'end' is ambiguous when using std ranges
when I try to compile following code: // This file is a "Hello, world!" in C++ language by GCC for wandbox. #include <iostream> #include <cstdlib> #include <ranges> #include <vector> #include <numeric> #include <cmath> template <typename T> struct Foo { std::vector<T> vec; auto begin() { return vec.begin(); } ...
std::ranges::begin is not a function; it is a function object. You cannot specialize it or redefine it. This is deliberate. The old standard method of specializing begin/end in the std namespace is not how Ranges works, and it was designed specifically to stop you from doing that. The way you make a range is by definin...
64,740,833
64,748,886
C++ error: no matching constructor for initialization of "my:Library" with Clang 11.0.3
I have been several post with something similar to my problem but I can't figure out how to solve it in my implementation. It's about a custom exception classes that compile perfectly in Linux with gcc 9, but in MacOs (Catalina) with Clang 11.0.3 fails dramatically. Here is the code: #include <stdexcept> ...
It looks like your compiler is complaining that it won't automatically convert the hardcoded string "Division by near-zero value" that you provide to the constructor of Exception from const char* to const std::string&. I have no access to macos at the moment but my guess is that you could fix it by constructing a std::...
64,740,886
64,744,035
how can i make my code show this output im new to smfl and codeblock
how can i make my code show this output im new to smfl and codeblock i dont know how to call sprite and make it move me and my friend are confuse during this pandemic online classes are hard :( this is the output #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <SFML/Window.hpp> cl...
First you need to load the texture. sf::Texture texture; texture.loadFromFile("ship.png"); Do not delete the texture. It has to exist for you to use it. Next you need to create a sprite using the texture. sf::Sprite sprite(texture); Remember to draw the sprite, this is done in the same way you draw the player. You ca...
64,740,912
64,741,063
Converting for loop into recursion (c++)
So i want to convert this for loops (printL, clearL) into recursion. I need to make recursion named printList, clearList. And i'm not allowed to use loop. Please help i'm kinda new to c++ and have no idea how to even start on this. Here's the full code. #include <iostream> using namespace std; struct Node { string...
It's simple enough to print a list recursively. If the list is empty do nothing Otherwise, a) print the first item on the list, b) print the rest of the list 2b is the recursive part, your printList function calls itself to print the rest of the list. This is how you use recursion to do loops. Putting that into cod...
64,741,251
64,741,393
Assigning a class member function to a map, in the constructor
I have a class member function that needs to call other class member functions depending on an integer value, like this: class foo { public: foo() { mTestMap[1] = (*this).test1; mTestMap[2] = (*this).test2; mTestMap[3] = (*this).test3; } bool test1 () {} bool test2 () {} b...
std::function<bool()> This std::function wraps a callable object that takes no parameters and which returns a bool. That's what this means. bool test1 () {} You'll be surprised to learn that this is really not a function that takes no parameters and which returns a bool. It is a class method that takes no parameters ...
64,741,655
64,741,832
Getting all possible combinations of an integrer array in C++
I have an array of integers, for example: a[1,2,3]. I would like to get all possible combinations of these numbers where they don't repeat, possibly with recursion. I saw something like this done with strings here: Get all combinations without duplicates but don't know how to adapt it to integers without using any stan...
You can achieve all permutations of a list with comparable elements using std::next_permutation from <algorithms> library. The cppreference has a nice article about this: https://en.cppreference.com/w/cpp/algorithm/next_permutation We can use the code example to apply to your question. #include <algorithm> #include <st...
64,741,757
64,742,050
Is there a way to update enum variables with new states in C++?
I want to know if there is a way to update an enum variable in C++ giving the program new states dynamically. For example, I create a void enum variable for the days of the week, and then, I want to let the user enter the days to update the enum variable.
For example, I create a void enum variable for the days of the week, and then, I want to let the user enter the days to update the enum variable. No, that's not how enums work in c++. They are only a fixed set of numerically representable values, where that set is completely defined at compile time. Enumerated values...
64,741,854
64,746,872
accessing std::shared_ptr<std::map<>> without using "get"
I think this is a standard question but still I'm unable to find a solution or this. I might be missing something very basic. All I want to do is to access (read only) the data within a std::shared_ptr<std::map<int, int>>. The only way I could find is to actually get the object beneath the shared pointer and use it as ...
I think the API I am looking for is at() as I can use this API directly on the pointer (irrespective of whether the map is const or not) auto& someMap = *(tmap.get()); // get the reference to the map instead of copy. try { // either use reference to be able to modify the non-const map // or use the "at" api to ...
64,742,225
64,742,790
What's the difference static or inline in C++
I'm new to C++, I'm confused about static and inline. What I want to do is defining a global counter. I test it on the code as below (it is just a skeleton to illustrate the idea) // in main.cc #include "T.h" int main() { runFuncInT() ; cout << "# of trans is " << trans_cnt ; return 0; } // in T.h static size_t...
In C++17 you should declare your variable in the header as inline: inline size_t trans_cnt = 0; From https://en.cppreference.com/w/cpp/language/inline: since C++17: Because the meaning of the keyword inline for functions came to mean "multiple definitions are permitted" rather than "inlining is preferred", that meani...
64,742,263
64,742,643
Vector of shared_ptr of an class C++
as the title says I want to declare a vector from shared_ptr of a class. This is class member. Deklaration of class header: std::vector<std::shared_ptr<connection>>RemoteVerbindungen; usage in the class: RemoteVerbindungen.push_back(std::shared_ptr<connection>(new connection(SERVICE_SOCKET))); //Iterator pos...
You should prefer std::make_shared() instead of using new manually: std::vector<std::shared_ptr<connection>> RemoteVerbindungen; ... RemoteVerbindungen.push_back(std::make_shared<connection>(SERVICE_SOCKET)); And, prefer auto when declaring and initializing the iterator in the same statement: auto VerbindungsNr = Remo...
64,742,296
64,742,603
Expanding on where put put a critical section when dealing with loader threads and large amount of data
I've read tutorials on the subject and watched YouTube videos on it and I think I understand the reasoning behind why they are used. There are a lot of reasons why they are used, but one of the is because modern multi-core CPU's have internal caches to increase performance (L1 and L2). This might result in one core rea...
Your code is correct. The mutex is guarding the list and not the data contained withing the list node. Therefore, as you have written, the filling of the data into the Result struct is unprotected and does not need protection. When reading, only the list needs protection. The reading of the results do not need protecti...
64,742,334
64,742,454
Why is the first digit of a string still read and output in a while loop where the condition !isdigit is false?
Note: I know the solution that would solve the issue, but I don't understand the "computer logic," or what is going on behind the compiler. In my C++ textbook, there is a blurb of example code that reads: cout << "Enter a line of input:\n"; char next; while ((!isdigit (next)) && (next != '\n')) { cin.get (next); co...
As mentioned in the comments, you have to initialize next before using it, otherwise it is undefined behavior. Now lets assume, next is properly initialized to a non-digit character. The condition (!isdigit (next)) && (next != '\n') is checked once when you enter the while loop and every time when you reach the end of ...
64,742,472
64,750,570
Pybind11 - Casting a list of abstract-inherited class elements
I have one pure abstract class and 2 inherited classes where each contains a method called go as follows: // Pure abstract class class Animal { public: virtual std::string go() = 0; }; // First inherited class class Dog : public Animal { public: std::string go() override { return "woof! "; } }; // Second inhe...
The correct way to write call_go is void call_go(py::list animals) { for (py::handle animal : animals) { // wrong //std::cout << py::cast<Animal>(animal).go() << " "; // correct way std::cout << py::cast<Animal *>(animal)->go() << " "; } } Thanks to the pybind11 community at https://gitter.im/pybi...
64,742,487
64,742,618
Passing array data through textures in opengl
So i'm trying to pass a bunch of vectors to the fragment shader and apparently i should do it with a 1d texture. But if i try to access the passed vectors, the values are not what i expect. How should i index the texture() function? Passing the texture: std::vector<vec3> triangles; //triangles is already filled by this...
When using texture, the texture coordinates are floating point values ​​in the range [0.0, 1.0]. Use texelFetch to perform a lookup of a single Texel from texture with integral texture coordinates in the range [0, width): triangle.a = texelFetch(triangles, i*4, 0).xyz; triangle.b = texelFetch(triangles, i*4...
64,742,588
64,825,887
How to manage memory while reading CSV using Apache Arrow C++ API?
I don't understand memory management in C++ Arrow API. I use Arrow 1.0.0 and I'm reading CSV file. After a few runs of ReadArrowTableFromCSV, my memory is full of allocated data. Am I missing something? How can I free that memory? I don't see any method in memory pool to clear all allocated memory. Code Listing below. ...
Maciej, the method TableReader::Read should return shared_ptr<arrow::Table>. The arrow::Table itself has a number of shared pointers to structures which eventually contain the data. To free up the data you will need to make sure that the arrow::Table and any copies of it are destroyed. This should happen as soon as ...
64,742,615
64,742,705
Overloading << operator: struct with vector of structs
Overloading << for vectors works. Overloading << for custom structs works. The combination works as well. But if I use the << operator on a struct with a vector of structs, compilation fails. I made up a little example to showcase the problem: #include <iostream> #include <ostream> #include <vector> template <typena...
In the main function, when you write this line: std::cout << agg.items << std::endl; the compiler will look in the global namespace for all overloads of operator<<. The correct overload is chosen via overload resolution, and so the call works. When you write the similar code here std::ostream& operator<<(std::ostream&...
64,742,725
64,742,815
Segmentation fault - trying to pass matlab code to c ++
I'm trying to pass a code that is in matlab for c ++ but it is giving segmentation fault (core dumped), can someone help me please? Code in MATLAB function strip = strips(strip,n,number_pixel) se = strel('square', 3); strip=imdilate(strip, se); strip = imfill(strip); [m1,n1] = size(strip); vet=0; for j=1:n1 for...
It is very hard to tell what the problem is, when not having a fully working example. One obvious problem with your code is, that you use j uninitialized in your second loop: for (int i = 0; i < n1; i++){ int j; if (v[i] < limite){ strip.at<uchar>(i, j) = 1; // <- uninitialized j is used } //...
64,742,878
64,754,728
How to implement BST functions insert() and split() based upon rank?
I am trying to figure out how to implement code to the functions of insert() (which inserts an element into the tree), split() (which splits the tree on rank r into two trees of L and R. L containing ranks < r and R containing ranks >= r. For this assignment, I am dumbfounded. I believe I have the code for my insert co...
I'm assuming we're dealing with unbalanced BSTs here (balance makes this harder). Splitting the null tree is trivial (return (null, null)). Given a non-null tree T, compare the rank of the root to r. If it's less, then recursively split the right child to get (R<, R≥) and return (T′, R≥) where T′ is T with the right ch...
64,742,972
64,743,050
Can va_lists in stdarg.h handle C++ references?
Can va_lists handle C++ references? I know they can handle ints, doubles and pointers, but not floats, chars, etc. Can they handle C++ references?
You should #include <cstdarg> rather than <stdarg.h>... If the caller provides a reference as an argument to such a function, the call will work the same way as if the referenced object was specified directly. For example, if you have: void f(...); T my_t; T& x = my_t; f(my_t); f(x); The values passed in registers an...
64,743,152
64,743,237
How to use a template to create two very similar member functions in C++
I am coding a C++ library and one class has two member functions that only differ in one function call: int MyClass::member_func_1(int a) { // ... int b = some_function(); // ... } int MyClass::member_func_2(int a) { // ... int b = some_other_function(); // ... } Is there a way of not having to dupl...
A template solution is only a good solution if the call to either of the member functions is executed in a tight loop, where the overhead of testing a boolean or making an indirect function call would be too costly. In this case, if C++17 standard is an option, the if constexpr syntax is probably the simplest way. Like...
64,743,666
64,744,679
Why using QQuickWindow::grabWindow() causes a window to turn into an image?
I have a QQuickWidget and want to grab a screenshot using QQuickWindow::grabWindow(). However when I do that the QQuickWindow becomes an image and is not responsive. Below is a minimal reproducible code: The bug is reproducible in Qt5.13 to Qt5.15.1 in release mode (for some reason Qt throws an assert in debug) //TestW...
QQuickWidget uses a non-visible QQuickWindow to render the items, and that rendering is rendered again in the QWidget, so when trying to save the image it interferes, causing the lag as I have already pointed out in this post. A possible solution is to grab directly from the QQuickWidget: #ifndef WINDOWGRABBER_H #defin...
64,743,992
64,744,075
How to use a linked list when working with a class
So I have a class named Student and I have to make a list of students using linked lists. Below you have my code: #include <string> #include <iostream> using std::string; using std::cout; using std::endl; class Student { private: int grade; string name; public: Student(int grade, string name) { ...
When we compile your code (GodBolt.org), we get: <source>:44:28: error: use of deleted function 'Node::Node()' 44 | studentList = new Node(); // Reported error at this line | ^ <source>:25:7: note: 'Node::Node()' is implicitly deleted because the default definition would be ill-f...
64,744,092
64,744,664
C++: Datatype of a "number constant"
I had in mind the numeric constant in C++ (and also in C) have a datatype assigned. When these constants are an operand the datatype can influence the result and the result's datatype. I know the datatype depends on the constant itself like 5 or 5.0 5.0f and it depends on the architecture/compiler. But I don't know the...
It sounds as though you're conflating the concept of "data type" with the size of the underlying type -- which are two different things. The type of an expression is fixed and well-defined in C++. All literals have a fixed, well-defined underlying type, whether they are integral literals, floating literals, boolean li...
64,744,100
64,744,143
why doesn't the 'all_members' variable change after adding 1 to `man`?
I just started programming and I started with C++. I'm learning about variables and was practicing. I added two variables together and then added 1 to one of them (man). After that, I wanted to show them added together (all_members). But it doesn't count in the +1 I included. How can I solve this ? #include <iostream> ...
This line: int all_members = man + women; initializes all_members with the value of man + woman, with the values that man and woman have when this code is executed. If at some later point, you change the value of either man or woman, this has no effect on the value of all_members. If you want the value to change, you ...
64,744,576
65,175,261
Incomplete WEBKITGTK build
I am running buildroot on a fedora32 machine. I enebale the webkitgtk package. Downloading and configuring of the source runs with no errors However, when during the build process, make throws an error and crashes. I am fiarly new to linux and GTK and will gladly appreciate some pointers to exactly what is wrong. below...
UnifiedSource build errors are relatively common in trunk. Usually the issue is a missing header in some of the source files referenced by the affected unified source file, in this case UnifiedSource-3c72abbe-28.cpp. You mentioned the build error is happening in WebKitGTK 2.30.2 tarball. To fix the error you can try se...
64,744,588
64,744,703
Mutex in a class added to map doesn't work c++
I am trying to get a map of an int to a class. For some reason when I run the code it doesn't compile. The code is below. #include <iostream> #include <mutex> #include <map> using namespace std; class test { private: mutex thismutex; public: test(){ }; ~test(){ }; }; int main() { ...
A std::mutex is not copyable or movable. This means that your class, which has a mutex as a member, does not have a default copy constructor. Which makes its use somewhat limited with most containers, including a map. That's the reason for your compilation error. You're trying to create a new entry in a map in a way th...
64,744,631
64,744,808
Deducing template parameters from std::function
I'm writing a little class using a static template member function trying to map a std::function with its parameters : class test { public: template <typename R, typename... Args> static double exec(std::function<R(Args...)> func, Args && ... args) { func(std::forward<Args>(args)...); // do some...
The compiler can't deduce the std:function arguments and return type, because you are not passing exec a std::function at all. Instead of a std::function, you can just make exec accept an arbitrary type of callable (which includes functions), and let the compiler deduce its signature: template <typename Func, typename...
64,744,916
64,744,978
How to resolve this issue with variadic non-type template parameter in C++11?
enum Enum { e0, e1, e2 }; int translate(Enum e) { //... } int translate(Enum e, int index) { //... } class A { public: template<typename... Ts> A(Ts... ts) { //... } }; template<Enum... es> class B { public: static std::shared_ptr<A> getA() { //for exampl...
Here's a solution using std::integer_sequence. It's a C++14 feature, but ports to C++11 do exist (haven't used this, can't vouch for its quality). template<Enum... es> class B { template <int... Is> static std::shared_ptr<A> getAHelper(std::integer_sequence<Is...>) { return std::make_shared<A>(translate(es, Is)...
64,745,113
64,745,175
Why I can't implement linked list on stack memory instead of heap?
struct node{ int data; node* next; } int main(){ Node *head; head->data = 999; Node *new_node; new_node->data = 1; head->next = new_node; cout << (head->next)->data; } This code doesn't work. If I use allocation, it works. I try searching on Google but no one ask about this. My code based on my understand a...
When you create Node* You are creating a node pointer not a node. This is just a variable that will hold a memory address, and that memory address will hold a node. Since you aren't allocating any memory there isn't actually a node to use when you use the -> operator. Basically its not going to work in your code becaus...
64,745,693
64,745,724
Why is copy assignment called but not move assignment?
Here are my test class. VTX has both copy assignment and move assignment. VTZ has a constructor that takes VTS&& to initialize its vtx memeber. struct VTX { int x; vector<int> vts; VTX & operator= (const VTX & other) { x = other.x; vts = other.vts; cout << "copy assignme...
Because vvv is an lvalue expression (even its type is VTX &&). Types and value categories are different things. The following expressions are lvalue expressions: the name of a variable, a function, a template parameter object (since C++20), or a data member, regardless of type, such as std::cin or std::endl. Even if ...
64,746,392
64,746,835
What does using ::fun mean when fun is a function?
void fun(){ std::cout << "hello" << std::endl; } namespace enc{ using ::fun; } This code above gives no error. I want to understand what's going on here. What does using ::fun; mean?
Breaking this down we have: void fun() is a function that does not return a value (essentially nothing). :: is a scope resolution operator. For example, cout and cin are defined in the std namespace. To qualify their names without using the using declaration we have to qualify them with std::cout and std::cin To an...
64,746,762
64,747,054
Convert hex string to unsigned char in C++
How can I convert it? And I want the converted result to 1. #include <iostream> #include <string> int main(int argc, const char * argv[]) { std::string s = "0x00"; // insert code here... unsigned char* str_hex = (unsigned char*)s.c_str(); unsigned char target = 0x00; std::cout << "result:...
Like this: // #include <string> std::string s = "0x4A"; unsigned char ch = std::stoul(s, nullptr, 16); // 'J' (Since C++11) Or like this: // #include <cstdio> std::string s = "0x4B"; unsigned char ch = '\0'; sscanf(s.c_str(), "%x", &ch); // 'K' (C library function)
64,746,871
64,747,116
Comparator function in Priority Queue
I'm trying to understand how the comparator function return value determines which element goes before the other when inserting into a Priority Queue. Below code stores integers in the descending order based on a comparator function. I understand that I do not need a comparator function for this simple evaluation, but ...
Whenever an entry is pushed into pq, does it always become b element in compfunc? No, that is entirely implementation defined. What the standard guarantees is that the elements in the priority_queue are sorted in descending order, where the "order" is defined by the Compfunc compare function being used. In order to...
64,747,235
64,747,405
How to convert hexadecimal value to integer in c++?
I am having the hexadecimal value in unsigned char and i am not finding any way to change this hexadecimal value as integer. Please assist on this. unsigned char c = '0x01'; int convertasint = (int)c;//not working int convertasint1 = (atoi)c;//not working Please guide me how to achieve this.
unsigned char variables are integers already (so are char). You don't have to do anything special to convert them. This code works unsigned char c = 0x01; // assign integer to unsigned char int convertasint = c; // now assign to int cout << convertasint << '\n'; // this prints 1 Also please note that hex...
64,747,308
64,747,527
WaitForMultipleObjects and 2 Events when bWaitAll = true
I want to get something done after 2 events are set off; however, I am not sure what WaitForMultipleObjects will return when both events are set off. This is what I have at the moment: if (WaitForMultipleObjects(2, lpHandles, TRUE, 0) == ___) { do stuff } else { continue } What am I supposed to place in the ...
When bWaitAll is TRUE then a return value of WAIT_OBJECT_0 indicates that all passed handles are in the signaled state. You only get a varying object indicated when bWaitAll is not TRUE so that WFMO returns with only one object signaled.
64,747,574
64,756,768
How does QT display minority language strings as they are
I am using QT creator writing a program (under Windows) to read the string in the text file. There is a string in Spanish: explosión demográfica, in which there are letters like ó. The QT program won't show it on the label correctly. I used tr() directly, but it didn't help. Neither QString::toutf8(). I also want to us...
For anyone interested in this extraordinary mojibake case: Ó Latin Capital Letter O With Acute (Unicode U+00D3, utf-8 byte sequence 0xC3, 0x93) 脫 CJK Unified Ideograph (GBK C393) 脫 CJK Ideograph-812B (Unicode U+812B) The mojibake mechanism is self-explained in the following Python script: print( 'Ó ->', 'Ó'.encode(...