question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
65,636,938
65,869,344
ESP8266 randomly cutting response
I want my NodeMCU V3 to fetch weather data from OpenWeatherMapApi. I found some sample codes how to send GET request, but the response is getting cut randomly. After reading response, I print the length of the received JSON response. The response should have something about 16k characters, but it's random every request...
I've found some solution here: ESP8266 - Response from server gets cut Using read() instead of readString() and putting delay(1) seem to work at first, but when I was saving the read character to an array instead of printing it, the response was getting cut again. However when I deleted the delay(1), everything stared ...
65,637,005
65,637,059
How do we catch a std class at destruction?
The title may not be very clear, let me explain: I just want to display a message when a string is destroyed, so I did that: std::string::~std::string(void) { std::cout << "Destroyed string" << std::endl; } It didn't compile, then I tried this: namespace std { string::~string(void) { cout << "Destroyed strin...
It's not possible to add custom destructor behavior to an existing class which already has a destructor defined. Moreover; you cannot (and should not!) modify the behavior of std::string using inheritance. If you want a destructor with custom behavior, you'll have to roll your own class to do it. You could perhaps 'w...
65,637,365
65,637,470
Using template alias over template
Reading a book A tour of c++ (second edition), 2018, I didn't understand an explanation about templates (I'll explain below). Two function signatures are given for a find_all function that returns a vector of iterators to all occurrences of a given value in a given container. #1 : template<typename C, typename V> vecto...
Lets say you have a code base like template<typename C, typename V> vector<typename C::iterator> first(C& c, V v); template<typename C, typename V> vector<typename C::iterator> second(C& c, V v); template<typename C, typename V> vector<typename C::iterator> third(C& c, V v); template<typename C, typename V> vector<type...
65,637,482
65,637,677
How are CMAKE_SOURCE_DIR and CMAKE_BINARY_DIR set?
When and how are these values set? Does it depend on the location of the CMakeLists.txt? Does it depend on where CMake is ran from?
Here is an example command where I configure a cmake project. I'll be using the newer cmake style of doing things since it makes thing more clear. # -S = CMAKE_SOURCE_DIR # -B = CMAKE_BINARY_DIR cmake -S C:\foobar -B C:\foobar\binary_dir As you can see -S specifies the CMAKE_SOURCE_DIR, and -B specifies the CMAKE_BINA...
65,637,499
65,637,549
C++ cout prints entire contents of 2D char array
I am writing a tic-tac-toe game to learn C++. I would like to store the game board in a 2D char array: char playerBoard[5][14] { {'2',' ','>',' ','_',' ','|',' ','_',' ','|',' ','_','\n'}, {'1',' ','>',' ','_',' ','|',' ','_',' ','|',' ','_','\n'}, {'0',' ','>',' ','_',' ','|',' ','_',' ','|...
None of your five array sub-elements is a nul-terminated string (except possibly the last one, but that relies on undefined behaviour). The std::cout << operation with a char* operand (or a char[] operand, which decays into a char*) assumes a nul-terminated string; in your case, as the terminators are missing, the buff...
65,637,796
65,638,517
How to instruct a polymorphic functor in a container to do its job and return results?
I have a std::vector<> of pointers to a base functor. This container, a calculator class, should be able to hold onto an arbitrary number of these function objects that calculate arbitrary statistics. The part I'm struggling with is how to write a method for the container class, that iterates over these pointers, picks...
This works, but I'm open to comments/criticisms/suggestions. #include <iostream> #include <memory> //unique_ptr #include <map> #include <vector> #include <string> #include <functional> class BaseFunctor{ public: virtual double operator()(std::vector<double> inputs) = 0; virtual std::string name() = 0; }; ...
65,637,813
65,638,132
C++ Cast from ‘std::__tuple... {aka ‘unsigned int*’} to ‘uint32_t’ {aka ‘unsigned int’} loses precision
You may have to forgive me as I'm new to C++ and may have made some fundamental errors with the code I have worked up so far. static tuple<read_result, uint8_t*> m_scan_record(bool skip, uint32_t& size, FILE* file) { read_result result; tuple<read_result, uint32_t*> rd_rec_size_result = m_read_generic_t<ui...
tuple<read_result, uint32_t*> rd_rec_size_result = ... The 2nd member of this tuple, as explicitly declared here, is a pointer to a uint32_t. That's what uint32_t * means, in C++. size = (uint32_t) get<1>(rd_rec_size_result); This retrieves the uint32_t * and attempts to convert it to a uint32_t. C++ does not work th...
65,637,905
65,637,946
Unexpected behavior using `std::count` on `std::vector` of pairs
My goal is to completely remove all elements in a std::vector<std::pair<int, int>> that occur more than once. The idea was to utilize std::remove with std::count as part of the predicate. My approach looks something like this: #include <iostream> #include <vector> #include <algorithm> using std::cout; using std::endl;...
Your biggest problem is std::remove_if gives very little guarantees about the contents of the vector while it is running. It guarantees at the end, begin() to returned iterator contains elements not removed, and from there until end() there are some other elements. Meanwhile, you are iterating over the container in the...
65,637,951
65,637,998
SFINAE - enable one function if arguments are copy-constructible and another otherwise
I want a function to be called if the argument are copy-constructible and another function (similar to previous but with extra code). I find that std::is_copy_constructible is not working as expected #include <iostream> using namespace std; struct NoCopy { int n; NoCopy(const NoCopy&) = delete; }; template...
The problem is that here U isn't deduced as NoCopy, but as NoCopy&. You can fix this by using std::decay_t<U> in your enable_if to strip the cv qualifiers and reference and yield NoCopy like you want.
65,637,974
65,638,866
Change input method on windows using c++ and windows API
I want to write some code in C++ in combination with windows API in order to change the input method on windows (Keyboard input language). Here is my first try: #include <iostream> #include <windows.h> int main() { int arr_size = GetKeyboardLayoutList(0, NULL); HKL hkl_array[arr_size]; // The array to hold i...
The very first sentence of the ActivateKeyboardLayout function documentation states: "Sets the input locale identifier (formerly called the keyboard layout handle) for the calling thread or the current process.". Since you never read input in your program, you don't observe its effect. It does not change the keyboard l...
65,638,122
65,638,157
Why do we not use a (*) when accessing the value of a dynamic array?
Our professor taught us to use an indirection operator (*) when accessing a dynamic variable. Hence, I fail to understand why the code is written like this: cout << arr[i]; And not like this: cout << *arr[i]; Here is the entire code: #include <iostream> using namespace std; int main() { int size; int *arr;...
For arrays like you have: arr = new int[size]; The syntax: arr[5]; Is equivalent to this: *(arr+5) It's just nicer looking.
65,638,222
65,638,371
Init count loop variable out or inside the loop declaration in C/C++
Maybe is a silly question, but I wonder if affects or not in the performance of a loop the declaration of the loop's counter (int i = 0 or size_t i = 0) inside or out the loop. For example: // Declaration of counter out of the loop: int i = 0; for(i = 0; i < iters; i++) { // do something } // Declaration of counte...
Good modern compilers with optimization enabled generate code based on where an identifier is used regardless of where it is declared (subject to the semantics required by the C standard or other rules). This should include redundant initializations; the compiler should recognize that the actual effects involving i are...
65,638,348
65,640,017
Weird performance difference between std::unordered_set::find and std::find
I tried comparing performance of std::unordered_set::find and std::find. Contrary to my expectation and rule https://clang.llvm.org/extra/clang-tidy/checks/performance-inefficient-algorithm.html std::find was significantly faster quick-bench with unordered_set unorder_set contains ints so hash shouldn't be an issue. s...
Some of this also depends on the hardware and the implementation. But to get a clearer idea of what's going on, it can be useful to graph the time taken for a number of different sizes with each. For this test, I used Microsoft's compiler, so some difference from clang/llvm isn't particularly surprising. Just for grin...
65,638,396
65,638,461
C++ map templates to other template, then to tuple
I'm working on some low level drivers and I thought I'd use C++ templates to spice it up. In Verilog, you can define bitmasks using [h:l] notation where h is the high bit, l is the low bit. I have a data structure already defined for this: uint16_t mask(uint8_t h, uint8_t l) { return h << 8 + l; } I'd like to memoiz...
I presume that your step 2, which you've described as already a done deal, is something along the lines of typename bytesType<n>::type Where the template parameter n is the number of bytes, and this gives you the type via an appropriate specialization. If so, then this seems to be something along the lines of a straig...
65,638,680
65,643,014
Using BOOST_STRONG_TYPEDEF to differentiate arg types but causing seg fault
I have a method requiring several variables of the same enum type. To allow the compiler to detect if I pass the wrong argument I am using BOOST_STRONG_TYPEDEF. However, I get a seg fault when I create an instance and compare within an IF statement. Boost version is 1.74 enum class Testable { UNDEFINED, A, ...
Sanitizer says ==3044==ERROR: AddressSanitizer: stack-overflow on address 0x7ffcc58b3ff8 (pc 0x56310c340e84 bp 0x7ffcc58b4000 sp 0x7ffcc58b3ff 0 T0) #0 0x56310c340e84 in boost::operators_impl::operator==(Testable const&, SomeType const&) /home/sehe/custom/boost_1_75_0/boo The problem is that Boost's STRONG_TYPEDEF...
65,638,764
65,639,002
Is it possible to return a reference to the result of a static or dynamic pointer cast?
so let's say I have the following function: template<typename T> std::shared_ptr<T> resourceAs() const { return std::static_pointer_cast<T>(m_resource); } This works. But what if I don't like the small overhead of creating the shared_ptr? What if I want something like this template<typename T> ...
std::static_pointer_cast<T>(m_resource); This function call returns an object, and not a reference to an object. std::static_pointer_cast takes an existing std::shared_ptr as a parameter, and creates a new std::shared_ptr object (for a particular purpose which is not germane). It does not return a reference to an exis...
65,638,908
65,638,980
Mutate return type of a lambda
The full context of this problem is unfortunately too involved to explain, but suffice to say it involves some complicated template metaprogramming and I find myself having to do some funny things. I've tried to boil down an issue I've encountered into a minimal example, so the question may seem awkward. If it's possib...
A little redundant, I suppose, but the following wrapper should works template <typename InputFuncType> auto function_converter (InputFuncType lf) { return [=](auto && ... args) { using RT = decltype(lf(std::forward<decltype(args)>(args)...)); if constexpr ( true == std::is_same_v<void, RT> ) ...
65,638,984
65,643,897
Why do C++ streams treat bools as numerics?
In C++, the stream I/O libraries do not by default print "true" or "false" when you output a bool, but rather "1" or "0". Instead, one is required to explicitly request a word-based printing, via std::boolalpha/std::noboolalpha: #include <iostream> int main() { std::cout << bool{ false }; //Prints "0" std::co...
std::cout << bool{b} uses std::use_facet<std::num_put<char>>(std::cout.getloc()).put(std::cout, std::cout, std::cout.fill(), bool{b}) to do the actual output. What this does is basically make a printf specifier and print that (modified by flags). This is speculation, but it might be because in C++98 when this was origi...
65,639,286
65,639,540
Why does sizeof(*value) returns different value than sizeof(value) in c++
I'm curious about this one: int main() { int a[7]; std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << " - " << sizeof(a) << " - " << sizeof(*a) << std::endl; } Returns Length of array = 7 - 28 - 4 So my question is: Why do I have to use (sizeof(a)/sizeof(*a)) to receive the right size, and why doe...
sizeof(a) returns 28 because you have 7 elements in the array, and each element is 4 bytes long. sizeof(*a) returns 4 because *a dereferences the first element in the array (an integer) which is 4 bytes long. Thus, sizeof(a) / sizeof(*a) == 28/4 == 7 EDIT: You shouldn't make a habit of finding the length of an array th...
65,639,539
65,639,626
Efficiently (time-wise) conversion of an array of double to a bitset, according to some function
I need to interface between two pieces of code: one which outputs an "array" (I may accept output as either a "standard" C++ array (of type double), or a std::vector<double>), and one which takes in a std::bitset. Putting aside what goes on at either end... What is most efficient (time-wise) way to convert the output a...
The most likely pattern that your compiler will be able to vectorize is simply setting the result to comparison result directly for (int i = 0; i < L; ++i) inputBitset[i] = outputVector[i] > N; Such loops will generally be vectorized if your processor supports it. More complex loops may also be vectorized, so wou...
65,639,672
65,640,667
WM_COMMAND unabled to fulfil request unless clicked outside of application window,
Currently creating an application that just outputs Physics equations + some historical and mathematical context. I've ran into this problem where I'm using WS_EX_CLIENTEDGE to sort out a list of these terms and when I click said term on the screen, expecting a definition to appear, it doesn't output anything until I'v...
The listbox is created without the LBS_NOTIFY style and will therefore not send LBN_SELCHANGE notifications to the parent window. Changing the first line in aListBox to the following fixes this. hList = CreateWindowEx(WS_EX_CLIENTEDGE, L"ListBox", L" ", WS_CHILD | LBS_NOTIFY | WS_VISIBLE | WS_VSCROLL | ES_AUTOVSCROLL, ...
65,639,705
65,641,574
Reusable std::shared_ptr
Is it possible to make std::shared_ptr not to delete an object, but move it to a list? #include <memory> #include <list> struct QObject { double socialDistance; }; int main() { std::list<QObject *> free_objects; std::list<QObject *> used_objects; QObject* p_object = new QObject{10}; free_obj...
Is it possible to make std::shared_ptr not to delete an object, but move it to a list? You might use custom deleter for that: std::shared_ptr<QObject> p(p_object, [&](QObject* p){ used_objects.push_back(p); auto it = std::find(free_objects.begin(), free_objects.end(), p); ...
65,639,902
65,639,959
How to calculate the angle between two points and rotate the third point baste on that?
I have a set of points based on which I want to calculate the next point's location. To give you a concrete idea of what I'm exactly after, consider the following image: For this image, I have both eyes center points(which are shown as yellow) and I need to calculate the proper location for the green ones. If the he...
You're making this far too complicated. Take the two points: L = {X=128,Y=121} R = {X=188,Y=81} And do a little vector arithmetic: D = (R-L)/4 LL = L-D LR = L+D RL = R-D RR = R+D And you're done. More pedantically (if you don't like vector arithmetic, or don't want to define a Point class), Dx = (Rx-Lx)/4 LLx = Lx-...
65,640,029
65,640,052
no operator ">>" matches these operands -- operand types are: std::istream >> const double
My Code #include <iostream> #include <stdlib.h> #define Pi 3.14159 using namespace std; class Rectangle { public: friend ostream &operator<<(ostream &output,const Rectangle &D) { output<<"length:"<<D.length<<endl<<"height:"<<D.height<<endl; return output; } ...
Ask yourself, can you read into a const variable? Reading to a variable changes the variable, so the answer is obviously no. Try this friend istream &operator>>(istream &input,Rectangle &D)
65,640,630
65,640,703
How to read in from a file word by word and assign those words to a struct?
In my project I have a .txt file that has the number of books at the top, and then title of a book and its author separated by a space, so for example: 1 Elementary_Particles Michel_Houllebecq I then have a struct for the book object struct book { string title; string author; }; There is a book array of these...
In this piece of code while (file >> file_string) { b[count].title = file_string; b[count].author = file_string; count++; } you read one word and assign the same value to title and author, don't expect the compiler to guess your intentions ;) Some additional hints and ideas: while(!file.eof() is not ...
65,641,326
65,642,012
How to transform const wchar_t type to LPTSTR (C++)
I am trying to modify an old plugin to create a new one (in C++ and Visual Studio 2019). When I compile I get the following error marking TEXT in red. E0144: A value of type "const wchar_t *" cannot be used to initialize an entity of type LPTSTR LPTSTR process_name = TEXT("rFactor2.exe"); module_address = GetModuleBa...
LPTSTR is defined as TCHAR*. What you want is a const pointer. You can use LPCTSTR, which is defined as TCHAR const*: LPCTSTR process_name = TEXT("rFactor2.exe"); If your function requires a non-const pointer, you can create a copy: TCHAR process_name[] = TEXT("rFactor2.exe"); Note that life time of the string litera...
65,641,451
65,643,443
Infix to Postfix Output program
I am a novice C++ programmer. I have written the following C++ code for infix to postfix expressing using an array-based stack, however, I get ^2 in string each time and also I can't figure out why my answer is not correct. I can't find the logical error either. Can someone please help me with this? #include<iostream> ...
Starting off, I just want to point out that the use of classes is for data hiding. Making your top, size, and other data members of public scope completely defeats the purpose. Secondly, the nomenclature of classes should start with an uppercase alphabet. The first error is with your stack::Push(char) method. Note the ...
65,641,658
65,643,682
How memory is deallocated in shared_ptr via the operator=?
I am a beginner to c++, I was learning the concept of shared_ptr. I also understood that Several shared_ptr objects may own the same object and the object is destroyed and its memory deallocated when either of the following happens: 1.the last remaining shared_ptr owning the object is destroyed; 2.the last remaining sh...
2.the last remaining shared_ptr owning the object is assigned another pointer via operator= or reset(). Yes. After "P2=P1" the memory allocated to P1 has to be deallocated right? No. It could happen to P2 if it pointed to something. Not P1. The logic behind the rule (2) is that the assignment overwrites the value o...
65,641,691
65,642,429
Late dispatch in Swift
According to this answer: Late dispatch The function is determined at compile time, but the actual implementation depends on the type of the object at runtime. Important for inheritance. The compiler will check if the the class or any of its parents have the function declared, but its up to the runtime to choose which...
You can read more about dispatching in Swift here - https://www.rightpoint.com/rplabs/switch-method-dispatch-table. Later on the fact that Late Dispatch is in many ways similar to Table Dispatch, where we have a declaration at compile time, but when dispatching, we substitute the necessary implementation depending on t...
65,641,887
65,687,954
C++ linked list notation, what is the difference?
I just want to know if there is and difference between these two notations: First example: struct node{ int data; node* next; }; void insert(node* list){ node* n,* last; last = list; while(last) last = last -> next; n = new node; last = n; n -> next =...
Your above explanation stands correct but let me also add one more point, Suppose your list = NULL; void insert(node* list){ node* n,* last; last = list -> next; while(last) last = last -> next; n = new node; last = n; n -> next = NULL; cin >> n -> data; } Then in the above case you are trying to a...
65,642,004
65,642,251
Side effects of passing temporary as const T& and binding to class reference
Let's say I've a struct definition and some function like this: struct A{ const std::string& _s; A(const std::string& s):_s(s){} //A(const std::string s): _s(s){} }; int main(void){ A a("E"); std::cout << a._s << '\n'; } This doesn't error or warn at all by default, you can get it to throw an error at runt...
The c++17 standard §15.2 point 6.9 says temporary object bound to a reference parameter in a function call (8.5.1.2) persists until the completion of the full-expression containing the call So you are good. No UB here auto x= A("E")._s. The other issues you have described well yourself. After construction accessing...
65,642,016
65,653,261
QML TableView: How do you only display a subset of model index data?
I want to display a subset of columns from an large existing C++ TableModel in a new QML TableView. All the documenation and examples I've read override QAbstractItemModel::roleNames() to expose model data associated with the roles as properties in QML. The problem is that the legacy TableModel's data() function has a ...
As far as I can tell it looks like the only way to avoid custom roles is to hack a Q_INVOKABLE function in the model: // LegacyModel.h: ... Q_INVOKABLE QVariant getMyData(int row, int column) const { return m_data[row][column]; } ... // TableView.qml: TableView { ... model: LegacyModel delegate: RowLayou...
65,642,340
65,642,893
Using unordered_multimap with a struct data type
I need to define an unordered multimap which holds a key of type int and a value of type "nod". Nod.h #pragma once #include <iostream> struct nod { int stare[100], pathManhattan, depth; nod* nodParinte; char actiune; nod(); void Citire(int n); void Init(); }; Nod.cpp #include "Nod.h" #include...
I think you need to create a header file for the map definitions in your application source ConsoleApplication1.cpp. You can't just #include the source code as that will give you multiple definitions of your maps. You can do this, create ConsoleApplication1.h: #pragma once #include <unordered_map> #include "Nod.h" ext...
65,642,518
65,643,666
How to use rayleigh_distribution<> from boost library in c++?
I'm trying to generate random number using Rayleigh distribution. I have implemented this using the c++ the library below: #include <boost/math/distributions/rayleigh.hpp> boost::math::rayleigh_distribution<> rayleigh(); I don't know how to use this library to return number related to sigma.
The sigma is passed in the constructor, so do it like this: const double sigma = 5.; boost::math::rayleigh_distribution<> rayleigh(sigma); The method sigma() merely returns a copy of the set sigma, so you cannot use that. What Scheff was referring to is that it would also work (given you want sigma to be 1.) if you do...
65,642,546
65,642,613
Array of abstract classes (interfaces) in C++
I want to declare an array of interfaces and further get a pointer to the list of interfaces Interface*. But compiler (GCC) prints error error: invalid abstract 'type Interface' for 'array'. Code: class Interface { public: virtual ~Interface() = default; virtual void Method() = 0; }; class Implementation : pu...
You cannot create an Interface object since it's an abstract type. Even if Interface were not abstract what you are trying would not work because of object slicing. Instead you need to create an array of Interface pointers, e.g. static Interface* const array[] = { new Implementation(), new ImplementationNumberT...
65,642,751
65,642,933
Raw pointer, smart pointer or std::vector for "low-level" container data in C++
Let's say I am making my own Matrix class/container which itself needs to manage some sort of array of doubles and a row/column dimension. At the risk of sounding hand-wavy, what is the considered "best practice" for how to store this data if speed is of importance? The options I can see are: Raw pointer to single dyn...
I would use std::vector because it solves memory allocation, deallocation, indexing, copying, etc.. Unless you will be using "millions" of matrices at the same time, the extra member (capacity) is probably not relevant. In any case, optimizing the library for speed is the last thing you want to do -- after you can tes...
65,642,765
65,642,788
why does the do while loop doesn't break?
I am having problem with following code switch(adminChoice){ case 1: do{ cout<<"\nEnter Student ID: "; cin>>studentId; cout<<"\nEnter Student Name: "; cin>>studentName; cout<<"\nEnter Student Password: "; cin>>studentPassword; ...
The condition adminSubChoice!='n' || adminSubChoice !='N' will be always true because no character will be both n and N at the same time. The condition should be adminSubChoice!='n' && adminSubChoice !='N'.
65,642,803
65,642,979
Notation for "reference to array" type
In c++, type of a reference to array is shown like int (&) [10]. As an example, when I try to compile with g++ and clang the following code template <typename T> void foo(T&); int main() { int a[] {1, 2, 3}; foo(a); } I get the following error: undefined reference to `void foo<int [3]>(int (&) [3])' In this...
It comes from how the type of pointers to arrays look like: int(*)[10]. The * is just replaced by &, like in all reference types. The reason that pointers to arrays look like that is how it looks like in C, and C++ had no reason to change it. int (*a)[10]; // "(*a)[10]" is an int // The type of `a` is `int (*)[10]`, ju...
65,643,041
65,643,141
std::unique_ptr operator[] vs. raw ptr dynamic array operator[]
I have the following code sample: void foo(int size) { std::unique_ptr<uint8_t[]> data = std::make_unique<uint8_t>(size); for(int i = 0; i < size; i += 2) { data[i] = 1; data[i + 1] = 2; } } The actual code does actual calculations, but that does not matter for this question and was rem...
Without optimisations, there is the overhead of calling operator[] and passing the index as an argument. With optimisations, the compiler can inline the entire function to avoid the overhead of calling the function (and since it results in identical assembly, you already know that the performance will be the same). Thi...
65,643,867
65,644,027
how to access data members of an object in an array
I have an array full with objects of a class I created. I want to access members of each of them but I don't know how. #include <iostream> using namespace std; class TRAIN{ int Train_Number; string Train_Name; int Arrival_Hr; int Arrival_Min; TRAIN(int Hr1,int Mn1, int Hr2, int Mn2) { ...
#include <iostream> using namespace std; class TRAIN{ public: int Train_Number; public: string Train_Name; int Arrival_Hr; int Arrival_Min; TRAIN(int Hr1,int Mn1, int Hr2, int Mn2) { Arrival_Hr = Hr2-Hr1; Arrival_Min = Mn2-Mn1; cout<<Arrival_Hr<<"Hr"<<Arrival_Min<<"min is t...
65,643,970
66,508,727
Minimum number of elements required to make two bags of at least k weight?
Suppose you are given a number k and an array of objects having some weight. Now your task is to find the minimum number of objects that you can put in two bags such that each bag weigh at least k. You can only take the objects as whole no breaking is allowed. Also, if an object is put in one bag it cannot be put into...
Here is the pseudo code for the program without dynamic programing. sort(a, a+n); // Sort the array of objects having weight int sum = a[n-1], count = -1; //Initialise sum and count unordered_set<int>log; // Create an unordered set to store logs (Unordered set will not add repetitive values in ...
65,644,053
65,873,313
lock_guard initialization in if-initializer instead of simple scope
Is it correct that if (std::lock_guard lk(m_state.mtx); true) { m_state.aborting = true; } and { std::lock_guard lk(m_state.mtx) m_state.aborting = true; } are 100% identical? Here is the background on my question: In Mastering the C++17 STL, the author gives a code example for a thread pool. It contains the f...
I'm the author of Mastering the C++17 STL. I'd already forgotten that construct, so there can't have been any important reason I used it. I believe Igor is correct: the choice would have been between ~ThreadPool() { if (std::lock_guard lk(m_state.mtx); true) { m_state.aborting = true; } m_cv.notify_all(); f...
65,644,333
65,646,527
Building a C++ template library with make
I am having difficulties with re-writting my C++ library into template form; main problem concerns re-designing the Makefile. In the previous state, when it was non-template I had: a header file lib.h in which (protected by include guards) we have the declarations of classes and overloaded operators. This file does no...
I have added an #include "lib.cpp" at the end of the header file for my library (inside the include guard, ofc). I can't say I think much of the advice you followed there. Code that is intended to be used as or in a header should be named appropriately (.h, .hpp, or whatever convention your project follows), and cod...
65,644,359
65,644,564
C++ #define value not defined in source file
I'm defining a value in my Main-file and then including a header file. The defined value isn't defined in the source file. Main.cpp: #define TN_VALUE double #include "SomeFile.hpp" int main() { TN_VALUE x = 3; func(x); return 0; } SomeFile.hpp: #ifndef _SOME_FILE #define _SOME_FILE #ifndef TN_VALUE #define TN_V...
I'm assuming your question is, Why does TN_VALUE is double in Main.cpp and float in SomeFile.cpp. For that question, this is the explanation, In C++, when you include a header file, it's content gets copied to the source file. Which means that there will be one copy of the SomeFile.hpp file in Main.cpp file and anoth...
65,644,361
65,644,503
I made a queue management system and created a function to add two queues
Here's my code. I created the function to add two queues using the operation overloading. For some reson it always returns an empty #include <iostream> using namespace std; class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } //adds ...
Your code should do something like this. This code isn't going to win any prizes for style, I'm just trying to show you what is required Queue operator+(Queue &obj){ Queue res; res.size = size + obj.size; // work out the new queues size res.queue = new int[100]; // allocate memory for new queue for (int i = 0; ...
65,644,442
65,644,491
Can't figure out how to set the value of EM_SETLIMITTEXT with winapi in c++
My question is fairly simple, so I'll get straight to the point. My code to create a text box in my gui application is below: CreateWindowW(L"edit",L"12345",WS_VISIBLE|WS_CHILD|WS_BORDER|ES_MULTILINE|EM_SETLIMITTEXT,50,230,680,388,hwnd,NULL,NULL,NULL); You can see that I have included "EM_SETLIMITTEXT." My goal is to ...
EM_SETLIMITTEXT is a message, not a window style, so as per the documentation you should write: HWND hWndEdit = CreateWindowW(L"edit",L"12345",WS_VISIBLE|WS_CHILD|WS_BORDER|ES_MULTILINE,50,230,680,388,hwnd,NULL,NULL,NULL); SendMessage (hWndEdit, EM_SETLIMITTEXT, 2000, 0);
65,644,476
65,644,602
How does std::cout work with char pointers?
Recently I've been learning about C++ pointers and I'm confused when it comes to char. char *c = "sampletext"; cout<< *c <<endl; cout<< c <<endl; cout<< &c <<endl; To be more precise: why does cout<< c <<endl; print whole C-string instead of address (as it takes place in int pointers for example), and why does cout<< *...
This happens because the compiler checks the type of the argument and calls the overloaded version of the operator that receives that type. In the C language, strings are implemented as char arrays terminated with the ’\0’ (nul) character, and arrays are referred to using pointers. So, when the argument received is c, ...
65,644,480
65,645,084
wrong constructor called for virtual base class of virtual base class
I'm having a problem with the constructors of a very complex class structure that is spread over several files. Each class has a public default contructor without arguments and a protected contructor with arguments. Each constructor of any derived class is calling the protected constructor of it's parent with arguments...
The Answer is given in the comments by Sam Varshavchik. The concept of passing the argument from each constructor to it's direct parent was the wrong way of handling the issue. I was under the wrong impression, that I can only access the direct parents of each class. Sam Varshavchik's comment helped me to see the real ...
65,644,567
65,644,671
How to solve linker error in multi-file cpp project
I have 3 files. A header (.h), a cpp (.cpp) & a main (main.cpp). Inside main I want to include only .h file but not the .cpp to use those functionalities defined. Here are the files person.h #ifndef PERSON_H #define PERSON_H #include <string> class Person { public: Person(std::string &&n) : _name(&n), _address(nu...
As mentioned by Igor Tandetrik, you're not including person.cpp in the actual build add_executable(${PROJECT_NAME} src/main.cpp src/person.cpp) Should get you there.
65,644,740
65,644,935
Is there proper way to alias type depending on passed template value argument at compile time (c++)
I wanna alias type according to passed template argument. Depending on Passed Template argument int value, return Type is decided. but there is many types what I want. I wanna do this with clean code. I know I can do this with std::conditional_t, but it's really messy. I need aliasing many types from int value template...
No, I don't see a way to get a switch statement for declaring a using type. The best I can imagine pass through a struct template specialization template <int> struct my_type; template <> struct my_type<1> { using type = Type1; }; template <> struct my_type<2> { using type = Type2; }; template <> struct my_type<3> { u...
65,644,780
65,646,562
How to create 3 threads of parallel execution using boost library in C++ (in Visual Studio 2019)?
I am trying to use the boost library to create 3 threads of execution, on Visual Studio 2019. The 3 thread functions each has a while(1) loop, to keep executing continuously. However, when I execute the program, I see that only the first thread is executed (and a breakpoint is hit). So I understand that the first threa...
Just postpone joining the threads: boost::thread t(&myclass::kafkaSvc1ProducerThread, this, rk); boost::thread t2(&myclass::kafkaSvc2ProducerThread, this, rk); boost::thread t3(&myclass::kafkaSvc3ProducerThread, this, rk); t.join(); t2.join(); t3.join(); Consider using a thread_group.
65,644,986
65,645,023
vector.size() - 2 leads to infinite loop - C++
I am trying to run a loop on vector but not on the last two elements. So for that I used the following implementation: vector<int> x; for(int i=0;i<x.size()-2;i++){ cout<<"looping over element"<<endl; } However, running the above code with no elements inserted into x leads to an infinite loop. Ideone link: Why do ...
x.size() returns an unsigned value. If this is smaller than 2 then the value will underflow and the result will become very large. On the other hand since i is a signed type hen it will sooner or later come to the max value of an int (which will still be less than the result of x.size() - 2), and then i++ will lead to ...
65,645,046
65,645,074
How can integer be appended to string if + '0' is provided
I encountered with a strange code in a solution of a programming problem and I couldn't find any good idea about it. Here, #include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int count=8; string temp="Hello "; temp+=count+'0'; cout<<temp; return 0; } Output is: Hello 8 ...
integer variable count was appended to the string even without type casting the integer variable. No, no integer variable was appended. The only suitable overload for the += operator is the one that takes a single char parameter, and ends up adding a single character to the string. The integer value type gets convert...
65,645,056
65,645,321
How to read n values from txt file using C++
I have the following c++ code by which I am reading values from .txt file Could you please help me to improve the code such that I can read not only 14 values but n values from the .txt //reading from text file static std::vector<double> vec; double a[14]; //values got read from txt file int i = 0; void readDATA() { ...
vec.push_back(value); Here, values are already added to vec, you don't need to add them to a again. You can just access those values by typing vec[n]. For example, std::cout<<vec[2]; //40 std::cout<<vec[4]; //15 And you can push back as many elements as you like to vectors, so you really don't need to declare another ...
65,645,196
65,645,343
Make sf::Shape a parameter type, SFML
I'm trying to make a function that take in parameter a sf::Shape object ( in order to accept only cirlce, rectangles etc ) But as it is an abstract class, it throws me that error "parameter of abstract class type sf::Shape is not allowed" This is the signature of my function : GraphObject::GraphObject(sf::Shape shape, ...
Accept shape as a reference or a pointer: GraphObject::GraphObject(sf::Shape& shape, int z = 0) or GraphObject::GraphObject(sf::Shape* shape, int z = 0). The reasoning is pretty self-explanatory. You cannot have objects of an abstract class type - well because they are abstract.
65,645,770
65,645,907
C++ separating std::strings by space
I have a std::string line = "!l1 l2 l3" and I want to separate this string by the spaces, remove the '!' and inserting l1, l2 and l3 into 3 std:strings l1_sep, l2_sep and l3_sep. l1, l2 and l3 can be values with up to 3 chars. Input Examples: "!50 125 5" or "!5 60 50" or "!100 7 123" Output desired: std::string l1_sep=...
You will need to add safety checks to make sure the string follows the pattern yourself. #include <string> using std::string; void parse(string line, string & l1, string & l2, string & l3) { // todo: insert your safety here; throw exceptions as necessary. line.erase(0, 1); auto space = line.find(' '); ...
65,645,904
65,646,901
Implementing a custom allocator with fancy pointers
I'm trying to implement my own allocator, which should work with STL containers and use a custom fancy pointer implementation. I'm pretty sure, that my classes fulfill all requirements (according to cppreference) but my implementation doesn't compile for std::list because there is no conversion from my fancy pointer to...
After some digging into the problem, I guess this is simply impossible due to libstdc++ internal limitations. This is a known old bug, "Node-based containers don't use allocator's pointer type internally": Container nodes are linked together by built-in pointers, but they should use the allocator's pointer type instea...
65,646,041
65,646,393
C++ get substring from each axis in a string
How can i acquire the value from each axis on a string? #include <iostream> #include <string> using namespace std; int main() { string text = "X:-600.913 Y:100.54 Z:412.22"; //do stuff string X; // must be -600.913 string Y; // must be 100.54 string Z; // must be 412.22 //print individual valu...
As mentioned in the comments, regular expressions work well for this kind of thing. Use the module regex. Like so: #include <iostream> #include <cstdlib> #include <regex> int main() { const std::string s = "X:-600.913 Y:100.54 Z:412.22"; std::smatch m; std::regex e(R"(X:(-?\d+\.\d+)\sY:(-?\d+\.\d+)\sZ:(-?...
65,646,117
65,649,118
QGraphicsPathItem between two movable QGraphicsRectItem
I'm trying to follow this example and eyllanesc's answer here Weird behaviour when dragging QGraphicsItem to draw a line ending with an arrow between two draggable/movable QGraphicsRectItems Here is my code: The customized QGraphicsPathItemclass (inherits from QObject also because I use signals): wireArrow.h public s...
What is required is very similar to what I implement in this answer so I will limit the code translated from python to c++: component.h #ifndef COMPONENT_H #define COMPONENT_H #include <QGraphicsRectItem> class Arrow; class Component : public QGraphicsRectItem { public: Component(QGraphicsItem *parent = nullptr)...
65,646,278
65,647,236
Have compiler ignoring setting an argument register before calling function
TL;DR; I am looking for a standard way to basically tell the compiler to pass whatever happened to be in a given register to the next function. Basically I have a function int bar(int a, int b, int c). In some cases c is unused and I would like to be able to call bar in the cases where c is unused without modifying rdx...
One approach that should work for gcc/clang on most platforms is to do int no_init; asm("" : "=r" (no_init)); return bar(a, b, no_init); This way you don't have to lie to the compiler about the prototype of bar (whichc could break some calling conventions), and you fool the compiler into thinking no_init...
65,646,332
65,646,360
Trying to get to grips with C++ and cant work out why this doesn't print out the names of the vector<string> entries
So this code doesn't print out the entries inside of the vector gameLibrary Originally I just used the gameLibrary.pushback(" ") function to add them and that worked fine. I'm more just trying to get to grips with why this doesn't work. when ( at least in my mind it's doing the same thing) #include <iostream> #include ...
addGame must not receive the vector it is filling by copy. It must be passed by reference or by pointer. Exemple passing by reference : void addGame(vector<string>& gameLibrary, string gameName) { gameLibrary.emplace_back(gameName); } Otherwise, the copy is modified, so the vector declared in main is unchanged.
65,646,383
65,646,689
Exporting functions from LLVM C++ API to WebAssembly
Situation: I currently parse a front-end language and generate function definitions in LLVM IR. I can compile the function definition to a WebAssembly file using the LLVM12 C++ API. However, the generated wasm code does not "export" any of the compiled functions and thus cannot be accessed from a javascript that loads ...
You can trigger the export of a given symbol by setting the wasm-export-name and wasm-export-name attributes. In C/C++ these correspond the export_name and export_module clang attribtes. See llvm/test/CodeGen/WebAssembly/export-name.ll in the llvm tree for an example of this. You can also ask the linker to export a giv...
65,646,533
65,646,667
C++ - sort array by Date
I am learning C++. I have created two structs (Date and Phone): struct Date { unsigned int day, month, year; }; struct Phone { std::string name; Date purchase_date; }; Then I insert some data with std::cin for multiple phones. My main function: int main() { Phone *phone[3]; phone[0] = new Phone; ...
You can use std::sort with a custom comparator. The comparator is used to tell if the first argument is "less" than the second argument: #include <algorithm> // std::sort #include <string> // std::string, std::begin, std::end struct Date { unsigned int day, month, year; }; // Compare dates bool operator<(Date ...
65,646,984
65,646,997
Why is the || operator not triggered here?
int main() { int precision = 10; int choice; //Title and Menu cout << endl << "==============" << endl << " TRIGONOMETRY " << endl << "=============="; cout << endl << "Current Precision: " << precision; cout << endl << endl << "Select:"; cout << endl << "1. Calculate Cos and Sin"; cout...
You should use the And operator (&&) to achieve the result that you want, try this: if (choice != 1 && choice != 8 && choice != 9) { cout << endl << "Please enter a valid choice between 1, 8 and 9."; } The reason why it didn't work with the Or operator (||) is because that for each number among 1, 8 or 9, ...
65,647,489
65,700,821
Compilation error C2760 in Visual Studio 2019 but not Visual Studio Code
Using the latest versions of Visual Studio 2019 and Visual Studio. In both I am trying to use this header-only class to display a vector: #pragma once #include <cstring> #include <iterator> #include <vector> // Header-only helper class for using strings class stringHelper { public: // Constructor / destructor ...
This problem was reported to Microsoft who responded (in under 48 hours!) with an explanation of the underlying issue. This is not a compiler bug, but relates to type deduction when using templates. Read the full discussion here. One of the comments provided a useful link to this StackOverflow answer with similar detai...
65,647,769
65,648,204
How to find the "ordinal hash code" of specified sequence?
I have a sequence of [-1,-2,-3,-4,0,1,2,3] and the task is to reach goal sequence of [1,2,3,0,-1,-2,-3,-4]. Symbol "0" means a gap - it could be swapped for a non-gap symbol like this: [-1,-2,-3,-4,1,0,2,3]. At each manipulation with initial sequence the cost is 0 (zero). I need to know the coefficient of how close eac...
Assuming all numbers are unique. Untested code ahead using SumType = int64_t; // feel free to shoot yourself in the foot by using floats. SumType PosSum(const std::vector<int>& curr, const std::vector<int>& goal) { SumType sum = 0; for(auto it = curr.begin(); it != curr.end(); ++it) { // if (*it != gabValue) ??...
65,647,925
65,649,362
How to Convert Eigen Matrix to C/C++ Array
In Eigen C/C++ Library, how to converter the operation result (example below) from Eigen Matrix to C/C++ Array? Example: const Eigen::MatrixXf mat = Eigen::Map<Eigen::MatrixXf>( array_C_input , 3, 3); const Eigen::MatrixSquareRootReturnValue<Eigen::MatrixXf> result = m.sqrt(); float* array_C_output = (float*) result;...
If you want to compute the matrix root of a matrix passed as C-style array and handle the result like a C-style array, you can either store the result into a MatrixXf and use the data() member of that matrix: Eigen::MatrixXf matrix_root = Eigen::MatrixXf::Map( array_C_input , 3, 3).sqrt(); float* array_C_output = matri...
65,648,180
65,650,375
How do I synchronize a store before a load in multiple threads?
Consider the following program: #include <thread> #include <atomic> #include <cassert> int x = 0; std::atomic<int> y = {0}; std::atomic<bool> x_was_zero = {false}; std::atomic<bool> y_was_zero = {false}; void write_x_load_y() { x = 1; if (y == 0) y_was_zero = true; } void write_y_load_x() { y = 1...
This idea is fatally flawed, and impossible to make safe in ISO C++ with non-atomic x. Data-race Undefined Behaviour (UB) is unavoidable because one thread writes x unconditionally and the other reads it unconditionally. At best you'd be rolling your own atomics by using compiler barriers to force one thread to sync a...
65,648,343
65,648,365
Write access violation c++ when i try to save from one variable to another
struct Array { int length = 5; int *first_cell; void create() { int *arr = new int[length * sizeof(int)]; *first_cell = *arr; } void random_fill() { int k; srand(5); for (k = 0; k < length; k++) { first_cell[k] = rand() % 10; printf("|...
I assume that you want to save the pointer to arr in first_cell. So write it like: first_cell = arr
65,648,369
65,648,492
There is something wrong with my formulas and I can't figure out which one and where
#include <iostream> #include <iomanip> using namespace std; //Power function float power (float base, int exp) { if (exp < 0) return 1 / (base * power(base, (-exp) - 1)); if (exp == 0) return 1; if (exp == 1) return base; return base * power (base, exp - 1); } //Factoria...
Your issue is with floating point error, mathematically your algorithm is correct, but your computer cannot hold big numbers with a sufficient precision. You're doing modulo 360, but that will put rad between 0 and 2*pi. That's too much. What I would recommend is to "shift" your input, rad, between -pi and +pi. I tried...
65,648,370
65,648,435
Why is the size of a template 1 Byte in C++?
With using, an alias for a type can be defined and a unit of this type has the same size like an original instantation (1). A template however only weights 1 byte (2). using aliasOfInt = int; template<typename T> struct intWrapper { using wrappedAliasOfInt = T; }; int main() { // (1) --> 4B std::cout << ...
The template is a red herring. It's a structure without data members, regardless of T. Since C++ does not allow sizeof(anything)==0, sizeof(intWrapper<int>) has to be greater than 0. This leaves size 1 as a natural choice.
65,648,379
65,711,310
How to install GNU MP (GMP) in Codeblocks on Linux mint
I was able to install GMP following a tutorial using MSYS2 in Windows, however I am quite unsure of how to do the same on Linux Mint. I can't use Windows as I need to use C++17, which MSYS2 doesn't let me do because my windows is outdated, so to use C++17 I use Linux. I am using a clang compiler, but I don't know how t...
Download gmp from here. wget https://gmplib.org/download/gmp/gmp-6.2.1.tar.xz unxz gmp-6.2.1.tar.xz tar xzvf gmp-6.2.1.tar cd gmp-6.2.1 ./configure make sudo make install it should be installed under /usr/local/. The debian way: Enable the sources repositories under your /etc/apt/sources.list.d/ then install apt-src ...
65,648,422
65,658,335
Make a nested object in C++
I come from javascript and am trying to understand objects in C++ I am trying to make a C++ object like this: var myObject = { first: { first: { first:"11first",second:"11second" }, second: { first:"12first",second:"12second" } }, second: { fir...
You can create nested objects on C++ like Javascript, but in order to understand how it works, you need to learn about types and functions mainly, you could visit learncpp.com to read about how C++ works. Now, answering your question the syntax to create a class on C++ is the following: class "ClassName:{ Access s...
65,648,838
65,649,538
Why do I need to define a function in order to pass it to a template function that is not invoking it?
The case is clearer than the question title. I have this piece of code running OK. It declares a function and then prints its type: int f(int); // function receiving int std::cout << "int f(int); type of f = " << typeid(f).name() << std::endl; But when I pass the function as a parameter to a template function, the li...
Templates generate code. Your function template generates functions. In this case, it generated: template<> void PrintDeclarationAndType(std::string text, int(*var)(int)) { std::cout << text << typeid(var).name() << std::endl; } there is a bit of magic in how the Ts are deduced, but once this is generated this is ...
65,648,897
65,649,022
C++20 behaviour breaking existing code with equality operator?
I ran into this while debugging this question. I trimmed it down all the way to just using Boost Operators: Compiler Explorer C++17 C++20 #include <boost/operators.hpp> struct F : boost::totally_ordered1<F, boost::totally_ordered2<F, int>> { /*implicit*/ F(int t_) : t(t_) {} bool operator==(F const& o) const ...
Indeed, C++20 unfortunately makes this code infinitely recursive. Here's a reduced example: struct F { /*implicit*/ F(int t_) : t(t_) {} // member: #1 bool operator==(F const& o) const { return t == o.t; } // non-member: #2 friend bool operator==(const int& y, const F& x) { return x == y; } priva...
65,649,077
65,649,115
Wrong value on first element in std::vector
I am learning c++ i am fearly new, i found a bug in my code and could reproduce with a example, in this code i am generating some price objects and adding it to a std::vector, why the value of close inside the object Price for the first element is aparently a random value in memory ? is this a reference issue ? #includ...
In the ####### before ######## list, you are printing objects with both of members entry and close are initialized. On the other hand, objects with only entry is initialized is pushed to the vector prices and they are printed in the ####### after ######## list. (Price current = prices[prices.size() - 1]; makes a co...
65,649,434
65,649,547
Why won't my code read all the character strings in a 'for'?
If i run this code and choose 3 for n (the number of sentences read from the keyboard), it will allow me to only read two of them. What am i doing wrong? #include <stdio.h> #include <iostream> #include <string.h> #include <stdlib.h> using namespace std; #define MAX 20 int main() { int n; printf("Enter the ...
You are forgetting to take the '\n' that was left in the input after you read n. You can either change your scanf to: scanf("%d\n", &n); or add a getchar(); right after it. Also, as mentioned in comments, you are allocating a single char in each array. You should multiply the result sizeof by the number of letters you ...
65,649,614
65,649,694
Why do my objects get deconstructed twice after I add their unique_ptr to a vector?
I am trying to make a vector of unique_ptrs to the Example class and for some reason every time I call emplace_back() the objects get deconstructed twice. I think it's easier for you to understand if I just show the code here: #include <vector> #include <iostream> #include <memory> class Example; typedef std::unique_p...
A std::unique_ptr owns what it's pointing to. So it doesn't make any sense for the constructor of your object (which has an owner already - whatever is constructing the object) to be able to create a valid unique pointer to itself. And of course that's not what you're doing. Like Sam's answer says, you're creating a br...
65,649,804
65,650,132
Why some expression that looks like a definition for normal types unexpectedly turns out to be a declaration for templates?
These expressions are all definitions for normal types: int num; bool flag; But some expression that looks like a definition for normal types unexpectedly turns out to be a declaration for templates(for details, see below and https://ibb.co/k0qCHp2)! Here is the related code snippet(https://godbolt.org/z/a9W9Wc): ...
Test<int> intTest; is a definition (which is also a declaration; all definitions are also declarations) of the variable intTest. However, this fact is rather irrelevant to your implied question of "why does this line compile". The reason it compiles is this: it causes an implicit instantiation of the class template spe...
65,649,992
65,650,063
Search both elements of a pair and replace either element
Given a pair of ints p, I want to be able to replace any 2 in it with a 3 and vice versa, so I did something like this: pair<int,int> f(pair<int, int> p) { if (p.first == 2) p.first = 3; else if (p.first == 3) p.first = 2; if (p.second == 2) p.second = 3; else if (p.second == 3...
You can use an std::map to store what to replace as a key and replacement as a value: std::pair<int, int> f(std::pair<int, int> p) { static const std::map<int, int> replacements = { { 2, 3 }, // 2 -> 3 { 5, 7 } // 5 -> 7 // Add more replacements }; auto it = replacements.find(p.f...
65,650,058
65,650,188
Trying to run a C++ executable inside a C++ code halts the program
My goal : To display a simple message box ("Object Detected") whenever an object is detected in the webcam. Ive got a C++ opencv code which displays the webcam (display_cam.cc). Ive another basic PySimpleGUI code which is being run inside another c++ code which simply displays a text box with text "Object Detected" (gu...
std::system will always block until the command exits. It needs to, because it returns the command's exit code. You have a few ways around this: Put the std::system() call in its own std::thread. Use platform-specific features in the command string to make it non-blocking. For example, on Linux, macOS, or any other p...
65,650,421
65,650,453
What is this C++ OOP concept for pointers called?
int main() { doSomething(something); } string doSomething(Thing *x); Here, doSomething is a function and Thing is a class. Now, I also have another inherited class called subThing, and I also want to doSomething to a pointer of subThing. What do you call the concept of using pointers to inherited classes? I ...
Look up “Polymorphism”. When subThing is derived from Thing, an instance of subThing is also an instance of Thing, so a subThing* pointer can be used anywhere a Thing* pointer can be used. Same thing with subThing& and Thing& references. Just watch out for “Object Slicing”. Polymorphic access to an object only works...
65,650,757
65,651,397
How to find the item number of maximum profit and how to assign array[100000]???? help me
Questions – A file is given as “input.txt” name. In this file, you have 100000(N) items. Every item has a fixed weight wi and price pi. You can take maximum 2036 weights. Find out the way to take items, so that you can get maximum profit. You must print items which you have selected to get maximum profit. See, the samp...
I'm not going to give you a straight answer, as this is either an assignment or a coding challenge, and you should be able to solve it yourself. Instead I've tried to transform your code into some readable code, to show you how this can improve your understanding of your own code //Fractional Knapsack struct Item { ...
65,650,927
65,650,949
Why does size of map changes on comparison?
Using the below C++ code prints different sizes of map before and after comparison. #include <iostream> #include <string> #include <map> using namespace std; int main() { string str1 = "abc", str2 = "def"; map<char, int> mp; for(char c: str1) mp[c]++; cout << "Size of map: " << mp.size() << endl; fo...
if(mp[ch]) This will call the map::operator[] with key ch. If key matches to an element in map it will return the value of that element. If key does not match to any element in the map, the function inserts a new element with that key and returns a reference to its mapped value. You can use map::find to check if the k...
65,650,940
65,651,067
How to solve runtime error in finding the largest number among n numbers
As I'm new to c++ I get runtime error for first example(I mean I tested my program with 5 examples it actually happens automatically by a site for testing) of my program I know that's because of exceeding time for running it but I dunno how to fix this. My program get n numbers from user and finds the largest one and p...
int *p=new int(n); The line above allocates just a single int, and sets the value to n. It does not allocate an array of n integers. That line should be: int *p=new int[n]; And then delete [] p; to deallocate the memory. But better yet: #include <vector> //... std::vector<int> p(n); is the preferred way to utilize d...
65,651,060
65,651,138
Pointer to array of objects in C++
Write a program to implement pointer to object in a class TRAIN. Train_Number , Train_Name, Arrival_Hr ,Arrival_Min, TimeDiff() are members in class. Member function TimeDiff() is used to find the time difference between Arrival Time (Arrival_Hr and Arrival_Min) and Reached Time ( New given Hr and Min for late arrival...
The program is a good start, but as-is it does not correctly address the things the question asks for. You are missing the TimeDiff() method. What you have put into the TRAIN constructor is supposed to be in the TimeDiff() method instead. The question asks for a “pointer to array of objects”, but you are using an “arra...
65,651,652
65,651,782
How to erase cv::circle from display window
I use OpenCV library for drawing circles on image. I need to erase last circle which was drawn on window by clicking on right button click. Currently, I wrote workaround, I replace red circle by white. but seems there is another solution such as erase it. How I can update my UI? std::vector<Point2f> right_image; // ...
It will be faster to store image without any overlays, and redraw circles each frame. If you want to append, move or delete circle just remove it from the list of objects to plot.
65,651,853
65,651,921
How to avoid function name conflict in a C library?
I'm programming a serial port on Unix, and I'm using the header file unistd.h. It contains the function: read(int fd, void *buf, size_t count) I'm making a class to call this function, and one of the methods in my class is also called read() to read one character. But when I compile, it says it cannot identify the fun...
If I was using C++, I could just add :: to resolve library conflict. But you are using C++. Just because you include a header that contains C API, it doesn't mean the translation unit stops being a C++ translation unit. If the header is designed to play nice with C++, then its contents are still put in the global nam...
65,651,922
65,652,392
overloading multiple operators in one function
is it possible to overload multiple operators in one operator overload? I want to do something like this: template<operator O> MyClass operator<O>(const MyClass & other) { return this.x <O> other.x; } where x is an int attribute of the class. so that itll be possible to overload all of the int operators at once, meani...
No, you can't overload multiple operators in one operator overload. You could however make a class template to use for all your Points: #include <iostream> template<typename T> class Point_impl { public: using value_type = T; template <typename U> friend class Point_impl; Point_impl() : x_{}, y_{} {} ...
65,652,209
65,652,824
C++ print string n times with white space between?
Is there any way to print a string on c++ n times. For example int main(){ int n = 5; cout << string(n, '|') << endl; return 0; } output is |||||, but desired output is | | | | | Since string() cannot take whitespace " ", if I want to add whitespace in between, how can i approach that?
You can use the standard algorithm fill_n for that #include <iostream> #include <algorithm> int main() { int const n = 5; std::fill_n(std::ostream_iterator<char>{std::cout, " "}, n, '|'); std::cout << '\n'; }
65,652,439
65,652,513
Accessing a static member function of a nested class template
For academic purposes I'm reinventing the wheel a bit and try to write a HAL library. Now in designing it I encountered a compiler error that I do not understand. template< class DRIVER, class PORT, class PIN > class Instance { Instance(){} public: static void set(const bool val) { ...
DRIVER::GPIOPeripheral<PORT, PIN>::set(val); DRIVER is a type template parameter of the Instance class template, but the primary class template does not know anything of the dependent type GPIOPeripheral of the parameterized type DRIVER; it only knows that the latter is a type (DRIVER may not even be a class type). ...
65,652,701
65,661,778
Exclude a number in a sequence so that the greatest divisor common of all the other at most. Find the index of the excluded one and that maximum GCD
Exclude a number in a sequence so that the greatest divisor common of all the other at most. Find the index of the excluded one and that maximum greatest divisor common. This is my code: #include <iostream> using namespace std; int gcd(int x, int y) { while (y) { int r=x%y; x=y; y=r; }...
Maintain a prefix GCD list and a suffix GCD list by accumulating the result of applying GCD in one direction. Then iterate over the list, checking GCD(prefix[i], suffix[i]) for the maximum.
65,652,737
65,652,974
high performance 'proper' c++ alternative to variable length array
I am writing a function which requires an array to be created at runtime. The array will be of small size so I am not worried about unsafe code, however, I want to write 'proper' code. As such I am considering three alternatives: char array[len]; char array = new char(len); std::vector array(len); Using Compiler Expl...
There are a few issues in the code, that may be leading you astray in the comparison. new char(len) allocates a single char, initialized with the value len. You'd be after new char[len] to allocate len chars. There should be a matching delete [], too. The std::vector<char> object is passed to populate_array by value, ...
65,652,937
65,653,055
Expression must be a modifiable lvalue - when setting an element of a dynamic array of fixed-length arrays
In my C++ program I have a dynamic char array where each element on this array is another fixed-size array, of length MAX_LINE_SIZE. This is how I defined this array inside my main function: char (*text)[MAX_LINE_SIZE] = nullptr; This array should contain some text that user enters from stdin: void init_text(char (*te...
The problem is that in text[i] = line; the types don't match. line is a char* and text[i] is an array: char[MAX_LINE_SIZE]. That is why you get the error error: incompatible types in assignment of ‘char*’ to ‘char [256]’ You cannot use assignment to copy a C-style string, you need to use strncpy (or do it yourself in ...
65,653,209
65,653,539
Modular Inverse Built-In, C++
There is a very nice way to find a modular inverse (that is, such b that ab ≡ 1 (mod m) for given a and m) in python-3.8: b = pow(a, -1, m) pow is built-in in python-3.8. Is there something like this in c++?
No there is no built-in function in C++ (to answer your question :) ).
65,653,339
65,653,398
Input/Output error when reading from serial port in Unix
My configurations for the serial port is close to the one in this link : Serial-programming-HOWTO in the non-canonical input mode. This is my code where the problem happens: char buffer; int received; while (true) { received = read(serial_com, &buffer, sizeof(buffer)); ...
Most likely you are trying to read data faster, than it comes in - and if you try to read a character, when none is available, this is indeed an IO error. You have a few possibilities: Use blocking mode (this will freeze the program at the read() call, until data is available use select to make sure you only try to re...
65,653,515
65,655,759
Initialize a class on top level that's defined bottom level in the same header file
Might be a dumb question. My apologies, but I would like to do the below, connectionState currentState; class connectionState { public: ....... ....... }; rather class connectionState { public: ....... ....... }; connectionState currentState; The former doesn't compiles at al...
There are forward declarations for this. Forward declarations also resolve the problem of circular dependencies: class connectionState; // forward class declaration extern connectionState currentState; // forward global extern variable declaration, now possible because connectionState is declared as a typename/class na...
65,653,767
65,653,859
C++ Benchmark Code Crashing - long numbers
Beginner here... Doing a code to check language performance in Cpp, Java and Python. The code must generate a random number N (1-60), fill a NxN matrix with random numbers between 0 and 9 and calculate its determinant. I started with cpp, but sometimes it succeeds, sometimes it fails. My guess is that crashes are relat...
Inside your function setMatrix: for (int j = 0; j < mat->N; j++){ mat->mat[i][j] = rand()%10; } rand() % 10 can sometimes generate 0 as well, thus putting zeroes inside your matrix. This will cause a floating-point exception when you do: Ratio = m1->mat[j][i]/m1->mat[i][i]; This line will again cause an issue whe...
65,653,983
65,654,043
GCC: 'std::is_same_v<int, T>' is not usable in a constant expression
Trying to implement the following code: template <typename R, typename V> concept SizedRangeOf = std::ranges::sized_range<R> && std::same_as<std::ranges::range_value_t<R>, V>; template<typename T> const SizedRangeOf<T> auto getView(std::vector<T>& vec) { // helper class class vector_view { std...
It seems to be a GCC bug: Bug 97402 - Value of dependent partial-concept-id is not usable in a constant expression. EDIT 04-Feb-2022: Bug is fixed in GCC 11.1 Playing with the same code while trying to make it compile in GCC leads to 'internal compiler error: Segmentation fault', for a code that compiles fine in Clang...
65,654,034
65,654,107
Getting a bad_alloc in the while loop
I have a problem with incrementing cur value, after that i get an bad_alloc error. Can someone tell me why is that happening cause i don't really understand. The program below is saving into the vector every number as many times as the number's value, then printing content of the vector. #include <iostream> #include <a...
while(v.size() != 100){ This will stop the loop when the vector's size is exactly 100. Inside the loop you will first add 1 value to the vector. Next time two values. Then three, and so on. If you work out the math on a piece of paper you will discover that you will never end up with exactly 100 values in the vector. ...