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,919,306
61,920,079
OpenGL doesn't paint, but the algorithm is correct
Hello I am implementing bresenham algorithm with openGl. The calculation formula is correct, It does not draw properly on the screen. What is the problem? It is not drawn even if the value is put in hard coding. And it compiles fine. #include <iostream> #include <GLUT/glut.h> void sp(int x, int y){ glBegin(GL_POI...
The vertex coordinates have to be in range [-1.0, 1.0]. The bottom left coordinate is (-1, -1) and the to right is (1, 1). If you want to specify the vertex coordinates in pixel unit, then you have to set an orthographic projection by glOrtho. For instance: int main(int argc, char** argv) { glutInit(&argc, argv); ...
61,919,519
61,920,038
Use sqlite3 in vscode for c++(undefined reference to `xxx')(I have use -lsqlite3)
I'm going crazy for this problem. I downloaded the source code and pre-compiled files of sqlite3 according to the tutorial, and used vs to compile, got the sqlite3.lib and sqlite3.exp files, and put it in the C: \ sql folder. Then I created the project in vscode, and put sqlite3.h in the root directory of the project, ...
I personally download the sqlite-amalgamation source and compile it as a regular source file. SQLite made it very easy and you should have no problem https://www.sqlite.org/download.html I don't mess with static/dynamic libs when I don't need to. The problem may occur because of which compiler compiled the library (ie ...
61,920,003
61,920,077
Variable inside a loop being set to the next array's element has the same memory address all the time?
Let's consider a little program like this: #include <iostream> using namespace std; typedef struct { int i, j, k; } ThreeDPoint; int main() { ThreeDPoint p[10]; for (int i = 0; i < 10; i++) { p[i].i = i * 3; p[i].j = i * 3 + 1; p[i].k = i * 3 + 2; } for (int i = 0; i < 10; ...
You are printing the address of the variable, not the address of your array elements. The variable and the array don't have the same address (obviously) and it's quite reasonable (but not guaranteed) that the same address would be reused for the variable each time around the loop. To print the address of the array elem...
61,920,083
61,920,316
How to call the value of a function-pointer member of a nested class of some enclosing class from within another nested class?
This is a pretty convoluted question, but I've tried to simplify the code as much as possible from my actual codebase. Let's say I have some class T with nested classes S and M. I have some methods method1 and method2 of S, and I also have a pointer selectedMethod that points to one selected of the two methods, by defa...
To me the prefix &t.s-> seems redundant It only seems that way because you store the pointer to member inside the same object on which you invoke the member. But given the general case auto foo_ptr = &SomeClass::foo; SomeClass obj; (obj*.foo_ptr)(); Both parts of the syntax are required. One obviously denotes the m...
61,920,449
61,937,194
C++ 2D vector to 2D pybind11 array
I'm fairly new to C++ and struggling with pybind. I simply can't figure out how to convince pybind to convert a 2D vector from C++ to a python-readable format. That's the code I have in mind: py::array_t<float> to_matrix(std::vector<std::vector<float>> &vals) { int N = vals.size(); int M = 6; py::array_t<fl...
There are a few things going on here, but let's start by getting a minimal example working. The following function will create a 2d array from a hard-coded std::vector<std::vector<float>> py::array_t<float> to_matrix() { std::vector<std::vector<float>> vals = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, ...
61,920,705
61,921,635
Self referential c++20 concepts
What is the moral equivalent to the following invalid code? // Suppose you want to check, as part of a concept, // if some operation on a type results in a type that models such concept. // you cannot constrain the resulting type with the same concept // in the same way you can't have self referential types // (that wo...
Suppose you want to check, as part of a concept, if some operation on a type results in a type that models such concept. That's infinite recursion. Like any functional recursion, you have to have a terminal condition. The normal way to define a terminal condition for template arguments is via a specialization. But co...
61,920,822
61,921,136
Imprecision when passing from string to int character by character in c++
First of all I am taking the string from geline(cin, s) and the input is in the form of: 100 49. And I can not take it with normal cin because I need to know where geline(cin, s) makes s empty so that means is a blank line and I should stop the program. When passing from string '99' (or any other number below 100) to i...
First of all I am taking the string from geline(cin, s) and the input is in the form of: 100 49. Then simplest solution is to use std::istringstream: int i1 = 0, i2 = 0; std::istringstream( s ) >> i1 >> i2;
61,920,992
61,921,042
I can't find a quote in [class.copy.elision] confirming that the initialization `T x = T();` is eligible for the mandatory copy elision
cppreference.com cites two cases for the Mandatory elision of copy/move operations. I'm interested in the second case as follows: In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type. Thus, the initialization below...
That's because the wording is in [dcl.init]/17.6.1 Otherwise, if the destination type is a (possibly cv-qualified) class type: If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initia...
61,921,167
61,958,670
Port pthread_cond_broadcast to std::atomic
Trying to understand all the in and out of std::atomic (lock-free operations in C++ 11). I was wondering if an operation like this: bool SomeClass::waitMyVariableToBeSet() { pthread_mutex_lock(&mMutex); while (!MyVariableToBeSet) { r = pthread_cond_timedwait(&msCondVariableSet, &mMutex, &ts); } ...
With C++20 this can be implemented using new atomic wait and notify operations: std::atomic<bool> MyVariableToBeSet; bool SomeClass::waitMyVariableToBeSet() { MyVariableToBeSet.wait(false); } void SomeClass::setMyVariable(bool newVal) { MyVariableToBeSet = newVal; MyVariableToBeSet.notify_all(); } Intern...
61,921,246
61,921,509
Is #include <Windows.h> bad practice?
I think it's universally accepted that #include <bits/stdc++.h> is bad practice, in part because it parses and includes every standard header, which is almost always unnecessary (it's also nonportable, but that's beyond my point). It's even worse when combined with using namespace std; because now you have a ton of com...
Msdn documentation explicitly tells you (a) in which header file a function is declared and (b) which header file you are supposed to include. Most functions tell you to include windows.h, for example SendMessage Some function, that were added later or have very specific use cases, are only available through other head...
61,921,324
61,978,516
Pointer Exception while getting RGB values from (video) frame Intel Realsense
I'm trying to get the different RGB values from a frame with the Realsense SDK. This is for a 3D depth camera with RGB. According to https://github.com/IntelRealSense/librealsense/issues/3364 I need to use int i = 100, j = 100; // fetch pixel 100,100 rs2::frame rgb = ... auto ptr = (uint8_t*)rgb.get_data(); auto strid...
stride is in bytes (length of row in bytes), multiplication with 3 is not required. cout << " R= " << int(ptr[i * stride + (3*j) ]); cout << ", G= " << int(ptr[i * stride + (3*j) + 1]); cout << ", B= " << int(ptr[i * stride + (3*j) + 2]);
61,921,476
61,922,477
Fibonacci Number modulo m
Task: Given two integers n and m, output Fn mod m (they is, the remainder of Fn when divided by m). My Code: #include <iostream> #include <vector> using namespace std; long long get_pisano_period(long long m) { long long a = 0, b = 1, c; for (int i = 0; i < m * m; i++) { c = (a + b) % m; a...
I tried what @idclev463035818 said and this seems to work. Try it, # include <iostream> # include <vector> using namespace std; long long get_pisano_period(long long m) { long long a = 0, b = 1, c; for (long long i = 0; i < m * m; i++) { c = (a + b) % m; a = b; b = c; if (...
61,921,720
61,922,188
How to handle recursion in member functions?
E.g., I have an empty function to clear a linked list: void empty(Node* head) { if (head->next) { empty(head->next); } delete head; head = nullptr; } But then I created a class for the linked list, so now I don't need to pass the head argument: void empty() { if (head->next) { empty...
A general approach is to declare a public member function that in turn calls a private static recursive member function. Pay attention that the name empty sounds confusing. It is better to name the function for example like clear. Here you are #include <functional> //... class List { public: //... void clear(...
61,921,784
61,932,373
How do I install boost-mpi and it's dependecies for clang on Mac OS?
I've been trying to install boost-mpi on MAC OS for clang, but I failed. Can anyone help me? I tried: brew install open-mpi brew install boost brew install boost-mpi But I got this CMake error: CMake Warning at /usr/local/lib/cmake/boost_mpi-1.72.0/libboost_mpi-variant-shared.cmake:64 (message): Target Boost::mpi alr...
I managed to fix it all. Actually, my error consists of a bunch of things. Firstly, as I found in this question, set(Boost_USE_MULTITHREADED TRUE) helps to remove CMake warnings. But then the issue with program warnings was because CLion doesn`t run mpi program with mpirun. But then there is other warning with mpirun p...
61,921,857
61,923,931
Halide with GPU schedule produce black image
I'm trying to learn Halide and I can't get GPU right, because it generate black images when scheduled for GPU. For CPU it produce good result (when comment out brighter.gpu_tile(x, y, xo, yo, xi, yi, 8, 8);) #include "Halide.h" #include "opencv2/core.hpp" #include "opencv2/highgui.hpp" void MinimalGpuExample() { c...
Try adding a buf.set_host_dirty() just after you construct it your input buffer. Halide isn't sure if that's uninitialized memory behind your pointer, or actual data that needs to be copied over when the GPU allocation is made.
61,922,677
61,922,761
Protected within this context c++
I'm having an issue with inheritance I guess. Here is the class from the header file: class Single : public Combination{ public: Single(Card* card); }; Here is Combination initialized in the .cpp file: Combination::Combination(Card** cards, CombinationType type, int numberOfCards){ this->cards = cards; thi...
You can't call a base class' constructor from inside a derived class' constructor body, like you are trying to do. It can only be called from the member initialization list. So you are going to have to change the way you allocate your array, eg: class Single : public Combination{ private: Card* myCards[1]; public...
61,922,988
61,923,088
How to synchronize threads at regular intervals?
I have problems synchronizing several threads at regular intervals without consuming too much cpu while waiting. I have a main thread, and several calculations threads that are all in the form : CalcThread() // x N threads { loop{ - do some calc stuff (variable but finite duration). - wait until main thread...
A condition variable is exactly what you want. Have your calc threads use std::condition_variable::wait to have them block until woken up by your main thread. Have the main thread call std::condition_variable::notify_all to unblock all of the calc threads.
61,923,289
61,931,764
Why and how should I use prototype design pattern
I am learning about design patterns and trying to implement them by myself. For most of design pattern I can understand there use and implementation but I am getting confused with Prototype pattern. Here is my approach to implement it. Ship.h class IShipPrototype { public: virtual IShipPrototype* clone() = 0; ...
The Prototype Pattern allows us to create a copy of an object polymorphically by calling virtual member function, which is usually called clone(), as in your code. Part which confuses me is that clone function returns the pointer for Interface, which means I can't store the clone in a different ship object In general...
61,923,337
61,926,340
Building/linking errors with the Vivek's Vcam / Capture Source Filtet
I'm struggling to build/link Vivek's Vcam / Capture Source Filter on Windows 10 with Visual Studio 2019 (Version 16.5.5) for x64 platforms. (I have already built the BaseClasses project with no issues.) These are the current building errors: >Dll.cpp >(folder)\vsprojects\sdk7samples\baseclasses\transip.h(214,55): error...
Try to disable "Conformance mode" in properties(From Yes(/permissive-) to No). I can reproduce this issue and then get it compile after disable it. This compiler option is set by default in Visual Studio 2017 version 15.5 and later, but it is not set by default in earlier versions. According to the /permissive document...
61,923,395
61,923,421
How to check is string correct to convert it to int?
Now I talk only about stl functions. Not something like this: for (char c : s) { if (c < '0' || c > '9') { return false; } }
I don't believe there is a built in function that does this, but you can use an algorithm to do this: bool is_valid_int(const std::string& s) { return std::all_of(std::begin(s), std::end(s), [](unsigned char c) { return std::isdigit(c); }...
61,923,669
61,924,057
Rule-of-five for a BST class in C++
I am implementing a binary search tree class and was wondering if my move/copy constructors and assignment operators are implemented correctly. (It seems to work correctly, but this is my first time implementing these constructors and assignment operators, I am afraid I might have missed something.) Here is the code (a...
The copy constructor default-initializes and then checks if other_tree is empty to avoid deep-copying it. But you already do that check in deep_copy_tree. Why not just initialize with that directly? BinarySearchTree::BinarySearchTree(const BinarySearchTree& other_tree) : tree_size{other_tree.tree_size} { std::cout ...
61,923,686
61,923,892
Modulus Function to Avoid Integer Overflow in C++
If I have 2 int or long long variables, call them a and b, and I want to compute the sum (a + b) mod p, where p is a large prime integer, how can I utilize the modulo operator in C++ to achieve the desired result? I have tried (a + b) % p, but this gives overflow sometimes, since a + b will overflow before the mod is a...
a %= p b %= p c = p-a if(b==c) sum = 0 if (b<c) sum = a+b if (b>c) sum = b-c EDIT: The trick is to avoid any calculation that might cause overflow, without knowing where the limit is. All we know is that the given a, b and p are below the limit -- maybe just below the limit. After the first two steps (a%=p;b%=p;)...
61,923,709
61,923,939
Why libraries automatically added?
I created a project in Visual Studio 2019. (Create a project > Windows Desktop Wizard > Console Application with all options unchecked.) Screenshot Something like this code is working but I didn't add math.h library to the code. I don't understand why sqrt function is working without error. #include <iostream> int mai...
Say you have the following files: a.h b.h main.cpp In main you have : #include <a.h> int main() { // Use func from a.h aFunc(); // Use func from b.h bFunc(); } Like your situation, let's say this builds no problem. How does the program know what bFunc is then? The likely answer is that a.h looks like thi...
61,923,805
61,924,259
C++ removing an std::function from a std::vector<std::function<...>>
I have the following system of callbacks class ... { ... std::vector<std::function<void()>> systemBringUps; std::vector<std::function<void()>> systemTearDowns; std::vector<std::function<void(EntityID_t)>> systemMains; std::vector<std::function<bool(EntityID_t)>> systemChecks; te...
You can use std::function<F>::target to get the held function object directly and compare that. For example, to erase all of the functions that are T::systemBringUp in systemBringUps, you could do something like: systemBringUps.erase(std::remove_if(systemBringUps.begin(), systemBringUps.end(), [](const auto& f) { a...
61,924,194
61,926,035
How to reference C# UWP Class Library from C++ UWP App
I am getting a COMException when trying to reference a method in a C# UWP class library from a C++ UWP app. This is happening with the most basic of setups, so I must be doing something wrong. Repro: Using Visual Studio (I'm using 16.5.4), Create a new "Blank App (Universal Windows - c++/CX)" Add to the solution a ne...
This issue is due to calling .net based WinRT components from C++/CX or C++ WinRT projects. To make it work, you can add Microsoft.Net.Native.Compiler nuget package in your c++/cx project and install it first. Then Right-click the project -> Unload Project -> Edit .vcxproj. After that, adding the following properties i...
61,924,283
61,924,717
I made my own custom stack and want to know how is there a way to iterate through the stack in reverse
This is the interface file #ifndef STACK_H #define STACH_H #include<iostream> using namespace std; class Stack { struct StackFrame{ char data; StackFrame* next; }; StackFrame* head; public: Stack(); void push(char); char pop(); void empty(); bool check_empty(); void ...
First of all as mentioned above, stack is LIFO data structure and thus should use another data structure for that purpose. Second, you can use second stack and copy data over to new stack, which is expensive. Third option would be to go from the top and kip a track and store pointer to the previous node and to the poin...
61,924,507
61,924,519
Only the first node in my Linked Listed is printing
I'm trying to build a basic linked list. I call the function appendNode() four times with different values and ONLY one prints to the screen. How do I get all four to print? how is it stuck at the first? void NumberList::appendNode(double num) { ListNode *newNode; ListNode *nodePtr; newNode = new ListNo...
In the case where there are existing elements in the list, your "appending to the end" logic is incorrect. You are trying to append the newNode every time in the loop. You need to append only when the end is reached: if(!head) head = newNode; else { nodePtr = head; while (nodePtr->next) { node...
61,924,590
61,926,499
no match for ‘operator>>’ (operand types are ‘QDataStream’ and ‘QJsonObject’)
I got this error when I using Qt 5.12 on Ubuntu Focal. However when I use Qt 5.13.2 and up, no error was shown. I want to get it work in 5.12 and lower, what should I to do achieve that? TQProfile::TQProfile() { type = "abc"; abcSettings = ConfigHelper::generateAbcSettings(); } QDataStream& operator << (QDataS...
A simple solution is to convert the QJsonObject to QByteArray using QJsonDocument: QDataStream& operator << (QDataStream &out, const TQProfile &p) { QJsonDocument doc(p.abcSettings); out << p.type << doc.toJson(QJsonDocument::Compact); return out; } QDataStream& operator >> (QDataStream &in, TQProfile &p) ...
61,925,101
61,925,142
Intel PIN: How do I see speculative instructions?
I'm writing a PIN tool where I want to see speculatively executed instructions that were eventually squashed. I.e. if a branch direction was predicted, some instructions were executed speculatively, the branch direction was resolved and the prediction was shown to be incorrect, the instructions that were executed woul...
You can't do that with binary instrumentation tools like PIN, only with hardware performance counters. PIN can only see instructions along the correct path of execution; it works by adding / modifying instructions in memory to run extra code. But this new code is still just x86 machine code that the CPU has to execute...
61,925,500
61,925,562
Is it possible to have an argument for a pointer in C++ and what does that mean?
I am trying to figure out what this line of code means: StJetTrack* track(int i) const { return (StJetTrack*)mTracks.At(i); } So, from my basic knowledge of C++, StJetTrack is a class, and track is a pointer, but then I get confused because track also has an argument, which then makes tack a function of some sort. Doe...
Remember that the syntax is: return_type function_name(arguments, ...); So in this case the StJetTrack* at the beginning means that the function return a pointer to a StJetTrack object.
61,925,502
61,925,596
C++: iterating over a list and an unordered_map in one loop
In c++, I have a list of wstrings and an unordered wstring/wstring map. std::list<std::wstring> m_L; std::unordered_map<std::wstring, std::wstring> m_UM; I need to run a loop over both lists and I don't want to repeat the loop code (in the unordered map, I only care about the first wstrings, not the second ones). Is t...
With C++20's ranges (or with range-v3 library) you can do that rather trivially: int main() { std::list<std::string> l_str = {"a", "b", "c"}; std::unordered_map<std::string, std::string> m_str = {{"d", "dd"}, {"e", "ee"}}; using namespace ranges::views; // for concat(), all() and keys() for (auto& e : ...
61,925,706
61,925,978
a template declaration cannot appear at block scope (template class in main)
here is my code: #include <iostream> using namespace std; template<typename T> class List { public: List(T); }; template<typename T> class A: public List<T> { public: }; int main() { //my problem is here...! A a(10); } I don't know how to declare this class in main and use it. In this case, I hav...
Since u didn't write a constructor for A, I supposed u want to use the inherited one, hence u have to provide the following line in A using List<T>::List; And since u used c++11, u have to provide the template arg, as follows A<int> a(10); If u want to make the compiler figure it out, use c++17 or c++20 and provide t...
61,925,722
61,925,754
Invalid operands to binary expression(when using two overloaded operators at the same time)
I am receiving the following error:error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Matrix') And the related code is like: Matrix Matrix::operator+(const Matrix &b){ Matrix C(r,c); int i,j; if(b.r!=r||b.c!=c) printf("invalid operation!"); else {for(i=...
(A + B) The result of this addition operation is a temporary value. ostream & operator<<(ostream &out, Matrix &A){ Temporaries do not bind, or convert, to mutable references. C++ does not work this way. They only bind to const references. Just change the 2nd parameter of this operator<< overload to const Matrix &, an...
61,926,005
61,927,714
How do I apply the printers.py modification? (Linux OS)
I checked the core file because the process(c++ lang) running on Linux died, and the contents of the core file [Corefile] File "/usr/lib64/../share/gdb/python/libstdcxx/v6/printers.py", line 558, in to_string return self.val['_M_dataplus']['_M_p'].lazy_string (length = len) RuntimeError: Cannot access memory at addr...
I think that there was a problem with class StdStringPrinter at printers.py I think you are fundamentally confused, and your problem has nothing at all to do with printers.py. You didn't show us your GDB session, but it appears that you have tried to print some variable of type std::string, and when you did so, GDB p...
61,926,015
61,926,118
Using the blend instructions in intel intrinsics (AVX)
I have a question regarding the AVX _mm256_blend_pd function. I want to optimize my code where I use heavily the _mm256_blendv_pd function. This unfortunately has a pretty high latency and low throughput. This function takes as input three __m256d variables where the last one represents the mask that is used to select ...
_mm256_blend_pd is the intrinsic for vblendpd which takes its control operand as an immediate constant, embedded into the machine code of the instruction. (That's what "immediate" means in assembly / machine code terminology.) In C++ terms, the control arg must be constexpr so the compiler can embed it into the instru...
61,926,670
61,926,744
Add include directory with Visual Studios 16.6
So i need to add a include directory to my project but the properties page gui has changed and now only has 5 options and none of them appear to add a include directory. Anyone figured it out yet because I can't seem to find the option in their new project property's setup. I'm on a c++ project if it matters.
It looks like you have opened the properties page of the solution. You need to open the properties page of the project instead. Project » Properties » C/C++ » General » Additional include directories
61,926,832
61,927,156
How to understand the sentence its lifetime began within the evaluation of e
int main(){ int v = 0; int const& rf = v; } To determine whether the expression int const& rf = v; is a core constant expression,it need to undergo these quotes: an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either: it is...
The beginning of that series of statements is: An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions: int const& rf = v; is a declaration, not an expression. Therefore, asking whether it is a core constant...
61,928,364
61,928,689
Can you use using to redeclare a public member in base class as private in derived class?
This code snippet demonstrating changing class member access came from IBM. struct A { protected: int y; public: int z; }; struct B : private A { }; struct C : private A { public: using A::y; using A::z; }; struct D : private A { protected: using A::y; using A::z; }; struct E : D { void f() { y = ...
The article seems wrong. It says, You cannot restrict the access to x with a using declaration. But I can't find such statement from the standard. [namespace.udecl]/19 A synonym created by a using-declaration has the usual accessibility for a member-declaration. [ Example: class A { private: void f(char); pu...
61,928,590
61,929,918
how to ignore n integers from input
I am trying to read the last integer from an input such as- 100 121 13 ... 7 11 81 I'm only interested in the last integer and hence want to ignore all previous integers. I thought of using cin.ignore but that won't work here due to unknown integers (100 is of 3 digits, while 13 is of 2 digits & so on) I can input...
It all depends on the use case that you have. Reading a none specified number of integers from std::cin is not as easy at it may seem. Because, in contrast to reading from a file, you will not have an EOF condition. If you would read from a file stream, then it would be very simple. int value{}; while (fileStream >> va...
61,928,943
61,928,984
Updating const variable value in C++
I know that we change const variable value this way in C(by changing it into non-const). #include<stdio.h> #include<stdlib.h> int main() { const int var = 10; int *ptr = &var; *ptr = 5; printf("var = %d\n", var); return 0; } similar thing (using a pointer) in C++ gives me a compilatio...
Modifying a const value through any mechanism (including casting away const-ness) results in "undefined behavior" (UB) which means that you cannot reason about the behavior of the program. The compiler is allowed to assume that const values will never change. Based on that assumption, the compiler might: Store const...
61,929,030
61,929,442
Shifting to the argument of a setter
Hello I want to use shifting operator >> to push something into an argument of function. To do it I can do the following, but is there any shorter and better answer? int foo; packet >> foo; setFoo(foo); The >> operator in packet takes an int. Also setFoo is constant and takes a constant reference of the integer. The ...
sf::Packet seems to have a member class called sf::getData() You can presumably do setFoo(*(int*)packet.getData()) but it isn't a "better" answer compared to your code.
61,929,268
61,930,359
Accessing different elements in an array
in for(auto e : elem) I am trying to figure how to access element e-1. while in pre- C++ 11 it would have just been elem[e-1] I am sure that has to be a c++ 11 equivalent.
With range-v3, you might do for (auto [p, n] : ranges::view::zip(v, v | ranges::view::drop(1))) { // ... } Demo
61,929,291
61,929,716
type trait for function pointer?
I need to conditionally use either std::abs or std::fabs inside template class, here is relevant code in simplified version: template <typename T> class C { public: using type = std::conditional_t<std::is_integral_v<T>, std::uint64_t, long double>; using check = std::is_integral<type>; // ERROR: mismatch i...
Do you really need to work with function pointers? Wouldn't be better to exploit C++ type-safe mechanisms? Such as follows: template <typename T> class C { public: using type = std::conditional_t<std::is_integral_v<T>, std::uint64_t, long double>; static const bool check = std::is_integral_v<type>; std::fu...
61,929,373
61,929,768
Bind Memeber function to another member
I want a system where an object inside a class can call a function inside that class when assigned. like this collider component example: class colliderComponent { void Collide() { //call the assigned function } } class object { public: void collideDelegate() { // do something } public: collidercomponent* ...
You can do this using std::function and std::bind. Here is an example (live demo): #include <functional> #include <iostream> class colliderComponent { public: void Collide() { collideDelegate(); } std::function<void()> collideDelegate; }; class Object { public: void collideDelegate() { std::cout << "collide de...
61,929,511
61,929,913
Inheritance and setting of a constexpr variable
I am trying to implement the following behavior: I have two classes, inheriting from the same class. Both of them will perform some work, changing their state at some point, and at some point, this state needs to be checked. The check is similar, for both classes in that in both tests, we compare the actual state with ...
template seems to help, especially as inheritance seems just here to factorize code: template <int x> class A { public: int y; A(int _y): y(_y) {} void test() { bool passed = x == y; std::cout << "Test" << (passed ? "" : " not") << " passed\n"; } }; // using B = A<2>; // Seems even eno...
61,929,586
61,931,072
std::vector<>.size() throws exception
i am trying to build a binary tree without pointers. Astd::vector<NODE>nodesholds my Nodes. This is my node: struct node { int bigger; int smaller; tuple data; std::vector<node> &nodes_ref; node(tuple d, std::vector<node> &nodes) : data(d), nodes_ref(nodes), smaller(0), bigger(0) {} bool insert(tupl...
I do not consider whether the logic in the two functions is correct or not: inline bool operator< (const tuple& lhs, const tuple& rhs) { if (lhs.a < rhs.a) return true; else if (lhs.a == rhs.a) { if (lhs.b < rhs.b) return true; else return false; } } inline bool operator> (const tuple& lhs, ...
61,929,815
61,929,878
I have to find the period of all numbers in an given array, like there are many solutions but size of the array is 10^5
Eg. The given array:[1,2,1,3,1,2,1,5] should return-1 -> 2 2 -> 4 3 -> 0 5 -> 0 There is a solution I can think of but it is of O(n^2). Suggest something better.
Transform in one linear scan your array into a hashmap of arrays indexed by value, containing the indices where that value was found. For your example this would be: { 1: [0, 2, 4, 6], 2: [1, 5], 3: [3], 5: [7], } Then for each entry l in the hashmap output 0 if len(l) <= 1, and otherwise output l[1] - l[0]. I...
61,929,851
61,935,730
How to static_assert that type is viable for template non-type parameter in c++20
I have a type TimeDuration. Right now it is literal type and I can use it as non-type template parameter. Such usage is very far away (compilation-wise) from type definition, so if anybody modifies TimeDuration such that it is no loner literal, it will be noticed much later. So I put static_assert(std::is_literal_type_...
There is a very simple way to get a compile error on whether a type is appropriate for use in a non-type template parameter: use it in a NTTP. The compiler will complain if it's not appropriate. You can easily write a small template somewhere and instantiate it explicitly with your type. Something like: template<auto v...
61,929,992
61,931,607
cast void* based on enum value in C++
I am writing a Python Library in C++ using the python C Api. There I have about 25 functions, that all accept two strings. Since Python might save strings in utf8/16/32 (the moment on char requires a bigger size the whole string will use the bigger size). When checking which kind the string is you get a enum value betw...
Put the complexity away in a function using variants using python_string_view = std::variant<std::basic_string_view<char>, std::basic_string_view<char16_t>, std::basic_string_view<char32_t>; python_string_view decode_python_string(python_string py_str) { Py_ssize_t len_s = PyUnicode_GET_LENGTH(py_str); ...
61,930,067
61,930,347
std::string not accessible after converting from QString
I have a QDialog which has a QLineEdit and a slot connected to the QLineEdit's textChanged signal. std::string gname; void NewMsgDialog::nameChanged(QString str) { auto temp = str.toUtf8().constData(); gname = str.toStdString(); } In the debugger I can see that temp has a sensible content (e. g. "my text") bu...
Your code has undefined behavior. str.toUtf8() returns a temporary QByteArray, which you are calling constData() on to get a pointer to its char data, which you are saving to temp. But then the QByteArray goes out of scope after that assignment, leaving temp pointing to freed memory before it can be used in the std::st...
61,930,161
61,930,779
Confusion about callback and registering a callback (C++)
I am new to using callbacks in C++. I found some terms related to callbacks and it is making me confused. I want to know the details about callback and registering a callback in C++. Are they both the same? Are they different? When and how to use each one? I will be grateful if anyone can help me understand these with ...
In terms of real life scenario. We have Alice who wants to receive package from Shop as soon as possible, but does not want to wait in the Shop until the package is ready. But Alice has a friend, Bob, who has lots of time and can wait in the Shop. So Alice comes with Bob to the shop and says, hey prepare a package for ...
61,930,163
61,935,676
Should the operators == and <=> in C++ 20 be implemented as a member or a free function?
Note: I presume that this is technically duplicate of this question but: changes to == in C++20 are quite radical, and I am not sure if reviving 9 year question is the proper thing to do. I ask specifically about the operators == and <=> that are being rewritten by compiler, not for example operator <. p.s. I have my...
I would argue that in C++20, comparisons should be member functions unless you have a strongly compelling reason otherwise. Lemme first start with the C++17 calculus: we would often write our comparisons as non-members. The reason for this is that it was the only way to allow two-sided comparisons. If I had a type X th...
61,930,209
61,930,811
C++ Using through an interface a class that inherits from several others
I am learning C++ and I am confused about the multiple inheritance and the interface classes. I want to have a class that inherits from several others. Also, I want to use that derived class through an interface. So I suppose, the derived class should extend the base classes, and the derived interface should extend the...
This is the well known diamond problem in C++. This is how you solve it: #include <iostream> using std::cout; using std::endl; class Base1Itf { public: virtual void blue() = 0; virtual ~Base1Itf() { } }; class Base1Abs : virtual public Base1Itf { public: void blue() override { cout << "blue" << e...
61,930,634
61,938,818
what happened if store with memory_order_acquire
as we know: load with memory_order_acquire, store with memory_order_release However, I found with gcc4.8.2, open -O2, a compile error throwed, /usr/include/c++/4.8.2/atomic:199:9: error: invalid memory model for '__atomic_store' but if close -O2, the error disappeared further more, if with gcc8.3.0, the error would...
Without optimization, the order isn't visible as a compile-time constant to a compiler built-in, and GCC just treats runtime-variable orders as seq_cst (instead of branching on the value to skip an mfence). Optimization is required for constant-propagation to make the illegal order visible to the compiler logic that c...
61,930,698
61,931,530
Using a smart pointer to a struct from a C library which hides the implementation via typedef's (i.e. incomplete type)
I'm trying to use a C library which basically only exposes typedefs to structs that are used internally. The issue is that I want to use smart pointers to manage the lifetime of the raw pointers which are the interface to the library, but I cannot create the smart pointers because of an incomplete_type error. Note I ha...
std::make_shared and std::make_unique are used to allocate and then construct objects and return them as shared_ or unique_ pointers. It expects to receive arguments which will be passed to the constructor of your class, and it needs the type to be complete so that it can call this constructor. In this case, however, t...
61,930,699
62,174,895
WriteProcessMemory fails inside function
Hi i am new to function hooking and i was using code from an article. This is my code #include <windows.h> #include <iostream> FARPROC messageBoxAddress = NULL; SIZE_T bytesWritten = 0; unsigned char messageBoxOriginalBytes[6] = { } ; int __stdcall HookedMessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT...
This is called hook recursion, to remedy the issue you need to use a trampoline hook. A trampoline hook is like a regular detour, it jumps to your code, but then it jumps back to the address following your actual jmp instruction, that way it doesn't execute your code over and over again. You do not need to use WritePro...
61,930,847
61,931,470
How do i solve this and debug this because i already match it
.cpp(27): error C2181: illegal else without matching if cpp(37): error C2181: illegal else without matching if Hello, how to solve this problem I want to build a program about discount and total cost of order below is the code.. it say the problem but i cant correct it thank you #include < iostream > using namespace ...
These errors are causing by misplacement of parenthesis. Check this code,I removed the errors from it: #include <iostream> using namespace std; #define retailPrice 20 int main() { float quantity,discount; float totalCost; cout << "Welcome to GLAMOUR bookstore,Enjoy our cool promotion.\n"; cout << "Please enter the qu...
61,930,864
61,933,550
function "scale" was previously not declared constexpr
I tried to compile (on VS15) example of constexpr functions from Stroustrup's book "Principles and practice using C++" second edition. And I get the error I mentioned in the title. All the code is from the book except for the struct Point. struct Point { public: double x; double y; Point(double x, double y)...
Your class Point cannot be returned by constexpr scale as it doesn't have any constexpr constructor. So it should be: struct Point { public: double x; double y; constexpr Point(double x, double y) : x(x), y(y){} }; Demo
61,931,734
62,104,566
FLTK 1.4 widget position w.r.t. X11 root window?
context I am coding with others RefPerSys, a GPLv3+ project in C++17 on gitlab for GNU/Linux/x86-64/Debian/Sid. Its fltk-branch git branch is using FLTK 1.4, compiled from source code, with an Xorg display server. I have C++ classes like (in file headfltk_rps.hh): class RpsGui_Window: public Fl_Double_Window { static...
There is a function inherited from Fl_Widget: x() and x(); you may call those to know the parent window position: class RpsGui_CommandWindow { void your_func () { int parent_x = RpsGui_Window::x(); } }; With X11, you may call XQueryTree to obtain the root ID of the window and then call XGetWindowAttrib...
61,931,895
61,938,174
What can be used to replace loops and if statements in my code?
I implemented battle ship game. Here i have function which checks game field correctness. bool Model::checkMyField() const { // Check field for correct ship placement return ( shipNum(1) == 4 && shipNum(2) == 3 && shipNum(3) == 2 && shipNum(4) == 1 ); } int Model::shipNum( i...
To avoid the double loop for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) You need some position iterator. struct Pos { int x = -1; int y = -1; } Simpler here would be to reuse existing container, such as std::array or std::vector constexpr std::size boardSize = 10; constexpr std::array<Pos, boar...
61,931,992
61,932,725
Perfect forwarding for returned value?
I'm overloading an operator[]: const Type&& operator[](int index) const { if (index >= size) { std::cout << "Error: excessive index.\n"; return 0; } else if (index < 0) { std::cout << "Error: negative index.\n"; return 0; } else { Node* temp = head->next; for (int i = 0; ...
Such unified syntax that would work for all, const/volatile/non-const/lvalue/rvalue/etc., implicit object parameters is currently not supported. However, there's the proposal P0847r4: Deducing this which adds this functionality. With that, you could say: template <typename Self> auto&& operator[](this Self&& self, int ...
61,932,018
61,932,170
How to differentiate between constructors
I have two constructors in a class template, one with array, one with vector as parameter. I have pointer members which point to the given parameters. I have to overload operator[] and write size() method (only one of each) that work with both but I don't know how to differentiate between the given types. How can I tel...
You can have a private bool flag at class level and set it to true of false based on the constructor being called. The Difference can be seen easily as one them takes two parameters and the other takes only one parameter so, constructor calls can be predicted. class view { bool flag; const T* arrayT; co...
61,932,059
61,932,231
Implicitly convertible argument, but of ref type
#include <iostream> #include <string> void foo(const std::string & s) { std::cout << s; } const char * text = "something"; int main() { foo( text ); } I started wondering what is happening here because gdb reports s == "". What is supposed to happen according to a recent (say C++17) version of the standard...
The class template std::basic_string has implicit conversion constructor basic_string(const charT* s, const Allocator& a = Allocator()); So in this call foo( text ); a temporary object of the type std::string is created and a reference to it is used as an initializer of the function parameter. At the end of this stat...
61,932,258
61,934,123
Path mismatch when including libraries with CMake
I am trying to include two libraries into my project to use them. I'm using CMake with CLion. The two libraries are: https://github.com/herumi/bls and https://github.com/herumi/mcl I got the following project setup: This is the main CMake file: cmake_minimum_required(VERSION 3.17) project(blsbenchmark) set(CMAKE_CXX_...
As discussed in the Q&A here, you have to provide a different path to the include_directories() command. In your case, you can provide the parent directory to those found in your custom Find Modules. For example, for the mcl repository, the header is located here mcl/include/mcl/bn.h. This is how you've defined the inc...
61,932,615
61,933,360
Sort std::vector<std::string *> overloading <
I want to use std::sort() on a std::vector<std::string *>. For this, I want to overload <. I want to use this operator to compare the first character in the String I guess the std::sort() function doesn't call my operator because the vector actually has std::string * as type instead of std::string. But I'm not sure h...
You have a vector of pointers to objects of the type std::string std::vector<std::string *> str_vector; So if you will call the standard algorithm std::sort without specifying the comparison function then the algorithm will try to sort the vector comparing the pointers themselves without comparing the pointed objects....
61,932,675
61,935,466
Multi Screen/Window QT QML C++ application
I am new to QT Quick and QML and I am trying to build a Linux Desktop multi Window application using C++ and QT. I mean application having multiples windows like: Slash or Welcome Screen Main Dashboard User Profile Charts and Graphs Etc. etc. I want to have these screens as independent C++ classes and QML files fo...
Use the Quick Controls 2 StackView control: https://doc.qt.io/qt-5/qml-qtquick-controls2-stackview.html This control maintains a stack of QML views where the top one is always visible and you can pop and push views with animation.
61,932,900
61,933,163
C++ template function, specify argument type of callback functor/lambda while still allow inlining?
What we usually do is like this: template<class Callback> void some_func(Callback const& callback){ .... } What I want is like: template<class void Callback(int)> //<--- void some_func(Callback const& callback){// not valid .... } We can specify the type if we pass by std::function but it disable inlining.
If you have C++20 that's is exactly what the concepts are for #include <concepts> template<typename T> concept Callback = requires(T a) { { a(int()) } -> std::same_as<void>; }; template<Callback T> void some_func(T const& callback){ // .... } int a(int) { return 0; } void b(int) {} int main() { /...
61,932,969
61,939,802
Changing the content of a const with a pointer in C++
I'm trying to understand pointers and I encounter this example. If I have int MAX_VALUE = 90; the program behaves like I expected. But with const int MAX_VALUE = 90; it doesn't. What is the explication? #include <iostream> using namespace std; int main() { const int MAX_VALUE = 90; cout << "Create variable...
As others have said, you're exploiting undefined behavior. In your case, your program is able to execute without crashing because your compiler's linker allocated space for the "constant" MAX_VALUE in RAM, and it was allocated in a RAM region whose attributes are not set as "read-only". I.e. it's being placed in writab...
61,933,022
61,937,449
Can't find VS 2019 Project Defaults in Property Page
I tried to change my character set with the project defaults but when I access the property page on my project and I go the general section in the configuration properties, it doesn't show the project defaults. Do you know any way to fix it so that I can edit my character set?
You have selected the wrong menu for character set. Its in the advanced settings of Visual Studio 2019
61,933,319
61,934,586
Check if the class has any base class in C++ in compile time
I want to check whether the class X has ANY base class using type utilities in C++. For example: class X : public Y { } static_assert(std::has_base_class<X>::value, "") // OK but: class X { } static_assert(std::has_base_class<X>::value, "") // Failed Does anything like my imaginary has_base_class exist in the standar...
As mentioned in comments you can't do exactly this in standard C++. The closest you get from std library is std::is_base_of, but it is for testing a specific base class. But as mentioned here GCC has std::tr2::bases (and std::tr2::direct_bases) that solves your question for a generic "has any base" assertion. These cam...
61,933,434
61,934,179
Detecting Walls in Multidimensional Arrays C++ Issues
I need some help figuring this out. For some reason, when I move along my array say for example "e" for east, I have made a detect wall collision so the player can't go any further. However, when I try to go "w" for west (back) it goes back 2 instead of 1. Any ideas on how to fix this? For now, use the e butt...
Its an issue with misleading logs - you don't print the current position, but the one which "type" is being checked. So you can get to logs [5, 0] and [3, 0] when: You move east from the [4, 0] room. You check what's at [5, 0] (first print). You hit a wall, so the current position is moved back to [4, 0]. Discouraged,...
61,933,533
62,667,310
Implementing one dimensional gsl integration in C++ with parameters as border of integration
I'd like to perform the following one dimensional integration in C++ using gsl, I(x) = int_{x/4}^1 dy y^{3/2+a} (1-y)^{1/2} exp(1.13*sqrt(log(4y/x))), where a and x are treated as constants of the integration and I would like to be able to perform the integration for x sampled in the interval 0.000001<x<0.001 for a fi...
If the x indicated in the lower limit of integration ("x/4" expression) is the same as the x participating in the formula of the integrand, then the solution is as follows: #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <cmath> #include <gsl/gsl_integration.h> #in...
61,934,484
61,934,706
deleting key from AVL tree that points to 1 or more values
I am working on a uni project and i need to create a idea bank that stores an idea. Per requirements i have created an inverted index algorithm that takes all words from one idea and stores them into an AVL tree, when retrieving a word from my tree it returns the ID the word was found in. the problem i am having is whe...
I think the problem is right here: for (int j=0;j<index.idList.size();j++) { if ( ID == index.idList[j]) { tree.AVL_Delete(wordsToDelete[i]); del = true; } } At that point you've found the idea inside the list of ideas that hav...
61,934,909
61,936,382
Why did I get rid of an error (reference to " " is ambiguous) just by removing using namespace std; in c++?
I was writing a recursive function (in C++) and instead of putting the arrays as parameters of function I made them global. When i used those global arrays in my recursive function I got this following error: "error: reference to "(name of array)" is ambiguous" My Code: #include<bits/stdc++.h> using namespace std; #d...
This is because left is the manipulator defined in C++ under namespace std.As,you are using it in your program as a global variable,it causes ambiguity. If you rename left to lef(or any other name that is not keyword or manipulator)in your program,your program works perfectly. Check this link to know about left manipul...
61,934,988
61,935,065
Overloading composed operators (+=,-=,*= and /=). Doesn't calculate how it should
The code is a part of a more complex one, but i reduced to see the part where i have the problem. So after overloading the +=, -=,*= and /= operators,the results are all the same and i don't know what i'm doing wrong. The header file looks like this: #pragma once #include<iostream> using namespace std; class Fraction...
The operators are overloaded incorrectly They create a new object of the type Fraction_ext and change it while the operators shall change the left hand side objects and return references to the changed objects. For example Fraction_ext & operator +=( const Fraction_ext &F) //overloadng += using member method { this...
61,934,998
61,936,995
std::for_each seems to be cleaning std::string
I'm making a simple snake game in c++17 with STL, and I have a problem with parsing board (std::vector) to std::string. I'm using std::for_each with my custom functor. Here's parsing method: std::string Board::parseBoardToString() { boardToString.resetStringBoard(); std::for_each(v_board.begin(), v_board.end(),...
Change std::for_each(v_board.begin(), v_board.end(), boardToString); to std::for_each(v_board.begin(), v_board.end(), std::ref(boardToString)); Function objects passed to std algorithms are copied; std ref wraps them up so they are not copied.
61,935,297
61,956,207
using an iterator of a map<char,strring> to return a pointer map<char,strring>*
Im working on a university assignment hence the pedantic nature of my question. The assignment is to implement a hash table, of size 26. The hash function is simply the last letter of the word {hash(apple) = e, hash(car) = r}. I have chosen to use a map<char, string> char for each letter of the alphabet (hash) and stri...
Ok, so I think you are attacking this the wrong way. std::map is already a fully fledged, hash-table-like container (cringe, yes I know it is not really, don't hurt me!). Using it will most likely lead you astray from what you should learn from this exercise. std::vector is your friend. If you have your ASCII table r...
61,935,632
61,935,782
Need help to create class Counter in C++
I have a task to create a programm which get a number from 0 to 999. Methods that should be realized in it. 1. too display this object. 2. to plus 1 for number. 3. to minus 1 from number. 4. to minus whatever number from original number. I've done all of then except last one. In m program it stand's for "o" #include <...
First thing you need to do is pass the 'number for minus' to the method that is going to do the subtraction. else if (opt == 'o') { cout << "input number for minus "; cin >> m; schet.process_minusnumber(m); // <-- change here Then you need to write process_minusnumber so that it takes ...
61,935,708
67,201,980
What are "Tony Tables"?
The following sentence is excerpted from the GitHub page: C++20 features described in Before/After tables ("Tony Tables") What are Tony Tables in the C++ culture? Why are they used to indicate Before/After tables?
Tony Tables are, to a certain extent, 'just' before/after tables. Show what code would look like without a certain function or feature, and show what it would look like with the feature. They were originally used in this C++ proposal: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0032r3.pdf (see the appendi...
61,935,787
61,935,845
Are `x = &v` and `*x = v` equivalent?
int * x; int v = 7; Given this code, what is the difference between 1. x = &v , and 2. *x = v ? I understand that in both cases, *x contains 7 but does x contain memory location of v in both cases? If not, what does x contain in cases 1 and 2, and is this the only significant difference between the two?
Given the statement: int v = 7; v has some location in memory. Doing: x = &v; will "point" x to the memory location of v, and indeed *x will have the value 7. However, in this statement: *x = v; you are storing the value of v at the address pointed at by x. But x is not pointing at a valid memory address, and so th...
61,935,819
61,936,031
Using std::size from non-const context
I'm wondering why constexpr functions (std::size in particular) do not work from some non-const context when only type matters. Let's have a look at two array_size implementations: The old good c++98 template <typename T, size_t N> char (&array_size_helper(const T (&)[N]))[N]; #define array_size(a) sizeof(array_si...
I wrote a whole blog post about this. No, std::size shouldn't be reimplemented. There's an important difference between the two implementations: with array_size(), everything is in an unevaluated context. Only the types matter, not any of the specific values. array_size() works for any C array type and for no other typ...
61,935,876
61,936,073
Does size_t have the same size and alignment as ptrdiff_t?
On my platform (and on most of them I think) std::size_t and std::ptrdiff_t have the same size and the same alignment. Is there any platform where that is not true? In short: is it required by the standard?
In short: is it required by the standard? No. The only requirement is from [support.types.layout]/2 and it is: The type ptrdiff_­t is an implementation-defined signed integer type that can hold the difference of two subscripts in an array object, as described in [expr.add]. There is paragraph 4 [ Note: It is reco...
61,935,928
61,935,960
How to create a function with an unknown number of parameters?
I need to create a function to calculate the average of int types. how to do it better? Example: double calculate_average(int num1, ...) { .... return sum / count; } int main() { calculate_average(5, 4, 3, 2, 1); calculate_average(3, 2); }
You can use fold expressions for this: template<typename ...Ts> double calculate_average(Ts... ts) { return (((double)ts / sizeof...(ts)) + ... + 0); } Note the sizeof...(ts), is a separate primitive for parameter packs. It's not a pack expansion, but instead gives the number of arguments that are passed into the fu...
61,936,228
61,936,468
how to work out the search complexity of a function
I have the following two functions and i am trying to compare the time complexity my first function is a simple for loop: For (i=0;i<m;i++) // do stuff Time complexity: i=0 is executed once i< n is executed n+1 times i++ is executed n times = 2n+2 = 0(N) i am struggling to work out my time complexity for this second...
The first for loop runs for (m-1) times, thus having time complexity O(m). The second function runs the AVL_Retrieve function once and for each loop count of index.idList times, giving the complexity O(log (number of nodes in tree))+O((count of index.idList)*m)
61,936,316
61,942,177
QListWidget rows overlaping each other
First of all I am apologizing for my English in advance. I am trying to display a custom widget in a QListWidget, but when more than one row is added, they are displayed on the same spot. (source: minespeed200.de) Settings of the QListWidget alternateingRowColors:true movement:Static isWrapping:false r...
The issue was that i left the gridSize of my QListWidget at it's default value and the y component had to be set to the height of my widget i was displaying. Adding: list->setGridSize(QSize(0,this->sizeHint().height())); fixed it.
61,936,900
61,937,386
Palindroms numbers between 1 to 10000
I want to write a program which displays palindromes numbers between 1 and 10000, I wrote a script which displays if the number typed by the user is a palindrome or no but when I add the for loop it gives me false results My code: #include<iostream> using namespace std; int main() { int num, reverse = 0, remainder, t...
You need to make sure that reverse is always 0 at the start of loop iteration: for(num=0;num<1000;num++){ reverse = 0; temp = num; cout << "temp = " << temp << endl; while( temp != 0) { remainder = temp % 10; reverse = reverse * 10 + remainder; temp = temp / 10; cout << "remainder = " << remainder << endl...
61,937,108
61,938,617
Is the visitor pattern a better option than controlled use of RTTI?
I often find myself trying to decouple objects using the boost/QT signals. The naive way to do this is for each concrete type I want to communicate, I create a new signal and slot signature and wire up all the dependent objects. This leads to the visitor pattern, ideally I'd like to emit a visitor and have all the list...
With visitor pattern, when a new listener is added to the IVisitor, you have the guaranty that existing visitors have to handle that new listener. With simple dynamic_cast, not handled listeners is more probable. depending how (each, (so no uniform behavior)) classes implement it, you might throw for unsupported listen...
61,937,214
61,938,194
Everything but arrays in c++ are passed by value by default?
Everything in c++ , including the STL containers are passed by value . But the exception is Array which are passed by pointers . Right? Why are arrays in c++ [eg: int a[5] ] are passed by pointers but the vectors are passed by value ? [By default] edit: okay , std::array can be passed by value also , I wasn't aware of ...
By default all function arguments in C++ are passed by value. Your confusion comes from the fact that the name of an array is actually a pointer to the first element of the array (eg. for the array int a[6], a is a pointer to a[0]. Unless the function parameter is explicitly a reference to a pointer, even pointer argum...
61,937,389
61,937,546
The output has extra % sign in C++
int n,t; cin>>n>>t; char arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } // for(int i=0;i<n;i++){ // cout<<arr[i]; // } while(t>0){ for(int i=0;i<n-1;i++){ if((arr[i]=='B')&&(arr[i+1]=='G')){ char temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = arr[i]; i++; ...
The extra "%" is not something printed by your program. It is just something that your shell added to tell you that there is no newline character after the text. In order to easily check this you can redirect your program output to a file. You will see that the "%" character will not be in the file. Alternatively, if ...
61,937,462
61,941,684
Material with several colors for mesh in Unreal Engine
I have a mesh presented as UProceduralMeshComponent. Also I have a set of colors: one color for each vertex of this mesh. I'm looking for a way to create a dynamic material in which all these colors will be and they will correspond to the coordinates of the vertices. It should look something like this: Does anybody kn...
UProceduralMeshComponent::CreateMeshSection accepts an array of vertex colors. Pass an array of colors for each vertex and use a VertexColors node in your material.
61,937,797
62,032,538
how to navigate to a user input site on OSX?
I'm pretty new to C++ and I'm trying to write a simple function to take user input and navigates to the site, adding the https://www. at the beginning of the string, but I cant quite figure out how to call the link within the quotes (or otherwise) within the system function. I come from python so I'm used to being able...
I made a few changes to your program: #include <fstream> #include <iostream> using namespace std; void openChrome(string site) { string link = "https://www." + site; string script = "open -a \"Google Chrome\" " + link; const char *command = script.c_str(); system(command); cout << link; } int main(...
61,937,850
61,938,442
How to exponentiation with while loop
I've a trouble. Like in descripton. How to do it in c++? Teacher gave a exercise that we must use three loops (for, while adn do..while), and this while loop is strange for me, what I have wrong in this code? #include <iostream> using namespace std; int main() { int a, b, c, d; cin >> a; cin >> b; c = a; d = 1; while...
I think you are looking for this answer. #include <iostream> using namespace std; int main() { int a, b, c, d; cin >> a; cin >> b; c = a; if(b == 0) { cout << 1 << endl; return 0; } while(b>1) { c *= a; b--; } cout << c; return 0; } In you...
61,938,855
61,940,166
C++: how to convert std::vector operations to Eigen::VectorXf?
I have this vector operation and I'm trying to implement Eigen:VectorXf to optimise its speed: for (int m = 0; m < vectorSize; ++m) { A[m] = ((B[m] * C[m]) + ((D[m] * E[m]) + (F[m] * G[m]))); H[m] = A[m] * I[m]; out = out + H[m]; E[m] = C[m]; ...
With vectors you have to use array() to get component-wise multiplication. You can use the sum() function to compute out as the sum of elements of H. VectorXf B, C, D, E, F, G, I; //... // Assuming all vectors have the same size const VectorXf A = ((B.array() * C.array()) + (D.array()) * E.array()) + (F.array() * G.a...
61,938,875
61,938,974
Defaulting to user input using a lambda when parameter is not explicitly passed
I wrote the following code (Still wondering about its uses...) to default to user input if the parameter is not passed. #define _CRT_SECURE_NO_WARNINGS #include <iostream> unsigned getInput() { unsigned input; std::cin >> input; return input; } void foo(unsigned number = getInput()) { std::cout << num...
Yes, you can use a lambda. What you need to do is call the lambda after you define it like void foo(unsigned number = []() {unsigned num = 0; std::cin >> num; return num; }()) // ^ define lambda ^^^ // ...
61,939,428
61,939,745
Increment `int i = 0` to increment in the position of an initialized char array
Let's say I have a char variable: int i = 0; char currentByte = (*(char*)((intptr_t)bytes + i)); Longer down in the code, I want to change currentByte depending on the number of i. How would I go on about this in C++? I wanted to do something like this: // Go through bytes, and go to next byte: i++; To then change c...
Functions are your friends: char GetByte(int pos) { return (char*)((intptr_t)bytes + pos); } And, perhaps, depending on the scope of your i: char GetCurrentByte() { return GetByte(i); }
61,939,725
61,939,726
Where, specifically, does the standard state that modifying a const object is undefined behaviour?
The following example is well known to exhibit undefined behaviour: T const x = T(); T& r = any_suitable_conversion_to_Tref(x); // fine r = T(); // UB This is confirmed for const_cast by cppreference: const_cast makes it possible to form a reference or pointer to non-const type that is actually referring to a const o...
The C++17 standard states in chapter 10 "Declarations" under [dcl.type.cv] 10.1.7: Except that any class member declared mutable (10.1.1) can be modified, any attempt to modify a const object during its lifetime (6.8) results in undefined behavior.
61,939,865
61,939,996
undefined symbol - using log4cxx in centos 7
I've difficulty to make my snippet code working on centos 7. So, I've these packages installed on the box: log4cxx.x86_64, log4cxx-devel.x86_64, apr.x86_64, apr-devel.x86_64, apr-util.x86_64, apr-util-devel.x86_64, glib2.x86_64, glib2-devel.x86_64 in CMakeList.txt, I've tried bunch of combinations (successful bu...
This appears to be a C++ standard library ABI mismatch; the mismatched symbols demangle to: log4cxx::xml::DOMConfigurator::configure(std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > const&) log4cxx::xml::DOMConfigurator::configure(std::__cxx11::basic_string<char, std::char_traits<char>, s...
61,939,974
61,955,058
Read list of different types from istream into vector
I'm trying to read text of the following format from an istream (e.g. std::cin): <type_code> <n> <elem_0> <elem_1> ... <elem_n-1> where First line <type_code>: 0=int, 1=double, 2=char, 3=std::string; Second line <n> is the number of elements in the list; Third line contains the actual elements, separated by a space c...
(Note: Please also refer to answers by @Jake Schmidt and @anastaciu. They provide great examples of C++17 std::any and std::variant) I figure out that putting everything in a template function fits my need just well. C++ is statically typed (whatever that means) so you have to write that switch statement anyway and in...
61,940,127
61,940,194
C++ map container erase() segmentation fault
I use this code to remove elements from map container that equal to some int. for(auto x:m){ if((x.second)==element)m.erase(x.first); } As result Segmentation fault. I also tried this: for(map<int,int>::iterator i=m.begin();i!=m.end();i++){ if((i->second)==element)m.erase(i); } Same result. If you put i++ into if...
erase() invalidates the iterator being used by the for loop. Fortunately, erase() itself returns an iterator to the next entry, so the correct loop would look like this instead: for (map<int,int>::iterator i = m.begin(); i != m.end(); ) { if (i->second == element) i = m.erase(i); else ++i; }
61,940,182
61,940,636
How to create a template class that can handle std::set with different type parameters
I need to write a template in C++ that implements an abstract version of a set. I can't find a solution (or worse, don't really understand what to do) about a compile error. This is a simplified version of the main program I need to compile and run -- that is, I MUST NOT change anything in this: #include <algorithm> #i...
This can be achieved through polymorphism and a template constructor. #include <utility> #include <memory> #include <iostream> template <typename T> class set_ops { private: // Interface type. class set_ops_iface { public: virtual ~set_ops_iface(); virtual void list() const = 0; };...