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,793,225
61,793,331
Could not deduce template argument (vector, std::function)
I created a templated function of which I am trying to automatically deduce the template argument. MCVE(compile it): template<class Value, class Allocator> void foo(const std::vector<Value, Allocator>& v, const std::function<void(const Value&)>& f) { } int main() { vector<int> v; foo<int>(v, [](const int&){});...
Template argument deduction doesn't consider implicit conversion. Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later. Then type deduction of the template parameter Value on the 2nd function argument f fails bec...
61,793,281
61,793,322
Why I could not use getline() with a ifstream object?
I want read a file and write a copy file.But when I use getline() function, it is OK in main function but not in Writefile function. It confused me. The parameters are same: getline(ifstream object,string) #include<iostream> #include<string> #include<fstream> using namespace std; void Writefile(const ifstream & inF,of...
void Writefile(const ifstream & inF,ofstream & outF,const string &str){ should be void Writefile(ifstream & inF,ofstream & outF,const string &str){ Coceptually stream objects change when you read or write from them, so don't use const references for stream objects.
61,793,688
61,794,523
c++ iterator of any container with specific value type using concepts
I want to get rid of all the unholy enable_ifs in my templates and replace them with C++20 concepts, however there's barely any info on concepts and the syntax changes with just about any source I read. Here's a function that takes two iterators of any container with MyClass values: template <class IteratorType, typena...
Probably not the easiest to understand reference, but the normative source of information for concepts is the available standard draft. Where a concept definition is specified grammatically as 1 A concept is a template that defines constraints on its template arguments. concept-definition: concept concept-name = ...
61,793,812
61,793,938
Trying to make an bank management System but having errors
The things that i would like to accomplish is the functions of methods of the applications but getting many errors from the code which i don't completely understand and try to solve but came up with nothing. #include <conio.h> #include <stdio.h> #include <iostream> using namespace std; class bank { char name [100...
See here: #include <stdio.h> #include <iostream> using namespace std; class bank { char name [100],add[100],y; int balance, amount; public: void open_account(); void deposite_money(); void withdraw_money(); void display_account(); }; void bank::open_account()//: missing { cout << "Enter yo...
61,794,031
61,794,837
Find maximum product subarray
We need to Find the contiguous subarray within an array (containing at least one number) which has the largest product and return an integer corresponding to the maximum product possible. I found this code to solve the same : int maxProduct(const vector<int> &A) { int n = A.size(); vector<int> maxarray(n); ...
minarray's purpose is to handle negative numbers. {-1, 42, -2} would return 42 without minarray. if (A[i]>0){ maxarray[i] = max(A[i], maxarray[i-1]*A[i]); minarray[i] = min(A[i], minarray[i-1]*A[i]); } else { maxarray[i] = max(A[i], minarray[i-1]*A[i]); minarray[i] = min(A[i], maxarray[i-1]*A[i]); } Wh...
61,794,137
61,794,374
I get const_iterator instead of iterator from std::set
I have the following code which does not compile at all. It says that I cannot convert const Node to Node& but Node is not const nor methods of A refer to a const this nor std::set is const. Where am I wrong? #include <set> #include <string> struct Node { std::string name; }; struct NodeNameComparator { using...
std::set is not just a set of elements, it is a sorted set of unique elements. Elements of std::set are immutable by design, so that you cannot break std::set invariant by modifying its elements. That's the reason why std::set::iterator and std::set::const_iterator are both constant iterators. Cppreference on std::set ...
61,794,240
61,794,380
Can anyone please tell why this code is producing the wrong output?
Problem statement: Given two arrays A and B. Given Q queries each having a positive integer i denoting an index of the array A. For each query, your task is to find all the elements less than or equal to Ai in the array B. My code doesn't seem to work for all the test cases. Input 20000 // array size 24527...
When you are calling the findindex() function, pass arr1[x] instead of x. GFG Verdict:
61,794,367
61,794,467
Input a null value with cin or getline()
I'm trying to make a program that outputs random numbers between 1 and 21 with a loop. To exit the loop, you've to digit 'c' or 'C' and I want to make it continue the loop by pressing only ENTER, but the cin function doesn't accept a null input. Could you help me? The code is like this: char input[100]; int number; do{...
Use std::string instead of a char array, and then use std::getline() to get exactly one line. std::string input; while (std::getline(std::cin, input) && input != "c" && input != "C") { std::cout << (rand() % 21 + 1) << '\n'; } As an aside, it looks like you're using using namespace std;. Don't do that.
61,794,729
61,796,041
How does prepared statements in Sqlite C++ work
I do not know how to implement prepared statements in my Sqlite3 code #include <iostream> #include <sqlite3.h> #include <stdio.h> static int callback (void* NotUsed, int argc, char** argv, char** azColName) { int i; for (i = 0; i < argc; i++) { std::cout << ("%s = %s\n", azColName[i], argv[i] ? argv[i]...
You start with an sql statement that has placeholders for the parameters that you wish to bind later. Here, I use a single question mark for the placeholder, but there are other options described in the documentation. std::string sql = "UPDATE company SET name = ? WHERE id = 1"; Then you construct a prepared statement...
61,795,331
61,795,646
Partial specialization for one method in the class
I have a template matrix class. I try to implement the size (always square) as a template parameter. template< // Type of data typename type_t, // dimension of the matrix 4 -> 4x4 std::size_t dim_t, // I don't want a matrix of non numeric value typename = typename std::enable_if_t< std::is_ar...
You might use SFINAE: template< typename type_t, std::size_t dim_t, typename = typename std::enable_if_t< std::is_arithmetic_v< type_t >, type_t > > class Matrix final { // ... // Specialization for matrix 4x4 template <std::size_t N = dim_t, std::enable_if_t<N == 4, int> = 0> void doSom...
61,795,505
61,796,024
C++ - How to make 4x4 matrix and cout columns from top to the bottom (need to decryption a string)
I am a begginner in C++ and I just started working out with matrices that are not simple. I found out about "Caesar Cipher" algorithm or whatever it is called and I made some task for me to do. I want to make 4x4 matrix and cout columns from top to bottom. The problem is I do not know how to make 4x4 matrix that will e...
You may use string to make array easier. It's better to put some leeway in the arrangement. But 16*16 is too big. In order to output the 4*4 range, both i and j must be repeated from 0 to 4. Code: #include <iostream> #include <string> using namespace std; int main() { char word[5][5] = {"saor", "eece", "ssi...
61,795,550
61,796,623
boost::multi_index_container MRU
I have a bmi multi_index_container for MRU defined as following bmi::multi_index_container<Item, bmi::indexed_by<bmi::sequenced<>, bmi::hashed_unique<bmi::tag<hashed>, KeyExtractor>>> It is actually based on the bmi example. Once inserting and relocating the item to head everything is ok. The problem starts when I'm l...
To convert between different indices' iterators, use projection.
61,795,754
61,804,007
How to add macro Visual Studio 2019
I was trying to make a program to sniff packets and went to libtins If you are using a static build of libtins on Windows, then you have link your application with tins.lib. You also need to add this macro definition to your project: TINS_STATIC What does it mean? It even does not have a value. Can some one help m...
See this answer for a full guide for using libtins with Visual Studio. Using #define TINS_STATIC (before including any libtins headers) would work. Alternatively you could add TINS_STATIC in the project settings under C/C++ > Preprocessor > Preprocessor definitions. It does not need to have a value, because the libtins...
61,795,826
61,798,056
Can I export a Windows CRITICAL_SECTION from a DLL?
I hovered over CRITICAL_SECTION in VSCode and the tooltip reads: typedef RTL_CRITICAL_SECTION CRITICAL_SECTION typedef struct __unnamed_struct_13a13_1 CRITICAL_SECTION I am not sure how exporting structs work. Can I do this? extern "C" __declspec(dllexport) CRITICAL_SECTION myCritSect;
I do not see why it should not work, but I would rather use a pointer to critical section returned by a function. That must definitely work. extern "C" __declspec(dllexport) LPCRITICAL_SECTION GetProtector();
61,795,889
61,796,825
Gtk::Window icon set with set_icon_name doesn't work on wayland
I'm trying to solve a synfig issue by testing out this sample program: #include <gtkmm.h> #include <iostream> class HelloWindow : public Gtk::Window { public: HelloWindow(); ~HelloWindow(); }; HelloWindow::HelloWindow() { set_icon_name("org.synfig.SynfigStudio"); // <- ...
The answer is not mine. A user from GTK irc gave this and I'm only quoting the conversation Here is the chat history: Riot | GTK And the quoted answer normally you have a desktop file and the icon (and the name) are used from there so if synfig studio doens't have one, well, add one
61,795,949
61,796,152
Copy function parameter to const local variable
I'm digging in glm library, and found this type of code, also there are some other simmilar stuff. My question is: what is a purpose to copy function parameter to const local variable inside function, like this -- T const a(angle). Is it for some performance benefits? template<typename T, qualifier Q> GLM_FUNC_QUALIFIE...
There’s no purpose. This was probably done in a misguided attempt to avoid the indirection of repeatedly accessing angle (which, being a reference, is probably implemented by the compiler as a pointer). Whether this outweighs the cost of a copy is not obvious: if the type T is small and trivially copyable then making a...
61,796,452
67,824,411
Using modules in c++20
I have this program I am trying to compile. Live here import std.core; int main() { std::cout<<"ravioli"; } I was reading about Modules in C++ 20. The source has only information about running it on Microsoft C++ compiler. Has any other compiler implemented modules yet? If yes what additional flags do I need for...
According to one of STL devs in Reddit, the stl modules like stl.core or stl.io are just a Microsoft thing and is intended as a starting point for a C++23 proposal. They're just a repackaging of the existing Standard Library with no organizational changes other than dividing them into five or so groups. You can found m...
61,796,576
61,810,573
HTTP request with C++
I need to send an HTTP request to the server (www.google.com) and get a response. All this I implement in C ++, and I need a library of minimum size. I tried connecting curl, cpr in Visual Studio, but not successfully. P.S. I'm new to C ++. Thank you everyone :D
How can i install curl in VS I suggest you could try to use vcpkg to install curl: 1,Get vcpkg from: https://github.com/microsoft/vcpkg/archive/2019.08.zip and extract it to a folder of your choice (e.g. C:\vcpkg\) 2,Open Developer Command Prompt for VS 2017 (see Windows Start menu or %PROGRAMDATA%\Microsoft\Windows\S...
61,796,664
61,797,103
lambda function uses its parameter as template parameter calling template function
The following is the sample code, which cannot compile. We use iteration function to iterate over some range and run the lambda callback function. The iterate function will pass some indications (i.e. type) to the callback lambda function, which will then do works based on indications. Since these indications are fixe...
You can't use a run-time variable as a template parameter, which should be a compile-time constant. But you can wrap constants into std::integral_constant to encode a constant value into a type: template<typename Func> void iterate(Func func) { for(int i = 0; i < 5; ++i) func(std::integral_constant<int, 0>{...
61,796,703
61,796,903
Array of objects prints blank string
(The issue has been solved and the solution has been added as comment line to main.cpp) The problem I'm having is described in the main.cpp file. I already checked another questions about this and none of them really helped. I'm trying to create a console application with C++ where you can add BOOKS to the LIBRARY. In ...
one problem in your code is that you have many instances of a library class so addBook is landing in one object and displayInfo in a new one (empty one) you have to: int main() { Library obj1; // declare the lib in scope for all the cases while (true) { int number; // Ask user what to do cou...
61,796,758
61,820,432
Matrix class content using shared_ptr?
class Matrix { private: int rows; int cols; int** Mat; public: Matrix(){} Matrix(const int& rows, const int& cols):rows(rows),cols(cols) { Mat = new int* [cols]; for (int i = 0; i < rows; i++) { Mat[i] = new int[cols](); } } Matrix operator +(c...
#include <iostream> #include <memory> #include <cassert> class Matrix { private: int rows; int cols; std::shared_ptr<std::shared_ptr<int>> Mat; public: Matrix() = default; Matrix(const int& rows, const int& cols) : rows(rows), cols(cols) { Mat.reset(new std::shared_ptr<int>[rows], []...
61,796,907
61,799,465
Why does my wired sphere turn into ellipsoid when translating and changing camera angle?
I need to translate my wired sphere along z-axis back and forth while also changing camera angle. Whenever my sphere gets translated, it slowly turns into ellipsoid. I really don't understand why. Here you can see pieces of code where I believe is a mistake. Also, shapes shouldn't be changed when resizing the window, o...
[...] while also changing camera angle. Whenever my sphere gets translated, it slowly turns into ellipsoid. That's caused by the Perspective distortion or wide-angle distortion and increases towards the edge of the view. The effect can be decreased by reducing the field of view angle, but the effect will never be can...
61,797,004
61,797,275
c++ Replace macro fuction that calls a method of an object
I am working on a code that can't be rewritten completely. Somewhere in the code I have this snippet #define ITERATE_AND_CALL(vectorOfObjs, function)\ do\ for(auto & v : vectorOfObjs)\ {\ v.function();\ }\ while(false)\ later on in the code it is called like this in several ...
The do/while(false) thing is a way to protect the macro from accidents when you use it in an if statement. You can replace the macro with a nice function template: template <typename Container, typename FPtr> void ITERATE_AND_CALL(Container& container, FPtr callable) { for (auto& v : container) (v.*callable)()...
61,797,224
61,797,502
Can I use a member variable of type ofstream initialized in the class constructor?
I'm having issues declaring a constructor of an inherited class. class Report{ public: string fileName; std::ofstream outputFile; Report(string fileName, ofstream outputFile) { fileName = fileName; outputFile = outputFile; //<-- error here } void returnFile(string, ofstream); ...
You can't pass it by copy, you can't copy one, but you can pass it by reference and initialize it in the initializer list of the class: Demo class Report { public: string fileName; std::ofstream &outputFile; //reference here // reference parameter, and initializer list Report(string fileName, ofstream ...
61,797,230
61,797,712
Add interface library as SYSTEM in modern CMake
I'm currently transforming my C++ project from simply using a Makefile to using CMake. As I'm unfamiliar with CMake, I try and avoid learning "old" CMake and stick to "modern CMake" best practices, e.g. described here. However, I could not figure out how to include a simple, header-only, third party library without get...
To add a header-only library in modern CMake, you can use target_include_directories with SYSTEM INTERFACE. You can place this in your top-level CMake file, before processing the src/CMakeLists.txt file: add_library(foo INTERFACE) target_include_directories(foo SYSTEM INTERFACE ${CMAKE_SOURCE_DIR}/third-party-lib/...
61,797,322
61,797,937
while reversing string 'my.name.is' i'm getting output as 'is@.name.my'. I don't understand from where '@' came from
Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. Input: The first line contains T denoting the number of testcases. T testcases follow. Each case contains a string S containing characters. Output: For each test case, in a new line, output a ...
When you do char c[siz]; for(int i =0;i<siz;i++) { c[i] = s[i]; } you don't append a 0 to c[] to mark the end of the string. If you used siz + 1 as an array size, and put a zero (null character) at the end, it would work. But still, you should not use VLAs.
61,797,355
63,964,901
C++ Efficient arithmetic operator overloading for class containing Eigen matrices
I want to construct a class that contains several Eigen Matrices or Vectors. I want the objects to behave as mathematical vectors: therefore I want to overload +, - and *(by a scalar). I want to do very many linear combinations of these objects, so I would like to implement it in a way that it takes full advantage of E...
I tried to solve the problem by myself. I tried several versions and compared them with directly summing Eigen vectors. The first strategy follows What are the basic rules and idioms for operator overloading?: using realValueType = double; const int NDim = 1000000; using InternalVecType = Eigen::Matrix<realValueType, E...
61,797,371
61,797,689
save function to same adress in each runtime
I have an object that has an array of pointers to functions as config value like this: class Object{ public: bool (*function[2])() = {}; }; bool fooFunc(){return true;} bool barFunc(){return false;} Object obj; void setupObject(){ obj.function[0] = &fooFunc; obj.function[1] = &barFunc; } I am on a µ...
Is there a way to write functions specify the address to which a function is written to? No. Not in standard C++. Choosing the address is something that the linker does. How to configure the linker to store the functions in manually chosen address, I don't know; It'll probably depend on what linker you use. I could ...
61,797,485
61,798,001
Understanding C++ struct with explicit and default values
I have a hard time understanding the following code, can someone please elaborate. struct WUpdate { explicit WUpdate(std::string id = "", std::string message = "") : id(std::move(id)), message(std::move(message)) {} explicit WUpdate(const UpgradeJob& job) : id(job.m.id), message(job.message) {} ...
the code compiles but when running I can see that the value of time is always set to -1, regardless of what I try to initialise it with. None of the explicit keyword or that default value thing you mentioned has anything to do with time being always set to -1. You simply forgot to initialize time in the constructor a...
61,797,586
61,798,203
Remove progressbar border
How can I remove the white border from the progress bar? HWND hProgress = CreateWindowEx(0, PROGRESS_CLASS, NULL, WS_CHILD | WS_VISIBLE | PBS_SMOOTH, 29, 215, 492, 32, hwnd, (HMENU)0, hinst, NULL); SendMessage(hProgress, PBM_SETBARCOLOR, 0, (LPARAM)RGB(12, 12, 12); SendMessage(hProgress, PBM_SETBKCOLOR, 0, (LPARAM)RGB(...
I believe this does what you're after. You probably want to modify the style before sending the progress bar any messages or you'll need to force it to redraw after. long style = GetWindowLong(hProgress, GWL_EXSTYLE); style &= ~WS_EX_STATICEDGE; SetWindowLong(hProgress, GWL_EXSTYLE, style); The top is without the chan...
61,797,825
69,830,955
QT5 Switching between Widgets size problem
I try to switch between two different Widgets in QT5. The first problem was that my first window was visible in the background of my second window. I solve this with a check in "autoFillBackground". Now i can switch between them, but if i resize them it only resize the Main content. Both Widgets have a grid layout. Res...
Update (based on the comments): The best solution was to use the QStackedWidget to navigate between the views. Docu: https://doc.qt.io/qt-5/qstackedwidget.html#details Example-Code for Button: // return back to first view void MainWindow::on_btnret_clicked() { ui->stackedWidget->setCurrentIndex(0); }
61,797,861
61,797,905
copy from std::priority_que into typdef edge
I have typedef std::pair<int , std::pair<std::string, std::string>> edge; I placed my edges into a std::priority_que<edge, std::vector<edge>, Compare> que; When I now try to que.pop() back into an edge variable a get an error. Why is that? que = priority_que with edges edge e = que.pop() // this does not work
Because std::priority_queue::pop() doesn't return anything. You need to call top() first to extract element. edge e = que.top(); que.pop();
61,797,944
61,798,202
Why GL_RASTERIZER_DISCARD does not enable me to write to stencil buffer?
I want to draw outline with stencil buffer in 3 passes. normal drawing pass outline mask generating pass outline drawing pass the second pass does not need fragment shader to work, because it only writes to stencil buffer, so I use glEnable(GL_RASTERIZER_DISCARD); to prevent touching fragment shader at all. Problem i...
From "What actually does GL_RASTERIZE_DISCARD": When enabled, primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage (see section 13.2) Given that you want to draw to the stencil buffer, you still want rasterization, just not to the color buffer . For that...
61,798,146
61,798,242
Difference between CSV files which makes different outcome using getline()
I'm writing a function which reads a CSV file using getline() and converts data to the vector of vectors. To test it I've tried to read two files with the same delimiter: one imported from the internet and second exported from R datasets. The first few lines of each looks like: File1.csv User ID,Category 1,Category 2,C...
The problem is here: while(fin>>temp){ row.clear(); //Read line and store in 'line' getline(fin,line); fin >> temp reads everything till the first space or newline. It is not clear why you do that as only with getline(fin,line) you then try to read the full line and you are not using temp. In t...
61,798,752
61,799,402
pass any object to function to create this object
I'm making a small generative video layering software using openframeworks and c++. To this effect I have one main class, one layer class and a lot of different types of video/simulations class. I need to make it so that when I press a key, a different simulation is loaded. I have two questions : How can I access a ...
Best method to do this is to use something called the factory pattern. Basically, define a function that takes an argument of some defined type that can be used to figure out what kind of simulation you want, and then create that simulation and return a pointer to it. A simple version of it might look like this: enum ...
61,799,267
61,799,520
Cannot pass a const char string to a template class
So I just made a PoC template class to be able to experiment with templates. I want to keep my code as it was done before, so I decided to simply use C-style strings and not std::strings. I'm using C++17 and microsoft compiler on visual studio 2019. Here it is: template <typename T1, typename T2> class Human { private:...
The culprit here was the move semantic at my constructor && which could not take in the c-string.
61,799,547
61,809,160
Invalid UTF-8 data when using std::locale to format numbers in French
I'm using the following code to format numbers using the proper locale. When using French, numbers have "non-breaking space" between groups of digits. The string I'm getting seems to be invalid. std::stringstream ss; ss.imbue(std::locale("fr_FR.UTF-8")); ss << 1234; auto result = ss.str(); here, result...
The problem is that std::locale doesn't support multi-byte digit separators because std::numpunct::thousands_sep only returns a single code unit (char in this case). As a result, in your case, the digit separator NO-BREAK SPACE 0xC2 (-62) 0xA0 (-96) gets truncated and you only see the first code unit 0xC2 (-62) which i...
61,799,647
61,801,188
C++: implementing a global constant whose value is given by the user
First of all, let me say I have read similar threads on how to initialize a global variable or how to properly implement global constants. Nevertheless, these questions did not really help me with my concrete problem, as also haven't any other ressources I've consulted. The problem is the following. I (have to) declare...
Think about it: If a value needs to be set during the lifetime of a program, it's not really a constant. So, you shouldn't try to pretend it's a constant by declaring it as const. If you don't want the program to accidentally change its value, you have to protect it in some other way, such as making it a private mem...
61,799,805
61,800,787
Integrating QT with CMAKE in Mac OS
I am trying to integrate my QT project to my CLION project. In this case I am having problems with the CMAKE and QT integration. The content of my CmakeList.txt is: cmake_minimum_required(VERSION 3.12) project(BD2_PROYECTO_1) set(CMAKE_CXX_STANDARD 17) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_PREFIX_PATH "/Use...
after some tries, I found the solution to my problem. So I am posting my CMakeList.txt code in case you have the same problem. cmake_minimum_required(VERSION 3.12) project(BD2_PROYECTO_1) set(CMAKE_CXX_STANDARD 17) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_PREFIX_PATH "/Users/jonathanprieto/Qt5.13.0/5.13.0/clang_64/...
61,800,163
61,800,751
How do you build wxWidgets samples on linux
I have recently downloaded wxWidgets (installed from source but I don't think that is the problem) and I cannot figure out how to build the samples provided on linux. From what I can tell all the makefiles given are for windows machines and from the few things I have found online just say to run make in the directory b...
You need to run the configure script to generate the make files for your system. There is a good article on this on the wiki. The configure script will produce make files for both the library and the samples. On linux, this 2 step configure/make process is quite common for building libraries and programs.
61,800,289
61,807,661
How to determine PdfPage object emptiness?
Let's have following snippet of code: PoDoFo::PdfMemDocument pdfDoc; pdfDoc.CreatePage( PoDoFo::PdfPage::CreateStandardPageSize( PoDoFo::ePdfPageSize_A4 ) ); the newly created page is clearly empty. How can one determine such a page is empty (with no xobjects, etc. inside). I've tried to lookup any kind of method like...
After few painful hours I've managed to solve the issue (could be done smarter, but whatever): /// @param page Page object to be checked for emptiness. /// @return True in case page is empty, false otherwise. bool isDocumentPageEmpty( const PoDoFo::PdfPage* page ) { PoDoFo::PdfContentsTokenizer tokenizer( const_cas...
61,800,403
61,801,417
C++ How to make derived class to take base class parameters automatically
When I change a value in base class and then, later on, create an object of the child class, child class created with an empty parameter instead of the changed value. Is there a way to object of derived class with the parameters of the base class? Example: Base.h class Base { class Child; public: int number = 0; ...
Here is how it is typically done in C++: #include <iostream> class Base { public: int number = 0; virtual ~Base() = default; void Setup() { number = 5; } }; class Child : public Base { // number exists here because of inheritance. }; int main() { // Child object seen as Base o...
61,800,509
61,800,987
Input operator overloading with a function
I am a bit new at C++ and I have to solve the following exercise: I have to create an object of class Sum(limit) where the user can input numbers until the sum of all the inputs reaches the limit. The main function has to look like this and cannot be changed: int main (){ Sum sum(100); std::cout << "Enter numbe...
Let's look at what we have to work with here... You have a newnumber() function that'll take an int and add it to your Sum object. In your insertion operator overload, you're given a Sum object and an istream object. We know we have newnumber() on the Sum object, but we can only use it if we have an int! So how can we ...
61,800,548
61,801,285
Stack of strings with templates?
I'm trying to make a push function for my class Stack but I keep getting errors. This is my code: (before you ask, I know using namespace std is a bad idea; we are required to use it now...). header: #pragma once #include <string.h> using namespace std; template <class T> class Stack { T List[100]; int size; pu...
You don't need to use strcpy here, you can just use = to assign the input: void push(const T &x) { List[size++] = x; } There are some other issues in your code. In pop, you are not decrementing size, and you are not returning if the List is empty. One option is just to throw if there is nothing to return: const T& ...
61,800,559
61,800,753
-fshort-wchar and std::wstring - segmentation fault
I use Ubuntu 18.04 and gcc 7.5.0. I have a library which is compiled with -fshort-wchar. I have noticed that using std::wstring in the library may leads to the segmentation fault. I have found a similar topic. There is an explanation: -fshort-wchar is not usable if you want to interact with any part of the standard l...
-fshort-wchar sets the size of wchar_t to 2 bytes Now think about what will happen if you use a part of the standard library that is not header only. A big part of the standard library is compiled into a library that you link with (libstdc++ / libc++). When that was compiled -fshort-wchar was not used and the...
61,800,591
61,800,712
How to Get text from Edit form in winapi?
I have wstring note and I want to get informaiton from my Edit box to this wstring note. I use : GetWindowText(hWnd, note.c_str(),100); But it shows an error. Argument of type "const wchar_t* is incompatible with parameter of type "LPWSTR". What is good solution for this?
The c_str() function returns a pointer to const memory. The GetWindowText wants a pointer to non-const memory. One solution in this case: wchar_t buffer[100]; GetWindowText(hWnd, buffer, sizeof(buffer) / sizeof(buffer[0])); note = buffer; Or: std::array<wchar_t, 100> buffer; GetWindowText(hWnd, buffer.data(), buffer.s...
61,800,674
61,810,021
Trying to understand a detour (hooking) function
Hi I'm trying to understand a function, it's about Windows API hooking. I'm trying to hook LoadLibraryA to see if any cheats are trying to inject into my game. For that I'm trying to intercept any calls to LoadLibraryA. I tried to write comments to explain what I think is going on, but I'm unsure about the latter part...
The function works fine, just need help in understanding whats going on in the later part > of the function. I'm unsure what happens from here jmp += len; First thing I notice is your code is doing the detour and the jmp back all in one go, which is different than I usually see people do it. memcpy(jmp, src, len); ...
61,800,893
61,801,312
Do you have to ship proto files with your project?
I'm making a game engine in c++ and working with protocol-buffers for the first time. I'm not sure if I need to have my proto files accessible by the running game in order to serialize and deserialize objects. I ask this because I'm using util::MessageToJsonString and it's crashing trying to load the proto file. I assu...
I got confused, proto files do not need to be shipped with the project. I had shutdown protobuf before trying to serialize a message. While debugging I saw the name of my protobuf file being used. This was a red herring.
61,801,379
61,801,703
Make sure that mocked GTest method overrides virtual method
I would like to make sure that a mocked method overrides base class virtual method. Is it possible to use MOCK_METHOD in the way when it generates method marked as override?
You can do that by specifying the specs parameter to the MOCK_METHOD like so, MOCK_METHOD(void, foo, (), (override)); Quoting https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#creating-mock-classes The first 3 parameters are simply the method declaration, split into 3 parts. The 4th para...
61,801,794
61,801,843
For a char[] of size 20, if i enter char from char[0] to char[7], and i write the char[] to a file, does it take up 20 bytes or 8 bytes on the disk?
Here is a sample code char text[20]; fstream file("temp.dat",ios::binary|ios::in|ios::out|ios::app); cout<<"Enter the text: "<<endl; cin>>text; //assuming text entered is elephant // file write operation file.write((char*)(&text),sizeof(text)); // file write operation done so if the char array of size 20 is storing t...
Since you use sizeof, it takes all the array, with \0 where there is no text. You could use strlen to limit to the length of the sting. All this C-like approach however is bad. Lots of overruns, under runs, serialization issues etc. Use std::string instead. In Windows you also want Unicode text.
61,801,804
61,801,844
Why exception is thrown at the end of this code?
int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; int* ar1 = new int[n]; int* ar2 = new int[n]; /*int ar1[n]; int ar2[n];*/ for (int i = 0; i < n; i++) { cin >> ar1[i]; } for (int i = 0; i < n; i++) { ...
The condition in this loop is wrong: for (int i = 0; i < n, k>0; i++) since it might fail even when i>=n (the condition will evaluate i<n, ignore it, and only check if k>0). Instead, you need to do: for (int i = 0; i < n && k > 0; i++) to check that both the conditions are satisfied. Otherwise, you are potentially ...
61,801,846
61,802,225
How can I avoid arithmetic overflow in c++?
This is a part of my code that I have a warning when I compile, I can't understand how to avoid an arithmetic overflow problem void read(int pn) //read person number pn { ifstream infile; infile.open("data.txt", ios::binary); infile.seekg(pn * sizeof(makers)); // this is the line I get warning infile.re...
The type expected by seekg is streampos, so do the following: infile.seekg(static_cast<streampos>pn * sizeof(makeres));
61,802,025
61,802,242
Inheriting class with multi parameter pack variadic template
I have a variadic template class with multiple parameter packs, something like this: template <typename... Types> struct TopicsList { }; template <typename... Topics> class TheParent; template <typename... OutputTopics, typename... InputTopics> class TheParent<TopicsList<OutputTopics...>, TopicsList<InputTopics...>> ...
What about template <typename... OutputTopics, typename... InputTopics> class TheChild<TopicsList<OutputTopics...>, TopicsList<InputTopics...>> : public TheParent<TopicsList<OutputTopics...>, TopicsList<InputTopics...>>, public ::testing::Test // ....................^^^^^^^^^^^...............^^^^^^^^^^^^^^............
61,802,165
61,802,231
How can an declare an array in a function that returns an array in c++
// functions that converts a number into an array int *initialiser(int number) { int array[20]; for (int i = 19; i >= 0; i--) { array[i] = number % 10; number /= 10; // number = number/10 } return array; } //I get this error primaryAddSub.cpp: In function 'int* initialiser(int)': ...
As the comment says, prefer to use a std::vector instead of an int*. An example of how this works would be: std::vector<int> initialiser(int number) { std::vector<int> array; // ... fill up array return array; } If you absolutely want to return an int*, then as the error says, you are returning a pointer...
61,802,254
61,803,467
Base class undefined, but its header is included
I'm having some troubles where a function isn't returning the right type, because a class isn't defined. I'm using a factory pattern. The two error messages that I'm getting are: 'return': cannot convert from 'DLA *' to 'Layer *' and: 'Layer': base class undefined (compiling source file src\Layer.cpp) and this ...
As they stand, your header files induce circular dependency, even though the #pragma once (and other) guards prevent any actual 'infinite recursion'. Let's look at the sequence of code, from the compiler's point-of-view, when compiling the Layer.cpp file (or any other '.cpp' source that has #include "Layer.h" in it). T...
61,802,399
61,802,546
Why does results are different when relational operators means the same?
For clarification, let's consider the following program: #include <iostream> int main(void) { short int i; // declaration short int value; short int sum; i = value = sum = 0; // initialization std::cout << "Enter a value: "; std::cin >> value; while (i != value) { // ### here's the confu...
This while loop while (i != value) does not include the iteration when i is equal to value because in this case the condition i != value evaluates to false. This while loop while (i <= value) includes the iteration when i is equal to value because in this case the condition i <= value evaluates to true. In fact the f...
61,802,544
61,803,014
Is there a quick way to zero all the static members of a class?
I have a class with static members that get reset to zero each loop, so something like: class Stats { static inline int counter1, counter2; static inline float time; static void resetStats() { counter1 = 0; counter2 = 0; time = 0.f; } } With a non-static class I can create a new ob...
Make the the variables non-static members of a class, and use a static instance of that class. This way you can use value initialisation to set all members to zero: class Stats { static inline struct { int counter1, counter2; float time; } data; static void resetStats() { data ...
61,802,577
61,802,696
Why is valgrind reporting two memory allocations when my code only requests one?
When I run the following program through valgrind (valgrind ./a.out --leak-check=yes): int main() { char* ptr = new char; return 0; } the report contains this: ==103== error calling PR_SET_PTRACER, vgdb might block ==103== ==103== HEAP SUMMARY: ==103== in use at exit: 1 bytes in 1 blocks ==103== total he...
As you surmise, the extra allocation is part of the runtime, and it is correctly cleaned up as you can see in Valgrind's output. Don't worry about it. If you're asking specifically what it is, you'll have to read the C++ runtime library of your specific compiler and version (libc since you're using gcc). But again, it...
61,802,629
61,803,503
How do I unit test (default) move operations?
I ran into this when I tried to write unit tests for a move-only class. I don't know how to write a test which checks if move operations actually moved the class's data members. I included here a simplified example of a class that parallels what I am working on. In reality that class supports a few more operations and ...
Here is a way to track the state of an object with a Marker member variable. Keeping in mind that std::move does not mean the object will be moved from, it only makes the object eligible to be moved from. Once an object has been moved from, its in a "valid but unspecified state" suitable for either being destructed or...
61,802,697
61,802,746
Nth Day of Christmas with recursion in C++
I want to solve this with recursion, but I am having trouble figuring out whats wrong. Create a function where given n days as an argument, return the total amount of items received throughout Christmas days as an integer. xmasItems(1) = 1 xmasItems(3) = 10 : Day1 = (1), Day2 = (1+2), Day3 = (1+2+3) | Day 3 total = (...
In the while loop of your else branch, you are decrementing n all the way to 0. So you are computing only the first day's value. Instead, you could use a copy of n for the forThatDay calculation, so you can make the recursive call correctly: int xmasItems(int n) { if (n == 0) { return 0; } else { int fo...
61,802,857
62,143,983
Linker error encountered upon attempting to use RtlInitUnicodeString()
The function RtlInitUnicodeString() used to initialize the UNICODE_STRING structure cannot be used as a linker error stating that an unresolved external symbol RtlInitUnicodeString referenced in function ***func_name*** (LNK2019) is thrown during compilation. I tried using the statement #pragma comment(lib, "NtosKrnl.l...
The function cannot be called directly as they belong to the internal API and their mere prototype header is exposed via the winternl.h header file (at least in this case). In order to use the functions that are part of the internal API, one can either use run-time dynamic linking to link the Ntdll.dll library as state...
61,803,112
61,803,349
Activating blocks of code with [#define & #ifdef] cross-file
I don't know what this concept is called, so title may sound weird. Imagine the following scenario: main.cpp: #define SOME_KEYWORD int main() { foo(); return 0; } other.cpp: void foo() { //Do some stuff #ifdef SOME_KEYWORD //Do some additional stuff #endif } I've tried it out and it doesn't work if...
In c++, from c++17, a constexpr-if would be a good way to go about doing this. e.g. in some header file: // header.hpp #pragma once constexpr bool choice = true; // or false, if you don't want to compile some additional stuff and in an implementation file: #include "header.hpp" void foo() { //Do some stuff i...
61,803,664
61,803,910
Chromium `debugger` equivalent, on `gdb` for Cygwin?
How do people trigger a breakpoint on gdb (for Cygwin, specifically) from the very source code? Like when a JS script has the debugger word in it and Chromium dev tools trigger stop for debugging?
Here's how SDL2 implements this feature: #if defined(_MSC_VER) /* Don't include intrin.h here because it contains C++ code */ extern void __cdecl __debugbreak(void); #define SDL_TriggerBreakpoint() __debugbreak() #elif ( (!defined(__NACL__)) && ((defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) ||...
61,803,924
61,806,276
Sample code for c++ WxWidgets blit an image to the canvas
I am trying to make a basic GUI using wxWidgets and wxFormBuilber to display a chess gameboard and chess pieces from a sprite sheet. I would really appreciate some sample code for: uploading an image from a file blitting an image at a specific location
Here's a simplest example I can think of. This uses this set of pieces from wikipedia (licensed under the Creative Commons license). This example only draws the black pieces, but you should be able to figure out how to draw the white pieces with a few simple modifications. // For compilers that support precompilatio...
61,803,954
62,093,937
Which C++ standard library headers invoke a requirement for the -pthread option with GCC?
If you use C++ threads with the GCC compiler (or perhaps more accurately, with the libstdc++ C++ standard library which ships with GCC) on Linux, you may need to include the -pthread option in your build process to get things to compile and link properly. What I'm curious about is which library headers invoke that requ...
<thread> <mutex> <condition_variable> <future> <shared_mutex> <stop_token> all use Pthreads types and functions. The Networking TS headers such as <experimental/net> and <experimental/executor> use <mutex> and <future> so they also depend on Pthreads. We'll soon be adding more concurrency headers such as <latch> <barr...
61,804,142
61,804,185
Why would you perform a Bit-shift twice ((x >> 4) << 4)?
So I am analyzing a Nes-Emulator code and I've come across this line of code that I can't make any sense of: nMapperID = ((header.mapper2 >> 4) << 4) | (header.mapper1 >> 4); Why is header.mapper2 bit-shifted once to the right and then to the left. The header by the way is this struct: struct sHeader { char name[4...
A bit-shift is not a rotation of bits. The new bits that appear are all 0s. So this expression: (header.mapper2 >> 4) << 4) first clears the 4 lower order bits, and then shifts all the bits back to the left. e.g. if you had a bit pattern like 01010101, the right-shift would first make the bits 00000101, and then the l...
61,804,175
61,805,099
How can't I sort by a number in descending order of course code
I am writing a program to manage a list of records. The user first inputs several records, until the string "END" that indicates the end of input. Then input a student id and output all record of the student in descending order of course code I am trying to use a bubble sort to do this, but I don't know why my program ...
Please don't use parallel arrays. Your issue is an example of the complexity of using parallel arrays. Use a collection of structures: struct Student { std::string subject; std::string id; double mark; friend std::istream& operator>>(std::istream& input, Student& s); }; std::istream& operator>>(st...
61,804,236
61,825,827
How can I put white spaces in Title of QGroundControl?
Is there a way that I put the white spaces in the QGroundControl? I am new to this and not sure much about QML or qmake. I want to change title from “QGroundControl” to “Q Ground Control”. I tried to do the change in the “qgroundcontrol.pro” at the below line, but this didn’t worked as I was expecting. FROM: DEFINES +=...
Fixed my issue by using the correct escape sequence: DEFINES += QGC_APPLICATION_NAME='"\\\"Custom QGroundControl\\\""'
61,804,457
61,818,735
Read values from unsigned char bytestream in C++
my task is to read metadata values from a unsigned char array, which contains the bytes of a binary .shp file (Shapefile) unsigned char* bytes; The header of the file which is stored in the array and the order of the information stored in it looks like this: int32_t filecode // BigEndian int32_t skip[5] // Uninteresti...
So 'reading' a byte array just means extracting the bytes from the positions in the byte array where you know your data is stored. Then you just need to do the appropriate bit manipulations to handle the endianess. So for example, filecode would be this filecode = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) |...
61,804,557
61,805,186
Pass array of structs by reference
I would like to pass an array of structs to a function. struct Month { std::string name; int days; }; Month months[12]{{"January", 31}, {"February", 28}, {"March", 31}, {"April", 30}, {"May", 31}, {"June", 30}, {"July", 31}, {"August", 31}, {"September", 30}, {"October", 31}, {"November", 30}, {"December",...
Since you will treat the content of Month as constant, simply pass a rvalue reference, e.g. Month*&& m. Example: void showmonths (Month*&& m, size_t nmonths) { for (size_t i = 0; i < nmonths; i++) std::cout << std::left << std::setw(12) << m[i].name << m[i].days << '\n'; } For further details on the declar...
61,804,604
61,805,443
How to expand parameter pack pattern in an "unzipping" manner?
Say I have a variadic function, foo: template <typename... Args> void foo(Args... args) { // some work } I want to have a magic function, bar, that forwards its arguments to foo in the following manner: Say if I call bar(x, y, z); It'll have the same effect as foo(x.begin(), x.end(), y.begin(), y.end(), z.begin()...
If you can use C++17, apply std::apply: template<class ... Conts> void bar(Conts&& ... c) { auto t = std::make_tuple( std::make_tuple(c.begin(),c.end())... ); // tuple< tuple<C1.begin,C1.end>, tuple<C2.begin,C2.end>, ... > [1] std::apply( [](auto&&... tuples){ auto oneTuple = std::tuple_cat(...
61,804,666
61,804,912
Call overridden method from base class
How to call overridden bar method from base class in the following scenario? There is requirement that callback should always call method foo which should call bar which is overridden by latest derived class. #include <iostream> #include <functional> #include <typeinfo> using namespace std; std::function<void(void)>...
You are binding the virtual method with the derived object improperly, slicing the derived object. Try this (* is removed) Base(Base *ptr){ callback = std::bind(&Base::foo, ptr); }
61,804,886
61,805,048
Linked List delete operation not working in visual studio using C
when I tried to implement a linked list in visual studio 2019 using c it produces heap error. It was due to the free function. However, the code works fine on online compilers which use the GCC compiler. https://www.jdoodle.com/c-online-compiler/ I can't able to figure it out.......................... here is the code...
The sizes you're passing to malloc are wrong. You should pass sizeof(struct Node). If you're compiling this as C++ you shouldn't be using malloc at all.
61,805,296
61,805,608
How are hash maps implemented in c++?
How is mymap[key]++ visualized. Am I incrementing the key or the value? In LINE 1 hash[numberToFind] is the key or the value that I am inserting into the result? unordered_map<int, int> hash; vector<int> result; for (int i = 0; i < arr.size(); i++) { int numberToFind = target - arr[i]; if...
Consider going to a good reference before asking on stackoverflow.com. cppreference.com is pretty good. https://en.cppreference.com/w/cpp/container/unordered_map key is the key. mymap[key] returns a reference to the element in mymap at key key. If key is not yet in mymap, mymap[key] default constructs an element at ke...
61,805,811
61,805,923
Operator bool() conflicting with template Type() operator when Type = bool
My template operator is conflicting (overloading) with the bool operator when template type is bool. Any way of getting around this? For example, can I somehow "turn off" the operator T() when T is assigned to bool? template <typename T = bool> class MyClass { public: operator bool() const { return false; } ope...
You can use SFINAE to disable to operator bool when T is a bool like template <typename T = bool> class MyClass { public: template <typename U = T, typename std::enable_if<!std::is_same<U, bool>::value, bool>::type = true> operator bool() const { return false; } operator T() const { return t; } private: ...
61,806,283
61,806,405
How to make a function wrapper that can wrap any function?
#include <iostream> #include <string> template<typename Func> class FuncWrapper { Func func; std::string name; public: FuncWrapper(Func func, std::string name) : func(func), name(std::move(name)) {} template<typename ...Args> auto operator()(Args ...args) { std::cout << "Entering " + nam...
You might use Raii: template<typename ...Args> auto operator()(Args ...args) { struct EndScope { std::string& name; ~EndScope() { std::cout << "Exiting " + name + "\n\n"; } } endScope(name); std::cout << "Entering " + name + '\n'; return func(args...); } You might go further to handle ...
61,806,378
61,806,490
Parse a whole (beginning to end) string in C++, including all whitespace
I'm looking for a way to generically parse a whole string in C++. What I mean by that is that the entire string is used in the parse, or else it's an error. This means that the naive operator >> behavior, which delimits on whitespace for most types, is not what I want (though I'd be perfectly happy if the solution invo...
For a double this can be achieved with std::stod after first reading your input as std::string. std::optional<double> parse(std::string const& str) { std::size_t num = 0; try { auto const res = std::stod(str,&num); if (num < str.size()) return std::nullopt; return res; } catch (...) { return std::...
61,806,536
61,807,094
Applying a simple Tesselation Evaluation Shader
I'm trying to learn how to use tesselation to render simple polygons, and for a starter I'm trying to write a simple program that essentially would just draw whatever vertices it's given, without any extra logic. My three shaders compile without error, but when I try to apply the program OpenGL returns error 1282. Base...
There are two problems. The first is that the vertex shader output is not being consumed by the tessellation evaluation shader. The VS outputs gl_Position, but the TES doesn't read gl_Position. It instead reads a user-defined input positionIn, which has no linkage to the value of gl_Position. Indeed, it has no value at...
61,806,545
61,806,724
How to handle texture animation in OpenGL?
I started using OpenGL with SDL2 and GLEW not so long ago, and I got two questions: How to pass a texture to GLSL's uniform sampler2D ? It seems to do it automatically when binded, but it confuses me. And the main question here: What's the best way to handle texture animation? Should I do it by GL_TEXTURE_3D? By lo...
glActiveTexture and glBindTexture calls in this order will bind a texture to the given sampler slot. Use a spritesheet as a TEXTURE_2D, and change the texture coordinates for swapping the animation frames.
61,806,912
61,807,237
Eclipse/CDT_C++ giving a "Semantic Error _"type XXX could not be resolved". The projects runs
I am completely new to programming and I am learning C++. I wrote a code to practice Functions with Return Values. The code builds and runs, but there is an error message and I would like some help understanding it. #include <iostream> using namespace std; void showMenu() { cout << " 1. Change personal informatio...
You passed undeclared identifier selection to processSelection function. Just pass menuSel to processSelection, so your main should look like this: int main() { cout << "" << endl; showMenu(); int menuSel = getInput(); processSelection(menuSel); return 0; }
61,807,003
61,807,306
Why does not read in a Struct with a pointer?
I've got this code, and for some reason the cin.get does not assign a value to the p.name[i]. I don't know why, but getline does not work aswell. I've tried to just cin.get(temp,30), to read a temp, but this dont work in the for cycle. #include <iostream> #include <string> using namespace std; typedef struct echip { ...
Place the cin.ignore() before the cin.get(): Live demo #include<limits> //... for (int i = 0; i < n; i++) { cout << "Name: "; cin.ignore(numeric_limits<streamsize>::max(), '\n'); //here cin.get((p + i)->name, 30); cout << (p + i)->name; cout << "Price: "; cin >> (p+i)->price; ...
61,807,285
61,807,885
Android Studio | CPP file errors error: undefined reference to 'AndroidBitmap_unlockPixels' In bitmap library
I'm trying to use AndroidJniBitmapOperations library. But I'm a Junior Dev, with no knowledge in the NDK, JNI world. I succeed to resolve a few errors like 'UnsatisfiedLinkError', but Now I'm getting a new one when I trying to build: error: undefined reference to 'AndroidBitmap_unlockPixels' Also I get a few errors i...
You need to link the library that provides that API. In https://github.com/LiorA1/MyRevApp/blob/master/app/src/main/cpp/CMakeLists.txt, copy the code that you have for the logging library like so: find_library(log-lib log) find_library(jnigraphics-lib jnigraphics) target_link_libraries(JniBitmapOperationsLibrary ${log-...
61,807,613
61,807,666
What is the difference between it.first and it->first?
for(auto it = M.begin(); it!=M.end();it++) { cout<<it->first<<" "<<it->second<<"\n"; } The above code works absolutely fine But, for(auto it : M) { if(it->second == 1) return it->first; } This gives me an error. Why do I have to use it.second and it.first instead of it->second a...
In the first loop, you use iterators to iterate over the container M. Iterators emulate pointers, and have to be dereferenced to give the value the iterator is "pointing" at. In fact, for that loop, it->first is really the same as (*it).first. In the second loop, you loop over the values in the container M. The loop it...
61,807,754
61,808,207
Create a smart-pointer-to-base-class from a reference
I have a container which store a vector of smart-pointer-to-base-class, and I'd like to populate it via a method without requiring my users to also create that smart pointer: class Base { // ... }; class Derived: public Base { // ... }; class Collection { private: vector<unique_ptr<Base>> pointers; publi...
You should probably stick to the template, yes. You then get class Collection { std::vector<std::unique_ptr<Base>> pointers; public: template<typename T> void add(T &&value) { pointers.emplace_back(std::make_unique<std::remove_reference_t<T>>(std::forward<T>(value))); } }; int main() { Col...
61,808,097
61,809,263
Using C++ w/ Lua in a runtime environment
I have looked this question up so many times that I am convinced I am missing a huge piece of the puzzle when it comes to integrating LUA into my C++ Game Engine. What I want to do is run my game engine, then while its running I would like to click on my ui and click "add script" and then run the script. That part is e...
To give a concrete example, suppose you wanted to teleport a ball to the player whenever they click the mouse. Here's what you could write to do that in Lua: local function clickHandler(event) local x, y, z = event.player:getCoords() local ball = event.world:getBall() ball:teleportTo(x, y, z) end game.regi...
61,808,228
61,808,336
'variable': initialized auto or register variable not allowed at function scope in 'naked' function
int __declspec(naked) Testing(int _byte, int _byte_size) { int byte_size = _byte_size; BYTE* bytec = new BYTE[byte_size]; memcpy(reinterpret_cast<void*>(bytec), reinterpret_cast<void*>(_byte), byte_size); int RE_format = 0; } This is whats cause the error, How would I go about fixing this...
Well, the error message is pretty self-explanatory, and the following at least compiles, although I'm not sure what use it is: int __declspec(naked) Testing(int _byte, int _byte_size) { int byte_size; byte_size = _byte_size; BYTE* bytec; bytec = new BYTE[byte_size]; memcpy(reinterpret_cast<void*>(b...
61,808,263
61,809,231
Problem with ASCII Rotating Cursor (TUI) Animation
I'm trying to create the rotating cursor animation thing. Each time I compile this I always get a slash (or two) left at the end, and the backspace character does not work. I used two ways to do this: the sleep function and the chrono timer and they worked very similarly and left a slash after spinning, ignoring the ba...
The output effect is not guaranteed but dividing it into sections might help. Idea: #include <algorithm> #include <chrono> #include <cstddef> #include <iostream> #include <string> #include <thread> using namespace std::chrono_literals; // a cumbersome way to be able to write 100ms // unformatted output of one char, a...
61,808,355
61,808,404
C++ overloading single operator passing 2 structures as pointers
Ok. I have the structure: struct birthdayPerson { int day, month, year; public: void Show() { std::cout << day << " " << month << " " << year << std::endl; } }; Then i want to overload the "==" so it can compare 2 instateated structs if those people has the same birthday (da...
First off, your operator== should take its parameters by const reference: bool operator==(const birthdayPerson &person1, const birthdayPerson &person2) Second, your array contains birthdayPerson* pointers, not actual birthdayPerson objects. Your statement personBirth[0] == personBirth[1] is comparing pointers, which i...
61,808,400
61,812,798
Trying to Beautify this Arduino Code [Beginner here]
complete beginner here, I was wondering if it's possible to simplify this code, to thin it down or shorten it up. As you can easily tell, this thing makes one led turn on when the other is off and viceversa, in a loop. void setup() { pinMode(3, OUTPUT); pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIG...
digitalWrite(13, HIGH); if (digitalRead(13) == HIGH) digitalWrite(3, LOW); After setting pin 13 high, there is no need to read its value. digitalWrite(13, HIGH); digitalWrite(3, LOW); is sufficient. Other than that you don't need to write beautyful code as a beginner. Focus on understanding what is going on an...
61,808,446
61,808,500
Protected Nested Struct Cannot Be Used As Return Type in Derived Outer Class?
I have the following class (simplified) Base Class - ExchangeGatewayUDSHandler.h class ExchangeGatewayUDSHandler : public Instrument::IInstrumentListener { public: explicit ExchangeGatewayUDSHandler(const EGUDSConfig& config); virtual ~ExchangeGatewayUDSHandler(); void ProcessEnque...
In your .cpp files, which are outside of the ExchangeGatewayUDSHandler and ICEGatewayUDSHandler class declarations, you need to qualify UDSValidityInfo in a method return value so the compiler knows where to look for that type, as it has not seen the ExchangeGatewayUDSHandler:: or ICEGatewayUDSHandler:: qualifiers yet,...
61,808,871
61,808,911
Overload resolution and user-defined conversion
Consider this example: struct Foo { Foo(int){cout << "Foo(int)\n";} Foo(double){cout << "Foo(double)\n";} operator int()const{cout << "operator int()\n"; return 0;} operator double()const{cout << "operator double()\n"; return 0.;} }; void bar(Foo){cout << "bar(Foo)\n";} void bar(float){cout << "bar(fl...
Does it mean that standard conversion is preferred over user-defined conversion? Yes. Standard conversions are always preferred over user-defined ones. See this In deciding on the best match, the compiler works on a rating system for the way the types passed in the call and the competing parameter lists match up. In ...
61,809,336
61,809,384
How to identify the symbols in the symbol table are my 'application' functions
I have an example C program test.c that defines three functions only: main, fn1 and fn2: void fn1(void){...} void fn2(void){...} int main(int argc, char** argv){...} Compiling and then extracting the symbol table of this program (via nm ./test) gives a ton of symbols: 0000000000601030 B __bss_start 0000000000601030 b ...
is there any way to differentiate these from the other application symbols? No. I can't find a way to filter my instrumentation pintool written in C++ to the routines within the .text section that I care about It's your application. Surely you can either use consistent naming, or collect a list of symbols you care ...
61,809,337
62,605,686
_Orphan_range crash when using static vector
In my project, I use the constructor of a static object to collect pointers, like a registration method. Very simply, no magic. But during the start I experience a crash, and I can't explain what's happening here. The crash is reproducible on Windows with MSVC or Clang, both using the MSVC headers. Given is the followi...
Having debugged a similar issue just now using VS2019 runtime, I'll go ahead and say this is almost assuredly caused by a zero initialized (but not constructed) vector. The forensics, in my case, looked like this: the value of _Pnext was 0x8 because _Myproxy is null. With _ITERATOR_DEBUG_LEVEL set to 2 (i.e.: in Debug ...
61,809,441
61,809,616
Getting an std::array reference without using templates
If a function receives an array range (begin/end) as pointers, is there a way to treat that as std::array again? void xyz(int* begin, int* end) { // at this point i know that at this memory range there's // an array<int> of end - begin size // is there any way i can get that back? } int main() { array<int, 5> ...
std::array is implemented as a struct holding a C-style fixed-length array as its sole data member. The begin() iterator is usually a raw pointer to the 1st element of the array 1. 1: @bitmask makes a good point in comments: "Note that std::array<T,N>::iterator does not have to be a raw-pointer. It usually is, but doe...
61,809,861
61,809,954
Why C++ STL hash table (unordered_map) doesn't accept vectors as keys
I assume that there is a reason behind this design choice. Boost seems to have an implementation for it, hence it should be possible to use vectors as hash table keys. Are there any theoretical properties for hash functions applied to arrays that make them more prone to collisions or other undesirable behavior?
You'll notice Boost doesn't actually have an extension to accept a vector<T> as a key specifically - instead it has an extension that lets you use any Iterable - and it generates the hash only as a function of the Iterable's contents... This may or may not be desirable, depending on: If you want to use object-identity...
61,809,866
61,810,184
Output numbers in reverse - c++
Write a program that reads a list of integers, and outputs those integers in reverse. The input begins with an integer indicating the number of integers that follow. For coding simplicity, follow each output integer by a space, including the last one. Assume that the list will always contain less than 20 integ...
You are not following the instructions you were given, in particular this sentence: The input begins with an integer indicating the number of integers that follow. As you surmised, you are indeed reading and printing out exactly 20 values, even if the user actually enters fewer values (and the instructions provide). ...
61,810,178
61,810,208
Does vector erase method needs class to have = operator?
I'm doing a computer science project where I use stl library vector as vector (Table is a class implemented by me). When I tried to use erase method without having implemented operator= in my class Table it fails. Then I added = and now it works but I'm not sure that was the problem. Is necessary to have operator= in a...
Is necessary to have operator= in a class to use erase method? Yes, it is required by the standard. And why it runs without having it defined? A class has an implicit assignment operator generated by the compiler by default, except in certain cases (for example, if it has sub objects that are not assignable).
61,810,239
61,810,713
Dump Lora.read() to array
I want to dump chars from a Lora transmitter using Arduino Nano. With this line I assume it can be store the chars into an array: char* dump = (char)LoRa.read(); char in[255]; strcpy(in, dump); char str[] = in; But unfortunately I get this compiler error: exit status 1 initializer fails to determine size of 'str' How...
The compiler can only supply the size of an array for you on creation if it has a brace enclosed initializer list. Like this: int array[] = {1, 2, 3, 4, 5}; If you're doing anything other than that then you need to put a number inside those braces. Since you're making a copy of the array in and that array is 255 cha...
61,810,339
61,856,303
How to find out the location of a failed assert? (Calling debug-build DLL in Unity)
Writing a C++ DLL to use from Unity3D. If I build the DLL as release, I currently get some undefined behavior nonsense. If building as debug build, the following popup shows: Unfortunately the error redirects into the vector class and not the place where it is actually used in my own code. I know what DLL function cau...
Turns out it is possible to debug the Unity editor as a whole with attached DLLs. Find out where the actual editor is (in the rightclick menu of the installs tab in Unity Hub) Open that EXE with Visual Studio (literally the "Open project" selection) Go to the solutions properties -> parameters and add: -projectPath "...
61,810,578
61,810,646
Memory allocation for struct that has a STL class c++
I'm running tests to see how variables are getting placed on the memory and sizing them out when I use a struct. Consider I have a struct that looks like below: typedef struct _ttmp { WCHAR wcsTest1[13]; WCHAR wcsTest2[13]; wstring wstr; }TTMP, *LPTTMP; How big is the size of TTMP when STL classes like wst...
sizeof(WCHAR[13])=26, which is not an even multiple of 4 or 8, so alignment padding would account for a few bytes (unless you set the struct's alignment to 1-2 bytes via #pragma pack(1) or #pragma pack(2) or equivalent). But, std::(w)string is much more than just a single pointer. It may have a few pointers in it, or a...