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
61,690,762
61,691,902
How do you recursively merge queues in C++? Assume they are already sorted
I made a function that merges two sorted queues. Queue<int> merge(Queue<int> a, Queue<int> b){ Queue<int> result; while (!a.isEmpty() && !b.isEmpty()) { int a1 = a.peek(); int b1 = b.peek(); if (a1 < b1) { if (! result.isEmpty()) { if (result.back() > a1) { error("queue ...
An explanation of why your code gives the results you see. The first call to recMultiMerge has 6 queues. left will be the first three ({3, 6, 9, 9, 100}, {1, 5, 9, 9, 12}, {5}), and right will be the last three ({}, {-5, -5}, {3402}). Then you make a recursive call with left. In that call, all.size() will be 3. left...
61,691,116
61,691,409
I have some trouble with fwrite() and fread()
#define ARRAY_SIZE 10 #include <iostream> using namespace std; int main() { // create array mas1 of ARRAY_SIZE integers and fill it with random values int array1[ARRAY_SIZE]{ 10, 78, 23, 81, 50, 15, 24, 26, 90, 59 }; // write ARRAY_SIZE integers from array1[] to f1.txt FILE* f1; fopen_s(&f1, "f1....
Modify your fwrite as fwrite(array1, sizeof(int), ARRAY_SIZE, f1); And fread as fread(array2, sizeof(int), ARRAY_SIZE, f1); fclose(f1)
61,691,156
61,691,206
Pointer arithmetic - how does the compiler determine the number of bytes to increment?
Consider the following piece of code. #include <iostream> int main(){ int a[] = {1,2,3,4,5}; int b = 5; std::cout << a[b] << std::endl; std::cout << b[a] << std::endl; } I understand that a[b] and b[a] are identical, as specified by the standard: Except where it has been declared for a class (13.5.5), the s...
It is not the size of the object that's the determinant type. It's the actual, complete type of the object. The compiler knows the actual type of every object. The compiler knows not just that a is four bytes (or eight bytes on a 64-bit system), but it's a pointer and b is an integral type. This is a fundamental aspect...
61,691,166
61,694,617
Does this example warrant the use of public inheritance
I'm trying to implement a library where Class1 provides about five public methods Method1 to Method5. Class2 provides two methods - Methods6 and Method7. And Class3 provides one method - Method8. Now, for the end user, I want to expose methods from combination of these classes. E.g. If the end user instantiates a class...
As you want easy combination, you might use template as variant of your first proposal: template <typename ... Bases> struct Derived : Bases... { }; using Class1Class2 = Derived<Class1, Class2>; using Class1Class2Class3 = Derived<Class1, Class2, Class3>;
61,691,451
61,784,975
Arduino (c++), How to read bytes from Sockets (WiFiClient)?
A server in java, sends from a Server socket a byte array, this byte array contains text (utf-8) with the next format: first 4 bytes: an int with the number of bytes of the text next n bytes: each byte represents a char. So i am using "WiFiClient" from the "ESP8266WiFi.h" library (it should be the same as "WiFi.h" ...
I fix it, i had problems with the way I read from the socket, the way I transform the 4 bytes into an Int datatype and with the way I transoform the bytes into a String, I figure out why i was not receiving all the bytes when trying to read from the socket, the reason was that when I call the method "client.read()" the...
61,691,643
61,749,295
Python fails to load C++ library even though PyInit_ entry exists
I am trying to load a CUDA library compiled from source into a Python program. On my Windows machine, it successfully loads the code. However, on my university's Unix computer cluster, it fails with the error: ImportError: dynamic module does not define module export function (PyInit_deform_conv_cuda) I have locate...
I would never have guessed this and I feel kind of stupid. The problem was that I installed the library into one Python environment and tried to run it from another. I'm posting this in case someone else makes this mistake. The error message wasn't at all helpful int this case.
61,691,924
61,733,192
Why does a shape not render when looking directly down on it from above?
I've tweaked tutorial04.cpp a bit from http://www.opengl-tutorial.org/beginners-tutorials/tutorial-4-a-colored-cube/ I've made a pyramid shape and I wanted to place the camera above the pyramid and look down at it, but what I found is when the camera is directly above the pyramid it doesn't render at all. If I change m...
You're not the first one to fall for this effect though: link There're two solutions: either don't use lookAt function at all and represent your camera's rotations with a quaternion; or track and never apply a "straight up" (0,X,0) or "straight down" (0,-X,0) looking direction for your camera. What is the problem ex...
61,692,147
61,692,186
Does C++11 support variable sized arrays?
I'm very new to C++, but I've been digging around and the general answer is no, c++11 does not support variable sized arrays, since array sizes need to be constant expressions. However, I've tried this code on XCode 11 (C++11): #include <iostream> using namespace std; int main(int argc, const char * argv[]) { u...
That is non standard C++. Some compilers accept it, but if you want to be portable you should stick with standard C++.
61,692,211
61,692,394
QPixmap not displaying on the dialog in Qt
I am trying to display a pixmap onto a window but for some reason it would not display this time (I have done it before but cannot pinpoint where I went wrong).
Turns out when I displayed the pixmap before I instantiated in a ResizeEvent rather in the Widgets constructor. pixRecieve=QPixmap(size()); pixRecieve.fill(); But this time I did it in the constructor since I do not need a ResizeEvent in this widget. In order to construct the QPixMap you need to input the size of th...
61,692,228
61,692,498
sfml put a sf::View on top of the defaultVeiw
I am trying to make a project that requires manipulating a view displayed on top of another view. I would also like to make it so where that view is displaying nothing it is transparent. When trying to do this it doesn't draw my overlaying view. I've read through the tutorial and looked through some popular forum websi...
You should set your view before you draw to mainWindow. Becuase of the loop you're actually drawing projectsBox through the default view and randomBox through the projectsView. while (mainWindow.isOpen()) { mainWindow.clear(sf::Color::White); mainWindow.setView(projectsVeiw); mainWindow.dra...
61,692,318
61,710,983
Using the Windows Driver Kit (wdm.h specifically) functions in a Windows Desktop Application and/or Console Application
I have a necessity to use the ZwSetValueKey() function declared in the Wdm.h header file available as a part of the Windows Driver Kit (WDK) to access the registry keys created by a kernel mode driver but Visual Studio does not allow the use of the WDK headers as it fails to detect the required header file when include...
The wdm.h header file containing the ZwXXXX functions are unsuited for use in applications that do not run in the kernel mode (as mentioned here). The equivalent NtXXXX functions in winternl.h and Ntdll.dll, on the other hand, are accessible for use as a part of the Windows Native System Services routine by application...
61,692,320
61,692,405
Char variables as an input to a Y/N question
I'm asking the user if he/she wants a drink. The only answer the user can type is Y for yes and N for no then there comes the final dialogue. I made the answer a char: char answer; then added an if statement. If the user types Y or N, everything's fine. However, whenever the user types Y(+ any letter) such as YHTY, the...
cin will accept only the first letter of input as answer as the data type of it is char, I don't see any problem here, it should server your need. You can check above statement through below code: #include <iostream> using namespace std; int main() { char answer,a2; cout << "Do you wa...
61,692,495
61,692,593
Can You Explain This Void Pointer Inside Function Paramter?
Here is the code in question! I have not spent too much time with C++, and I'm implementing a Binary Search Tree. void BST::Preorder(void(*visit)(const Node *)) Later on the function is called like this: bst.Preorder(PrintNode) With PrintNode being implemented as follows: void PrintNode(const Node* n) { cout << ...
So Preorder is a function that will iterate through all the nodes in the binary search tree (in a particular order) and do something at each node. So it's useful to write Preorder in such a way that the caller of Preorder can specify what is to be done at each node. That is the purpose of the visit parameter. It's a fu...
61,692,602
61,692,795
How can i make the QSlider indicate the current value
I can't figure out from the QT Assistant how to set the QSlider to show the current value while dragging, I came with this idea initially: QLabel* lblYear = new QLabel(); QSlider* sldYear = new QSlider(Qt::Horizontal); QObject::connect(sldYear, &QSlider::valueChanged, [&]() { lblYear->setText(sldYear->value); }); ...
QObject::connect(sldYear, &QSlider::valueChanged, [](int value) { lblYear->setText(QString::number(value)); }); You need to convert int value to QString to be able to use it with setText. Also, capturing pointer by reference is not always safe and it also doesn't make sense, since it is as cheap as capture it by v...
61,693,021
61,693,356
Disthinguish char and wchar_t in compile time
I have a template class simplestring which simplely handles TChar* and its length. TChar can be both char and wchar_t. Here is a simple left trim method, simplestring<T> ltrim(const T* _s = nullptr) const { const T* s = _s; if (s == nullptr) { #if ( sizeof(T) == 1) s = " \t\r\n"; #else s = L...
In C++17 you can use if constexpr: if constexpr (sizeof(T) == 1) // or (std::is_same_v<T, char>) s = " \t\r\n"; else s = L" \t\r\n";
61,693,232
61,693,332
Something really weird with C++ exp() function
When tying to implement mySqrt function in C++, I used the exp() function like this: int mySqrt(int x) { // For x = 2147395600 cout << exp(0.5*log(x)) << " "; // It prints 46340 return exp(0.5*log(x)); // But returns 46339 } I tried to google the reason for this behavior but could not fin...
With this code #include <iostream> #include <cmath> #include <cstdio> using std::cout; int mySqrt(int x) { // For x = 2147395600 cout << exp(0.5*log(x)) << " "; // It prints 46340 return exp(0.5*log(x)); // But returns 46349 } int main(void) { std::cout << mySqrt(2147395600) << "\n";...
61,693,324
61,693,537
Function hiding in c++
I was trying out few concepts of function hiding in c++. So here in the derived class I've used scope resolution operator using base::fun to provide scope of base class in derived class. My objective is to print cout<<" base "<< x; but the output only prints derived class cout. Any reasons why and how to solve? i.e it...
it should print both base and derived class value No. Only one function would be selected and called. Then the problem is that which one should be selected. In this case derived::fun is selected; because for using declaration, If the derived class already has a member with the same name, parameter list, and qualific...
61,693,513
61,867,349
Objective-C to C++ reading binary file into multidimensional array of float
I want to convert the following code from objective C to C++. In the class myClass, I have this attribute: float tab[dim1][dim2][dim3]; In an objective-C file, the multidimensional array is filled from a binary file: NSData *dataTab=[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pathOfMyTab" o...
I am assuming that your file contains the byte-representation of the array. If this is the case, then to mimic the behaviour of your Objective-C code using only C++ (the only thing that makes this C++ is the reinterpret_cast<>, otherwise it is just straight C), you could use the following code. I have not added any err...
61,693,583
61,693,595
Error with ofstream and ifstream being unidentified in Visual Studio 19
I'm trying to create a program using files and when I use ofstream or ifstream, Visual Studio says that ofstream and ifstream is undefined. Can someone please explain this? #include <iostream> #include <fstream> int main() { ofstream file("Test.txt", std::ios::app); file << "File successfully made\n"; ...
ofstream is in the namespace std, so you need to specify that. #include <iostream> #include <fstream> int main() { std::ofstream file("Test.txt", std::ios::app); // ofstream -> std::ofstream file << "File successfully made\n"; file.close(); return 0; }
61,694,458
61,695,096
QJsonArrays are not properly retrieved from QJsonObject
In the project I'm currently working on there I use Qt's JSON functionality to store the state of a graph, where every component of the system recursively calls the toJson-functions of its members for serialization. This works fine, but I run into a weird issue when deserializing the JSON file. As a test that illustrat...
Your problem is the brace initialization. When you do assignment-style initialization instead, it works. // instead of auto inner_1{inner_1_value.toArray()}; // use auto inner_1 = inner_1_value.toArray(); // same for all other brace inits What I think happens is the classic clash between brace initialization and list ...
61,694,467
61,694,512
C++ Object Instantiation - Which constructor is called when an object is instantiated using empty parenthesis
I am confused about the different syntax used for instantiating an object. This is my class: class Object { private: int field = 0; public: Object() = default; // Just for testing. ~Object() = default; // Just for testing. Object( const Object& obj ) = default; // Just for testing. }; This is ma...
All the three declarations are function declarations, but not variable definition (as you expected). Object b(); declares a function named b, which takes nothing and returns Object. Object f ( Object() ); declares a function named f, which takes a unnamed parameter whose type is a function returning Object and taking n...
61,694,501
61,695,222
Lifespan of smart pointer objects declared and initialized inside WndProc message (WM_CREATE)
If I declare and initialize object within main window callback function like so: LRESULT CALLBACK WndProc ( HWND hWnd // handle to window of this process , UINT msg // message constant , WPARAM wParam // holder of message parameters , LPARAM lParam // holder of message parameters ) { switch (msg) ...
Here's a workup of RbMm's suggestion, which I use myself in my own code. A smart pointer has little to offer here, so there's really not much point in using one. Please note that I have used C-style casts for brevity, but you can use reinterpret_cast if you prefer. class MyWindowData { ... }; MyWindowData *window_da...
61,694,731
61,694,880
What is the difference between vector_name, vector_name.begin() and (vector_name + vector_name.size()), vector_name.end()?
In this Example, they are using *max_element(vector_name.begin(), vector_name.end()); while here, they have used *max_element(vector_name, vector_name + 4); but when I use *max_element(vector_name, vector_name.end()); it throws this error: no matching function for call to ‘max_element(std::vector<int>&, std::vector<in...
In your first example, vector_name is a std::vector<int> vector_name.begin() and vector_name.end() returns a std::vector<int>::iterator or std::vector<int>::const_iterator depending on whether vector_name is const-qualified. vector_name + vector_name.size() is invalid, unless you define an operator+ for std::vector<in...
61,694,761
61,695,253
calling a class's non-static member from another class's static member
I have two classes; encoder.h #include "stationControl.h" public: static void getLocation(); static stationControl *station1; static stationControl *station2; static stationControl *station3; private: static stationControl *stations[3]; encoder.cpp #include "encode...
senarioControl is a member of stations[1], so you access it, like all members, as stations[1]->senarioControl Then you dereference it relative to stations[1], remembering that you need parentheses: stations[1]->*(stations[1]->senarioControl) Then you call the function, and due to precedence rules you need another pai...
61,694,785
61,694,848
How do I return the number of arguments of a function?
For example if I have int MyFunction(int,...);//no. of parameters is unknown And in main() MyFunction(1,2,3,4); The returned value should be 4.I've tried stdarg.h but to use that you have to know the number of parameters, so it doesn't hold up for me.Thanks!
Just return the number of arguments in a parameter pack. template<typename ...Args> unsigned MyFunction(Args... args) { return sizeof...(args); } int main() { return MyFunction(1,2,3); }
61,695,064
61,695,309
stack.size() vs stack.empty()
to check whether a stack is empty, we can use if(stack.size()). Then why do we have stack.empty(). Is there any condition where these results may differ or any advantage of using one over other.
To some degree it’s a style choice. Personally I think relying on implicit bool conversion should be restricted to things with pointer-like semantics: actual pointers, smart pointers, std::optional come to mind. It is ubiquitous in that context and just feels natural. In other contexts it feels weird. Communicate your ...
61,695,235
61,696,706
Creating a boost::spirit::x3 parser for quoted strings with escape sequence handling
I need to create a parser for quoted strings for my custom language that will also properly handle escape sequences, which includes allowing escaped quotes within the string. This is my current string parser: x3::lexeme[quote > *(x3::char_ - quote) > quote] where quote is just a constant expression for '"'. It does no...
I have many examples of this on this site¹ Let met start with simplifying your expression (~charset is likely more efficient than charset - exceptions): x3::lexeme['"' > *~x3::char_('"')) > '"'] Now, to allow escapes, we can decode them adhoc: auto qstring = x3::lexeme['"' > *( "\\n" >> x3::attr('\n') ...
61,695,469
61,695,900
Recursive Power Function Sanity Check
This is kind of an unusual question, but I'm working a problem and my issue is that it's working. But only when I run it, not when it's put through the submit process. I wrote this function to handle exponents using recursion (the requirement of the problem). double Pow(double num, int power) { if (num == 1.0 || p...
return ( (1.0/num) * Pow( num, power + 1 ) ); contains an unnecessary rounding because 1.0/num produces the result of 1 / num rounded to the nearest representable value, and this is then multiplied by Pow(num, power+1). Change this to return Pow(num, power+1) / num;. This eliminates the extra rounding. In the two cases...
61,695,763
61,695,866
Why there is difference in constructor and destructor calls?
Header file: Date.h file #include<iostream> #include<cstdlib> #include<cstring> using namespace std; class Date{ private: int day; int month; int year; public: Date(int d = 1, int m = 1, int y = 1900): day(d), month(m), year(y) { cout << "date constructor is called"<< endl; } ...
When you pass by value, you are in fact creating another object for the function's lifetime . Notice how you Pass by value two Data objects in Employee's Constructor? That means that two new Date objects are created up until Employee's constructor returns. These values are called automatic , and once constructor exits ...
61,696,000
61,696,287
segmentation fault in finding next greater element using stack
I have an array on which I iterate from right to left. You can see my implementation : int arr[]{1,3,22,4,1,-3,3,7}; int n{sizeof(arr)/sizeof(int)}; vector <int> v; stack <int> s; for(int i{n-1} ; i >=0 ; i--){ if(s.empty()){ v.push_back(-1); } else if(arr[i]<s.top()){ v.push_back(s.top()); ...
This logic looks very convoluted. There is probably a much cleaner and expressive way to write what you mean. The segfault is due to you checking if s is empty after you already look at the top while(arr[i]>=s.top() && s.size()>0) you could try while (!s.empty() && arr[i]>=s.top())
61,696,080
61,696,510
Access current URL in WASM (c/c++)
I need to secure my C++ WebAssembly script for stealing and using on other domains than mine. Is there some way how to access URL of current window in directly WASM script, where I can check it? I could send domain as parameter from JS to WASM, but it could be easy overwritten there.
No, there is no way to access the current URL from a WebAssembly module without interoperating with the JavaScript host. In fact, WebAssembly cannot do anything without the host's help! It is design to have no I/O capabilities. Furthermore, even if it could access the URL - it would still not be a very robust security ...
61,696,205
61,696,754
printing error message after third substring is found
Hello I am pretty new to C++. I have a question regarding the splitting of a string. For example, I have a string like this std::string str = "jump 110 5"; and between strings "jump", "110" and "5" can be as many spaces as there can be. I want to save 110 in an int variable and if after the number 110 another number o...
EDIT: Second attempt.. Here is what I wrote to parse the values into a vector. if the vector has more than one set of numbers, it prints and error. #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> int main() { std::string str = "jump 110 5"; size_t i = 0; for ...
61,696,259
61,696,334
Use any type in a function parameter in C++
I am trying to find a way to get this function into a more generic one. void addStage(Image (f)(Image)); The thing i want to get is something that can recieve different types of functions with or without parameters, void or not. I have tried something like this but of course it is not working. void addStage(auto (f...
Use SFINAE: template<class T> std::enable_if_t<std::is_function_v<T>, void> addStage(T* f) { ... } But, if you don't need any special check (wether T is a function or no) you can actually just use a template and leave to the compiler all the checks: template<class T> void addStage(T f) { ... }
61,696,430
61,696,940
C++ If statement skipped
I'm implementing collision resolution with two AABB's but it seems "if(*yDepth > 0)" is being completely skipped by the compiler. When i apply a breakpoint to the statement within visual studio it replies "this breakpoint will not currently be hit. Is it an issue with pointers? I have tried moving the contents of the s...
In release mode - or more precisely, when optimisation is on - the compiler can re-order, re-arrange, combine or even remove lines of code. This means that there is no longer a one to one correspondence between the lines of code you wrote and the machine code that is actually produced. This can mean that certain lines ...
61,696,443
61,696,513
Is there any way to make a constructor default values in a templated class?
I know that in C# you can do: class Account<T> { T id = default(T); } which assigns to templated id value default value of data type. How can I do the same in C++?
template <class T> class Account { T id{}; };
61,696,512
61,696,561
Swapping the values of elements in the array using pointers
I recently learnt pointers and began trying simple operations and simple functions with it and I did a swapping function that swaps first value and last value of elements in the array using pointers. Now my question is, while I have two pointers, a pointer basically points to a memory location of another variable corre...
Basically, when you are de-referencing the pointer in the swapping function, you are accessing the values stored in the variables the pointers are pointing to So any change in the pointer's 'values' is reflected in the variables to which they are pointing to.
61,696,567
61,696,847
boost is_invocable_v and is_invocable::value returning different results
Since I had to write some C++14 compatible code where I still wanted to make use of std::is_invocable in a template I tried to use boost::callable_traits::is_invocable. However while boost::callable_traits::is_invocable returned similar results, boost::callable_traits::is_invocable_v did not. Here is a simple example o...
This looks like a Boost bug to me. is_invocable and is_invocable_v have different implementations (taken from Boost 1.69, comment is mine): template<typename T, typename... Args> struct is_invocable : detail::is_invocable_impl<T, Args...>::type { using type = typename detail::is_invocable_impl<T, Args...>::type; };...
61,696,988
61,699,572
Prim’s MST for Adjacency List Representation
I was trying to implement Prim's algorithm using min Heap. here is the link I was referring to https://www.geeksforgeeks.org/prims-mst-for-adjacency-list-representation-greedy-algo-6/ I was wondering why can we use a vector and sort it using std::sort function in place of min heap.
You could, but remember that every time a new node is added to the MST you have to update the set of edges that cross the partition (edges to nodes that are not yet in the MST), so you would have to sort your vector at every iteration of the algorithm, which would waste time, since you just need to know which of the ed...
61,697,312
61,697,448
variable no of arguments for class template's member function
I am just learning about templates and was trying to write a simple template class for vectors like template <unsigned N> struct vec { std::array<float, N> m_buffer; float& operator[](unsigned index) { return m_buffer[index]; } vec(float value) { std::fill(m_buffer.begin(), m_buffer.end(), value); } ...
You might use variadic template: template <unsigned N> struct vec { std::array<float, N> m_buffer; template <typename ... Ts> vec(Ts... args) : m_buffer{{args...}} {} // ... }; SFINAE might be added to check arity and to restrict to float convertible parameters. Alternative which might be appropriate is ...
61,697,368
61,697,456
"expression is not assignable"
Im trying to find the second largest value of an array in order to create a equilibrium, the "largest_value" being the first and "large_value" being second, when i'm executing the it says "expression is not assignable".. i just started learning.. Any help would be awesome. #include<iostream> #include<stdlib.h> int main...
(largest_value - array[i]) = large_value; assignments work the other way around a=b assigns value of b to variable a
61,697,375
61,697,447
C++ Writing a vector of objects to file
I have a vector of objects with quite a few variables (name, type, length etc) which I am trying to write to file. vector <Boat> berths; void Boat::write_boats() { ofstream file("records_file.txt"); for (Boat b : berths) { file << owner_name << "; " << boat_name << "; " << type << "; " << length <<...
One problem I can spot: "i = 1" in the loop should be "i = 0", because array indexes start from 0. The second: you iterate 'berths' array, so you will get N * N boats saved, if you have N boats in 'berths'. The simple solution would be void save_all() { ofstream file("records_file.txt"); for (Boat b : berths...
61,697,669
61,699,090
imread works in a normal c++ program, but not in android with ndk native
#include <jni.h> #include <string> #include <opencv2/opencv.hpp> using namespace cv; #include <iostream> extern "C" JNIEXPORT jstring JNICALL Java_com_example_cppinandroid_MainActivity_stringFromJNI( JNIEnv* env, jobject) { Mat image; image = imread( "/home/<name>/a.png", 1 ); ...
Android directories do not match Linux at all. A good solution is to find your file through Java and pass the path to the file as a parameter to function Java_com_example_cppinandroid_MainActivity_stringFromJNI. If your file is in public files, you can try "/sdcard/a.png" - but the path may vary between different andro...
61,697,683
61,698,247
Insertion in Hash Table using Singly Linked Lists
I'm new here, I need some help with this problem, the problem is that it stores value for the first entry, but when I'm creating a list, for example when I want to insert 22, after I have inserted 2 before, it behaves as if it added the node after 2, but actually it doesn't create and I don't know why. Need assistance ...
When you assign temp = NewNode; you're not actually setting the value of the previous temp->next to NewNode. You don't need to set temp to NewNode, you need to set temp->next to NewNode once temp->next == NULL. What you are currently doing is this: [ node 1 ] --> nullptr | | as...
61,697,716
61,697,796
OpenGL crash in nvoglv32.dll during execution glDrawElements
During execution glDrawElements happen crash in nvoglv32.dll. Immediately called loadOpenGLObjects() and after it invoke draw(), in which happens сrash. Seems like something went wrong with glVertexAttribPointer, but i don't understand what. GLfloat vertices[24] = { -1.f, -1.f, -1.f, -1.f, 1.f, -1.f, 1.f...
Either you've to specify an Index buffers or you've to use glDrawArrays. When you use glDrawElements then you've to specify an GL_ELEMENT_ARRAY_BUFFER. Since you've 8 vertex coordinates, which are arranged to a cube, I suggest to specify and array of indices with 6 indices (2 triangles) for each side of the cube. GLuin...
61,697,887
61,701,068
How thread-safe is boost::asio?
I have an io_context that is run by multiple threads. I'm using sockets and timers. I know that I need to wrap all async_writes by a strand to prevent concurrent writes to the socket. But can two threads concurrently access the socket to issue an async_read and an async_write at the same time? Or what about shutdown() ...
This has oft been asked and answered: Thread Safety In general, it is safe to make concurrent use of distinct objects, but unsafe to make concurrent use of a single object. However, types such as io_context provide a stronger guarantee that it is safe to use a single object concurrently. So yes, you need to pro...
61,697,896
62,614,951
Vim's formatting/auto-indent in C++ class seems incorrect. is this normal?
It seems there are many options in Vim for indenting c code with the cindent and cinoptions variables. I've made no modifications to these settings and I've tested this with a fresh install of Vim and with no vimrc. I can't seem to find an explanation for the following behavior: If public is used on the first line in t...
Installing clang-format and using an autocmd solved my issue. Any new settings that I want to apply to c or c++ files can simply be added to the CPPFormatSettings function. Google's formatting makes the most sense to me, but there are 5 or 6 other styles to choose from. Changing to -style=microsoft will format the code...
61,697,977
61,698,546
Is "assert (this)" a viable pattern?
Suppose the C++ below. Before calling of a->method1() it has an assert (a) to check if a is sane. The call a->method2() has no such assertion; instead method2 itself checks for a valid this by means of assert (this). It that viable code re. the C++ specification? Even if it's covered by the standard, it not good style ...
Even if it's [permitted] by the standard It isn't. it not good style of course Nope. and it's error prone if the code ever changes, e.g. if the method is refactored to a virtual method. I concede that a virtual member function is more likely to cause a "crash" here, but you already have undefined behaviour and ...
61,698,026
61,698,142
Custom C++ string class
I am creating a class that works similar to the string class. I am in a starting stage doing some experiments. Assume all header files are added class String { public: int len; char *str = NULL; // Default constru...
Your code does this: Default-construct a String "A" Convert-construct a temporary String "B" from the expression "Hello" Copy-assign "B" to "A" The assignment does not invoke the constructor on "A". You only get one construction per object. Unless you specify otherwise (with delegating constructors), your default con...
61,698,497
61,698,882
std::for_each over a vector of non-copyable objects
I was reading about std::for_each in cppreference: Unlike the rest of the parallel algorithms, for_each is not allowed to make copies of the elements in the sequence even if they are trivially copyable. So, to me, it means that std::for_each does not copy-construct objects in the container and it should work fine...
Your lambda capture block attempts to capture the whole vector by value. This is unnecessary, since the access to the elements is granted through the reference argument. Try this: std::vector<std::thread> threads; std::for_each(threads.begin(), threads.end(), [](std::thread & t){t.join();});
61,698,570
61,700,501
Changing file extension associations programatically using MFC?
I can use this code in InitInstance to confirm which executable is associated with a given extension: TCHAR szRegisteredEXE[_MAX_PATH]; DWORD dwBufferLen = _MAX_PATH; HRESULT hRes = AssocQueryString(ASSOCF_NONE, ASSOCSTR_EXECUTABLE, _T("MeetSchedAssist.MWB"), NULL, szRegisteredEXE, &dwBufferLen);...
Step one is to create a Inno Setup installer that is going to manage the tweaking of the registry for us: ; SignTool parameters #define SignedDesc "$qMeeting Schedule Assistant File Associations Tool$q" #define SignedPfx "$q~~~~~$q" #define SignedTimeStamp "$qhttp://timestamp.verisign.com/scripts/timestamp.dll$q" #defi...
61,698,607
61,714,368
How to link GLEW and GLFW and OpenGL to MingW's g++
I am doing a course on OpenGL. So I have run my project in Visual Studio 2019 and it works. What I needed to do in Visual Studio was: Add GLEW's and GLFW's additional include directories. (when you download the libraries it is simply the location of the include file) Add GLEW's and GLFW's additional library directo...
The MingGW and mingw-w64 compilers are Windows commandline tools. They are Windows ports of (some of) the GCC compilers. tdm-gcc is yet another choice. Commandine tools for any operating system don't need their own shell. You can run them in any shell you've got on that operating system. On Windows today you have a cho...
61,698,642
61,698,838
Why do I got junk data, when sending a structure to shader storage buffer?
I am working on an opengl based raytracer application in c++. I would like to send data from the cpu side to the fragment shader. The data is a bounding volume hierarchies (BVH) tree. Unfortunately on the shader side I got junk data, when I am trying to write out the coordinates as color with gl_fragcolor. I don't know...
When you specify the Shader Storage Buffer Object, then you have to use the std430 qualifier. See OpenGL 4.6 API Core Profile Specification; 7.6.2.2 Standard Uniform Block Layout. If you want to use the following data structure in the shader: struct FlatBvhNode { // base aligment aligned...
61,699,029
61,699,538
c++ strings line reversion to the console
I just want to know what is wrong with this C++ code: I have to get chars from the console and count how many lines were written. Then i have to show them in reverse order. I.e: if i write 3 lines: "hi", "im", "lucas" with a '\n' ending each one. I have to reverse them, so it writes "lucas", "im", "hi", line by line. F...
There's a lot wrong with what you've shown. Unnecessary variables, no actual backwards iteration, bad loop conditions, etc. Here's code with a vector: #include <iostream> #include <string> #include <vector> int main() { std::string line; std::vector<std::string> entries; do { std::cout << "Enter a thing: ";...
61,699,110
61,699,256
Is it wise to not RefPtr all Gtk::Builder variables because Gtk::Application is referenced already
I'm still learning gtkmm3 so please be considerate with my (stupid) question I created a sample gtkmm3 app, the main class starts with: #include "app-window-declaration.h" // signal activate function was here int main (int argc, char *argv[]) { Glib::RefPtr<Gtk::Application> app = Gtk::Application::create...
A Gtk::Builder must be used via a Glib::RefPtr. Period. End of discussion. When the documentation says that there is only one way to do things, then trying to do things another way is undefined behavior. The reason why this restriction exists is part of the black box. You are not allowed to assume it has something to d...
61,699,654
61,699,779
std::initializer_list usage in variadic template function
I can't understand how below code snippet works. Especially std::initializer_list usage. template<typename ... T> auto sum(T ... t) { typename std::common_type<T...>::type result{}; std::initializer_list<int>{ (result += t, 0) ... }; return result; }
template<typename ... T> auto sum(T ... t) { //getting the common type of the args in t and initialize a new var //called result using default constructor typename std::common_type<T...>::type result{}; //(result += t, 0) ... this just sum the result and the next arg in the //parameter pack and then retur...
61,699,759
61,700,296
How smart is std::max_element()?
Suppose I have an std::vector<int>: std::vector<int> v; [v is initialized] and I want to get the maximum element of v. There is an algorithm for doing that: int max_value = *std::max_element(v.begin(), v.end()); So far, so good. Now, suppose that v contains 10,000,000 elements, and its 10th element is equal to std::n...
I can't speak for all implementations, but libc++'s implementation of max_element does not do that. There's a couple problems with the idea: The assumption that there exists a specialization of numeric_limits for the type of the elements of the sequence. (max_element works on anything that can be ordered.) This could ...
61,699,775
61,700,003
Does any major C++ implementation actually define `NULL` as `nullptr`?
Since C++11, the Standard allows the macro NULL to either be a integer literal with value zero, or a prvalue of type std::nullptr_t. Any Standard Library vendor deciding to change their definition of NULL from an integer to nullptr would very likely cause breakage for clients relying on pre-C++11 code. Does any major...
libstdc++ relies on including stddef.h, which defines NULL in the following way: // <stddef.h> // #if defined (_STDDEF_H) || defined (__need_NULL) #undef NULL /* in case <stdio.h> has defined it. */ #ifdef __GNUG__ #define NULL __null #else /* G++ */ #ifndef __cplusplus #define NULL ((void *)0) #else /* C++ */ ...
61,699,806
61,700,172
ADL name lookup problem, is using std::swap; swap(a,b) related to function overloading or inner scope function hide outer scope function?
I know what ADL is and I know in C++, inner scope function hides outer scope functions. That is, names do not overload across scopes. So funtion overloading need to be done in the same scope. So now my question is, for this common code snippet: #include <iostream> #include <string> using std::cout; using std::endl; na...
1. is true. For ADL, These function names are looked up in the namespaces of their arguments in addition to the scopes and namespaces considered by the usual unqualified name lookup. std::swap is found by usual unqualified name lookup, and Foo::swap is found by ADL, they're both in the overload set. Foo::swap is a no...
61,699,961
61,700,022
Why won't the pointer store and print the same data as the object it is supposed to match? (C++)
I am making a game where the user is allowed to choose a Player object from a vector of Player objects read in from a text file. I ask the user to enter a name in order to choose a player from the vector and I iterate through the vector to look for a matching name (assume each player has a different name). Once they ma...
for(Player p:playerVectorReadIn){ This is iterating by value, p is an object that's local in scope to this for loop, and is a copy of the object in the vector. Each time this loop iterates this object gets destroyed. If the loop iterates again, a new p object gets created. player1=&p; This saves a pointer to thi...
61,699,984
61,700,226
How can I repurpose the fields of a base class in C++?
I want to design a nodal class that I can then use for various types of trees, but I run into complications when I try to consider how to do it in such a way that I don't create unnecessary fields. For example, I have the following class: class Node { protected: Node *left; Node *right; } This class will have ...
With the suggested class hierarchy, BinaryNode would have four children. Left and right generic nodes from the base, and left and right binary nodes as direct members. Unless you need dynamic polymorphism, a template would be an appropriate way to reuse node code. This is a typical use case for Curiously Recurring Temp...
61,700,525
61,703,349
Access an array of pointers to objects on device CUDA
New to CUDA and gpu programming, having trouble with copying array of object pointers to device. I have a vector of object pointers, each object contains two vectors, that I will be working with in device code. I need to somehow copy that array into the device memory, however after reading similar solutions, still can...
auto **nodesPtr = (aho_corasick::Node **) malloc(a->nodes.size() * sizeof(aho_corasick::Node *)); int i = 0; for (auto &node: a->nodes) { auto *newNode = new aho_corasick::Node(' '); cudaMalloc((void **) &(newNode->cudaChildren), sizeof(int) * node->children.size()); cudaMemcpy(new...
61,700,587
61,700,888
C++ Code Creates CSV file, but does not write to it
I am trying to learn how to write data to a file in C++, in this case a CSV file. Currently my code will create the file in the location of my choice, but when I open the file, it is a blank document. Any insight here would be much appreciated! Thank you. #include <iostream> #include <fstream> #include <string> usin...
I was able to get it to work by declaring file object instead of initializing it. Take a look: #include <iostream> #include <fstream> #include <string> using namespace std; const char* path = "ex2.csv"; ofstream file; //string filename = "ex2.csv"; int main(int argc, const char* argv[]) { file.open(path, ios:...
61,700,656
61,701,345
std::unique_ptr initialization methods
I see that std::unique_ptr has the following ways of initialization: std::unique_ptr<some_class> sc_ptr{ new some_class }; wherein someone could delete the allocated some_class from underneath the std::unique_ptr. and some_class *scptr { new some_class } std::unique_ptr<some_class> sc_ptr1{ scptr }; std::unique_ptr<so...
Several reasons: make_unique takes custom deleter, so it is supposed to handle custom allocation. Passing allocator to a hypothetical allocate_unique is cumbersome. The same as .release() can provide a junction with a code that manages lifetime differently (including API in C interface that use raw pointers). Historic...
61,700,793
61,701,741
install C++ application using CMake on multiple systems
I wrote a simple openGL application using C++ and SDL2. I've compiled it using CMake on linux and everything works fine. How do I now run my program on other systems? Is it possible to compile the program on my linux machine and then open the compiled output file on another linux machine? Or does every machine have to ...
Binary Distribution How do I now run my program on other systems? This depends on 2 things: In order to run pre-built app on another system, that other system must be compatible in both SW and HW; meaning, both SW APIs and (HW architecture) must be "close enough". For example, if you built the app on any kind of P...
61,700,873
61,701,039
Printing stack with linked list without struct
I'm trying to create a stack using linked lists in c++ without struct.Bot i can't wirte display function how can i display ?Any help or clarification is much appreciated. Thanks class StackNode { public: int data; StackNode* next; }; StackNode* newNode(int data) { StackNode* stackNode = new St...
You can print the data and move to the next node, till you reach the last node. Code (Prints the stack, top to bottom): void display(StackNode* root) { while(root!=NULL) { cout<<root->data<<'\n'; root=root->next; } }
61,701,258
61,701,445
How to edit a function signature at the same time
I'm using VScode as my IDE, IN my college we require to write our codes using TopDown Design. like this example: void sum(int a, int b); int main() { int a=2, int b=3; sum(a,b); return 0; } void sum(int a, int b) { printf("%d", a+b); } My problem is that a lot of time while editing my function at the "...
If you place the cursor over the signature and press CTRL + D you can select all the signatures, one at a time, then you can change them all in one go.
61,701,280
61,739,433
Make CLion have C++ Source Files as .CC
In CLion, is there a way to make all C++ source files have the .cc extension instead of the .cpp extension by default? For example, in a new project, there is a main.cpp file. I want it to be main.cc.
Yes, you can! You can rename file main.cpp or any other from context menu or by Shift+F6 hot keys.
61,701,376
61,707,216
How to modify LastAccess time attribute of a file
I have implemented the following function which changes the LastAccess time of a file to the latest time of the current system but however, I wanted it to change the LastAccess time to a customized time. for example, I give a time like 1994-04-04 to the function, and then it changes the LastAccess time to that time. B...
I modify your code a little bit to achieve the goal. If you want to change LastAccess of file, you have to set this value only and set the other parameters to NULL. #include <tchar.h> #include <windows.h> #include <stdio.h> BOOL SetFileToCurrentTime(LPCTSTR lpFileName) { HANDLE hFile; FILETIME ft; SYSTEMTI...
61,701,425
61,701,656
How to find the line caused segmentation fault in c++ compiled program
I am using vim for c++ programming. I have bound the compile command to ctrl+c in vim and I run it in another tmux pane by running ./main.out. My problem is that when my c++ program gives me segmentation fault error, I don't know which line has caused the problem. But when I compiled and ran the program in vscode, it s...
When compiling the program, add the -g compiler flag, or even better -ggdb3, which will give you a much prettier output, by adding debugging symbols to the executable. Also, make sure that you compile with the -O0 optimization level. To actually debug the program, run gdb ./main.out to start the program in a debugging ...
61,701,494
61,702,565
Is there a std::sample equivalent in boost?
I'm still using C++14. So std::sample is out of reach. Is there something equivalent in boost? I do not want to copy my std::multiset which isn't reorderable.
As far as I know, there is not such a thing in boost. But you may write a simple one, yourself: template<typename T> std::vector<T> sample_items(const std::multiset<T> & ms, int samples) { std::vector<T> ret_value; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, ms.siz...
61,701,532
61,702,960
Qt5 QListView set up items in a horizontal row instead of vertical list
I am setting up a QListView with a custom QStyledItemDelegate and I would like to have my items rendered so they are in a horizontal 'row'. Assuming our QListView has models that are "A", "B", and "C", the standard view will have them as: --------------------------------------------------------------------------------...
You can change the flow property from "TopToBottom" to "LeftToRight" with setFlow as below: listView->setFlow(QListView::Flow::LeftToRight);
61,701,587
61,701,623
Why the definition of the assert macro, in a release build, cannot be just `#define assert(expression) 0`?
This is the definition of the assert macro in Visual Studio 2019 #ifdef NDEBUG #define assert(expression) ((void)0) #else _ACRTIMP void __cdecl _wassert( _In_z_ wchar_t const* _Message, _In_z_ wchar_t const* _File, _In_ unsigned _Line ); #define assert(expression)...
This prevents using assert as an expression. So if one does (by mistake): a = assert(something); The compiler will throw an error both for a release and debug build.
61,701,593
61,701,721
Wrong output in Diffk II Problem in Leetcode using set. Why is set being used to solve this problem?
The Diffk II Problem is : Given an array A of integers and another non negative integer k, find if there exists 2 indices i and j such that A[i] - A[j] = k, i != j The code I found online is : if (a.size() < 2 || k < 0) return 0; set<int> s; //for(int el : a) // s.insert(el); for(int i=0;i<a.size();i...
If you uncomment the 2 lines //for(int el : a) // s.insert(el); It means all elements will be added at the beginning. k is non negative, so it may become zero. Therefore, the function will give ignore the i != j condition and give false-positive when k is zero (searching for A[i] = A[j]). When inerting insi...
61,701,704
66,541,333
VS Code C++ debugging
I try to debug my C++ programs but it shows me this error: Could not find the task 'g++ build active file'. I tried adding a configuration as Visual Studio Code says in its website, by choosing C/C++: (gdb) Attach, but nothing changes.
I struggled for days to setup a running and debugging environment for C++ in VS Code. Finally I found a way to solve the problem. Please follow the below steps Prerequisites- Have Mingw32 installed on your PC. Install C++ extension for VS code Install Competitive programming helper extension for VS code. Something li...
61,701,785
61,701,929
Get all subsets of given size k from unordered_set?
I have an unordered_set<int> vertices and have to generate all subsets of size exactly k for my clique program. All of solution (including all on SO) that I've seen work on arrays, not sets. Is there any algorithm like Python's itertools.combinations implemented in C++? If not, how should I go about it? Convert to arra...
Generation all subsets will take huge amount of time when number of elements become large (except for some special cases like choosing 0, 1, n-1, or n elements out of n), so I don't think doubing memory requirements will become serious problem unless you have strict memory limit. For that reason, I think you should jus...
61,701,918
61,945,468
How do I add files generated during the build to my include directory?
I'm trying to use a Python script to generate some header and source files for my C++ code and move them to the appropriate source directories, as the subsequent C++ build requires them. Here's what the current iteration of my code looks like : # Generate the Parameters and ParamParser files. add_custom_command( OUTP...
I figured it out a while ago using Tsyvarev's advice in the comments. The solution was to add WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} as an argument to add_custom_command.
61,702,079
61,702,144
Is there a way to substitute all definitions of functions where they are used and to automatically change variables names in my source code?
I know this is a really weird question, but I have my reasons. During the last year and the beginning of this one, at school they are teaching us about programming (C++ and VB). We are aspiring to be "baccalaureates" (I googled the English term) in computing. But during my vacations I started studying programming (in ...
That seems very much like a custom job. you will have to do this by hand. That being said, there are ways in making that much easier. I personally use Visual Studios Code for some of my quick cpp scripts like the one you have written. This will help you rename symbols and format your code to your liking. Hope this help...
61,702,215
61,702,251
How can I check the user inputs the correct sequence of characters in a string
I need the user to input a reference with this exact model : ####.### There must be exactly 8 characters, the fifth being a full stop. for the moment I put this code i a while statement in check the length of the string and if the fifth character is a full stop. How can I check that the other characters are numbers ? K...
This seems like a good use case for std::regex_match. You can use it like this: std::regex r{R"(^\d{4}\.\d{3}$)"}; std::cout << "Enter the reference (####.###) : "; std::cin >> ref; if (std::regex_match(ref, r)) // ... else std::cout << "Wrong input. Reference should be '####.###'\n"; The regex works as follows: ^...
61,702,306
61,703,199
How to capture the value parsed by a boost::spirit::x3 parser to be used within the body of a semantic action?
I have a parser for string literals, and I'd like to attach a semantic action to the parser that will manipulate the parsed value. It seems that boost::spirit::x3::_val() returns a reference to the parsed value when given the context, but for some reason the parsed string always enters the body of the semantic action a...
In X3, semantic actions are much simpler. They're unary callables that take just the context. Then you use free functions to extract information from the context: x3::_val(ctx) is like qi::_val x3::_attr(ctx) is like qi::_0 (or qi::_1 for simple parsers) x3::_pass(ctx) is like qi::_pass So, to get your semantic actio...
61,702,525
61,702,603
Parse int from a string without regex?
If I have a string where there is some word and some number (like "Text 125"), is it possible to get this number and convert it to int without using regex?
Yes, you could use a stringstream if you know that it's a word followed by a number. std::stringstream ss("Text 125"); std::string buffer; //a buffer to read "Text" into int n; //to store the number in ss >> buffer >> n; //reads "Text" into buffer and puts the number in n std::cout << n << "\n"; Edit: I found a wa...
61,702,536
61,702,590
Is it possible to modify an attribute's attribute via reference?
Let's say I have a Language class and a Director class. class Language { private: std::string name; Director director; public: Language(std::string name); std::string getName() { return this->name; }; Director& getDirector() { return this->director; }; void setDirector(const Director& director...
In this function: void setDirector(const Director& director) { this->director = director; }; even though you are accepting the Director by reference, you are making a copy in the body, so you end up not changing the original Director argument. You could make the director member a Director&, but then you have to initia...
61,702,537
61,708,207
Getting symbols for explicitly loaded DLL from the application
I am modifying my application so that it can explicitly load a DLL (through the Windows API) and call some functions from the DLL. But I need to be able to call some application's functions from the DLL too. I can only provide header files of the functions to the DLL. But I am getting the LNK2019 'unresolved external s...
Thank you @AdrianMole for solving my problem! To resolve the external symbols in the DLL you'll need to create an import library of the EXE. In Visual Studio 2017, this can be done by going to the project properties. Go to Linker → Advanced and set the Import Library setting to the path and name you want. (For example:...
61,702,628
61,702,682
Iterating over a string with string::size_type vs int
This is the piece of code I'm working with on TDM-GCC with C++14 standard (32-bit/Windows 10): class var { private: vector<int> num; public: var(string x) { for(int i = x.size()-1; i >= 0; i--) // Notice use of INT num.push_back(x[i]-'0'); } }; int main() { var num1("232"); ...
string::size_type is an unsigned type, which means it can never be negative. That means this condition: i >= 0 will never be false. In fact, when i goes below 0, it will wrap around, and become the largest possible value of string::size_type. Then when you index x[i], you invoke undefined behaviour. I would suggest wr...
61,702,663
61,727,694
Sycl kernel-call very slow
I am new to stackoverflow, sycl and gpu-programming. I have a project with a working basic sycl kernel. The logic is working so I'm skipping it in the question. Also during the compiling and execution is no error. The big problem is now that the call of the sycl code is very slow. First I thought it was some memory cop...
First I would point out that this is a very simple set of SYCL code so if you are looking to measure performance it's probably not a very relevant example. Here's a research paper showing comparable performance of ComputeCpp with CUDA doing a reduction algorithm benchmark, see slide 40 for the chart. You'll also see in...
61,702,763
61,707,154
Why do I have some trouble with fwrite() and fread()?
This is my program: #include <iostream> int main() { // open file1.txt FILE* file1; fopen_s(&file1, "file1.txt", "wb+"); // write array of 5 integers to file.txt int array1[5] { 1, 2, 3, 4, 5 }; for (int i = 0; i < 5; i++) { fwrite(array1, sizeof(array1[0]), 5, file1); } f...
Read to write Pulled from Microsofts C Runtime Library documentation When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed. (The file is said to be open for "update".) However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there is n...
61,703,129
61,703,269
How to print an array of 5 values 1D as columns?
I have an array of integer values that is of one dimension.I need to print it as columns. Although I can print the values as columns but it pritns more than 5 values. The ideal output would be like this: 1 1 1 1 1 How would i do this? For example, my try is this: int main(){ int array[5] = {1,1,1,1,1}; cout<<"arra...
You can just write 2 loops: for ( int i = 0; i < 3; ++i ) { cout << setw(3) << array[i]; // first row } cout << endl; // next row for ( int i = 3; i < 5; ++i ) { cout << setw(3) << array[i]; // second row }
61,703,452
61,706,801
Accessing instance variables of a class from pybind11 wrappers
I haven't found a way to do a fairly simple thing with pybind11. Suppose I have an aggregated class, and I want to get to an instance variable of a class so I can drill down into it: struct foo { int x; }; struct baz { foo var; } PYBIND11_MODULE(test, m) { py::class_<baz>(m, "baz") .def(py::init<>()) .def("...
The following lambda creates the necessary GetX member function, which expects one argument: a baz instance. The argument is supplied by pybind11 when GetX is called on an instance of the wrapper class. ... .def("GetX", [](const baz &b) { return b.var.x; }); Usage: >>> import ex >>> v = ex.baz() >>> v.GetX() 0 Se...
61,703,634
61,703,666
Boolean Recursion Function for Binary Tree
So I have been trying to create a recursion function to identify if the each root's data is equivalent to the size of subtrees. For example) the tree below is true as all the subtree size is equivalent to the root value: grantparent (5) = 5 nodes parent (3)= 3 nodes I think I got the logic but having trouble translati...
Shouldn't left = thesizetree(root->left); right = thesizetree(root->right); return true; be left = thesizetree(root->left); right = thesizetree(root->right); return left && right; or somewhat more efficient return thesizetree(root->left) && thesizetree(root->right); It should be a red fla...
61,704,039
61,704,073
Nlohmann's json library, json array to a vector of structs with pointers inside the struct
I saw this post about converting a json array to a vector of structs. I have a struct named Foo: typedef struct Foo { Foo* SubFoo; } Foo; and when I try to do this: void from_json(const nlohmann::json& j, Foo& f) { j.at("SubFoo").get_to(f.SubFoo); } It gives me this error: error: no matching function for call t...
Just dereference the pointer: void from_json(const nlohmann::json& j, Foo& f) { j.at("SubFoo").get_to(*f.SubFoo); } Here's a demo. You'll have to ensure that you are not dereferencing an invalid pointer though.
61,704,108
61,704,341
Code skipping the instruction of waiting for multiple events
I'm coding a program in C++ in Visual Studio 19 that waits for 640 events to happen (in its case, it's just a array of 640 HANDLE where every position needs to move right or left, that is not important). Well, everyone of those has been initialised as for(i=0; i<640; i++) vector[i]=CreateEvent(NULL, true, false, N...
According to the docs for WaitForMultipleObjects, the maximum number of handles that can be waited on is given by MAXIMUM_WAIT_OBJECTS. A search of the Windows header files shows that it is defined as #define MAXIMUM_WAIT_OBJECTS 64 // Maximum number of wait objects in WinNT.h. So you're waiting on too many objec...
61,704,273
61,740,294
How can I fix this error at make from Azerothcore?
I am installing it by using the Documentation from Azerothcore, and at the point where I use the command "make" there came the following error: /home/wowazerothcore/azerothcore/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp:57:65: fatal error: no matching constructor for initialization of 'const std::unorde...
I suspect the reason for the error you are seeing is an old version of gcc, because the compiler is pointing to gcc include files. The reason apt-get update is showing all packages up to date, is because Debian GNU/Linux 8.11 (jessie) Release: 8.11 Codename: jessie is an old version of Debian. As per Debian package s...
61,704,361
61,704,472
What is this #define using multiple uninitialized arrays in one header file?
I have seen the following code being used in one header file from cyanogenmod (changed names to improve readability): #define THIS_C \ const char CP::a[] = "a"; \ const char CP::b[] = "b"; \ #define THIS_H \ static const char a[]; \ static const char b[]; \ How does this work and how can I use this kind of #define st...
How does this work Macros work by replacing the macro with its definition. If you write this in a source file: THIS_C The pre-processor will replace it with: const char CP::a[] = "a"; const char CP::b[] = "b"; and how can I use it? Well, if you want declare such variables, then you can use the macro to generate ...
61,705,212
61,707,255
making sfml c++ scroll bar won't draw shapes inside a veiw
So i'm trying to make a basic gui with sfml and need a scroll bar to scroll through a loop of drawables. After research I learned that view manipulation would be the way to do it. I have a rectangle for an outline that i'm trying to use as the view and have set up the bar itself i just need it to change the view. My is...
I've adapted your code to something that compiles and actually draws stuff on the screen. It's not how you want it to look but it show drawing through both views working. You should be able to experiment with this to progress. projectDrawables are located around 1000,1000 in your world where as allDrawables are positio...
61,705,395
61,705,454
C++ How to access child class virtual function from an array of pointers
I have an array of pointers defined like so: Person *people[2]; If I populate it in the main function, the program works just fine and my child class can access its method: int main(int argc, const char * argv[]) { Person *people[2]; Person p1 = Person(); Child c1 = Child(); people[0] = &p1; peo...
In populate, you are assigning the address of temporary (stack local) variables when you do people[0] = &p1;. Once you return from the function, the variable p1 dies, and person is left pointing to invalid memory. Attempting to access this memory from main then invokes undefined behaviour. You can fix this by allocati...
61,705,539
61,765,373
ovr_CreateTextureSwapChainVk crashes
I'm trying to create a VR application using Vulkan and OVR. Here are the main steps: Initialize OVR ovrInitParams initParams = { ovrInit_RequestVersion | ovrInit_FocusAware, OVR_MINOR_VERSION, NULL, 0, 0 }; ovrResult result = ovr_Initialize(&initParams); if (!OVR_SUCCESS(result)) { Debug::sendError("Failed to ini...
The problem was due to device extensions. Here are the correct extensions to use OVR : { VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, "VK_KHR_external_memory_win32", VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME, "VK_KHR_external_semaphore_win32", VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME };...
61,705,897
61,706,025
How to call construction on another inherited class in c++?
I am attempting to write a constructor using inheritance. Why does mammal class not inherit the animal constructor ? Also, why can't I overload it ? PS: constructor takes 4 parameters. Here is my code : class animal { public: string name; string diet; float dailycalories; float expe...
Here is how you call the parent constructor in the child constructor in C++: class mammal: public animal{ mammal(string name, string dit, float dacalo,float explife, float brainsize):animal(name, dit, dacalo, explife){ this -> brainsize = brainsize; } public: float brainsize; }; ...
61,706,169
61,706,232
In range v3 library, why ranges::copy do not work with output of ranges::views::chunk?
This works as expected: #include <range/v3/all.hpp> #include <iostream> int main() { auto chunklist = ranges::views::ints(1, 13) | ranges::views::chunk(4); for (auto rng : chunklist) { for (auto elt : rng) std::cout << elt << " "; std::cout << std::endl; } } On the screen: 1 2 3 4 5 6 7 8 9 10...
The issue is not with ranges::copy, it's just that ranges::views don't play nicely with std::ostream_iterator. You can just use ranges::ostream_iterator instead: ranges::copy(rng, ranges::ostream_iterator<int>{std::cout, " "}); Here's a working demo.
61,706,226
61,707,688
Multiple mat4 by vec4 and then make it vec3 in Python
Please help me. How can I multiply mat4 by mat4 and then make it vec3 in Python? Here is an example of what I need in C++: glm::vec3 var = glm::vec3((mat4(...)* glm::vec4(0, 0, 0, 1))); As well as a failed attempt on Python: var=pyrr.Vector3( pyrr.matrix44.create_from_translation(pyrr.Vector3([20,0,5])) * pyrr.Vector...
Use the @ operator. var=(pyrr.matrix44.create_from_translation(pyrr.Vector3([20,0,5])).T @ pyrr.Vector4([0,0,0,1])).xyz The @ operator is described in PEP-465
61,706,301
61,706,889
Creating an sqlite3 table with c++
I know their is another question with this exact title but it doesn't solve my problem, so here goes. I am following a tutorial on using SQLite with c++, but when I run my program to create the database table, I get an error; static int create_database(const char *s); static int create_table(const char *s); int main()...
There are couple of things, First you need to initialize error_message to nullptr. Otherwise sqlite3_free will cause a crash since error_message is having some garbage value. Secondly, according to the SQLITE documentation, you need to use atleast one of the three options while opening an SQLITE connection, SQLITE_O...
61,706,741
61,707,517
How would you hand a member of a class implementing an interface to another class using the interface?
I was just experimenting with interfaces and wrapping classes and I have come across a roadblock. I am wrapping an SFML::RenderWindow in a class that implements a draw() function. For example: struct ISprite { .... functions for sprites... .... } class SFML_Sprite : public ISprite { public: .... ...
Why don't you want to do the cast? It's safe and well defined in this context: class ISprite { }; class SFML_Sprite : public ISprite { }; class IWindow { public: virtual void draw(const ISprite& sprite) = 0; }; class SFML_Window : public IWindow { public: void draw(const ISprite& _sprite) { auto s...