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
66,055,273
66,061,984
Program that checks the connectivity of the graph produces a segmentation fault
I'm currently making a program to check whether a graph is fully connected. My approach is to use a depth-first search traversal algorithm, and just ensure that every node is connected. However, I'm currently getting a segmentation fault as soon as I compile the program. I've tried everything, I haven't been able to fi...
The main issue was the fact that you forgot to set the sizes of the vectors. That was causing the segmentation fault. But there are several other issues with your code: The logic to detect connectivity is not correct. In practice, with your code, the connection of the last node only determines the connectivity of the ...
66,055,636
66,055,745
I have a problem with this function, the output results are incorrect
I am trying to make something like this: 2^1 + 2^2 + 2^3 + 2^4 + ... + 2^n This is my code: #include <iostream> int main(){ int n, p=0; std::cout<<"N: "; std::cin>>n; for(int i=1; i<=n; i++){ p = p+(2^i); } std::cout<<p; return 0; } The result is always incorrect. If I input...
Notice that each term is a power of 2, which can be represented using the left shift operator: for (int i = 0; i < N; ++i) { p = p + (1 << i); } You could also note that each term is 2 times the previous term. Thus you could write it also as: unsigned int term = 1; unsigned int sum_of_terms = 0; for (int i = 0; i < ...
66,055,641
66,055,792
What is a "prospective destructor" in C++20?
It seems that in C++20 something called a "prospective destructor" was introduced. In C++17 [class.dtor]: In a declaration of a destructor, the declarator is a function declarator (11.3.5) of the form ptr-declarator ( parameter-declaration-clause ) noexcept-specifier(opt) attribute-specifier-seq(opt) In C++20 this ...
It means what it says it means. It is a "destructor", modified by English word "prospective", which means "potential, likely, or expected". So it's a potential destructor. The purpose of the concept is to allow... concepts. A destructor is a special member function with special properties and behaviors. But most import...
66,055,708
66,055,749
Is there a way to detect input form file redirection? (C++)
I'm making a program that receives input in 3 ways: keyboard (via cin) file (via argument given at cmd line) and input from file redirect. I'm making an if-else statement where the first part tests if there was an arg at cmd line and an else when no file was given. Now I'm just trying to find out how to make an if st...
On Linux (and most other Unix-style) systems, you can do: #include <unistd.h> bool stdin_is_redirected = isatty (0) == 0; This relies on the fact that stdin is file descriptor 0. Documentation here
66,055,843
66,055,874
Is it possible to initialize a vector and return it at the same time in c++?
So I have a question that involves returning 2 values as a vector on leetcode. What I want to do is after finding these two values, create a new vector with these values and return the vector at the same time. Essentially, turn the lines vector<int> temp; temp.push_back(a); temp.push_back(b); return temp; into one lin...
Even more concisely, you can use list initialization. in a return statement with braced-init-list used as the return expression and list-initialization initializes the returned object std::vector<int> foo(int a, int b) { return {a, b}; }
66,056,260
66,056,797
IDWriteFactory::CreateTextLayout method causes window to suddenly close
In the app that I'm building using the Windows API, I am currently working on writing text to the screen. I am trying to use the CreateTextLayout method, but with that particular function, I am running into problems that I can't figure out how to solve. When I just run my app, I starts fine and the just exits with no e...
You confuse the use of D2D1CreateFactory and DWriteCreateFactory. D2D1CreateFactory is used to create the ID2D1Factory interface, which is used to create an ID2D1HwndRenderTarget and an ID2D1SolidColorBrush to render text. DWriteCreateFactory is used to create an IDWriteFactory interface, which is the root factory inte...
66,056,261
66,056,310
Run C++ code easily on GPU lik Python language
In order to run Python code with GPU (after installing all libraries for this), one can juste add these line before the code: device_name= tf.test.gpu_device_name() if device_name!='/device:GPU:0': raise SystemEror('GPU device not found') else: print('GPU found!') with tf.device("/device:GPU:0"): #python c...
C++ doesn’t have any facilities built in for GPU programming, you’d need to use something like OpenCL (or CUDA if you have an Nvidia GPU) for compute, or OpenGL/Vulkan or another graphics library for graphics.
66,056,263
66,056,316
How do you directly initialize a char array within a struct without memcpy, strcpy, or {...}?
Here's an example to clarify what I mean: // A struct with a char array struct StructA { char value[6]; }; char Initializer[6] = "Hello"; // This works StructA works = { "Hello" ); // This doesn't work StructA doesNotWork = { Initializer }; #define MyValue "Hello" StructA alsoDoesNotWork = { MyValue }; Yes, me...
How do you directly initialize a char array within a struct without memcpy, strcpy, or {...}? You can use one a string literal in a default member initialiser: struct StructA { char value[6] = "Hello"; }; If you don't mind using the curly brackets for another object, then you can use that to initialise the anothe...
66,056,305
66,056,516
Why is my array initalized with 0 on every position?
So i am a total beginner. Basically my goal is it to print out a board with the opening position of a checkers game, but i can only draw a blank board without any pieces on it. I don't understand why because i declared it should only do this when the array position equals white (-1). But if try to do a test and print o...
I think @M.M already pointed the issue. The problem was in your checking the status of board cell (i.e., boardArr.at(i).at(j)) in your printBoard() function. Here, I am adding the updated code, please have a look and compare it with your one: //main.cpp #include <iostream> #include <array> //#include "board.hpp" //bo...
66,056,639
66,057,762
Is there a way to specify and use a list of all data members belonging to a C++ class
When developing C++ code, I often find myself trying to do something for all the data members belonging to a class. Classic examples are in the copy constructor and assignment operator. Another place is when implementing serialization functions. In all of these situations, I have spent a lot of time tracking down bugs ...
This is no way to do this without reflection support. The alternative way is to transform your customized struct into the tuple of your member reference then using std::apply to operate the elements of the tuple one by one. You can see CppCon 2016: "C++14 Reflections Without Macros, Markup nor External Tooling" for the...
66,056,978
66,057,079
Coverity complains about htonl operands but why?
This code converts a local toggle into an outgoing network-order boolean (which is actually a 32bit uint) and is at least 10 years old but Coverity started complaining about it just recently. I don't understand what the problem is and where it's getting "operand |" from. Is the problem that htonl is only supposed to wo...
This is a false positive. On a little-endian platform, htonl does an endian swap, extracting the bytes of the argument and putting them back together in the opposite order using the bitwise OR operator. Coverity correctly realizes that one of those bytes will always be zero because the original argument in this case ...
66,057,263
66,057,334
Wrong SHA1 in c++ OPENSSL
Can someone tell me what I'm doing wrong ? I'm trying to print SHA1 hash for "12345" but it displays the wrong one, I can't figure out what is the problem in the code int main() { string smth = "12345"; unsigned char hash[SHA_DIGEST_LENGTH]; SHA_CTX sha1; SHA_Init(&sha1); SHA_Update(&sha1, smth.c_str(), smth.length()...
SHA_* functions calculate SHA-0 sum. Replace all functions with SHA1_* alternatives to calculate SHA-1.
66,057,371
66,061,363
Objective C++ stable ABI?
Question 1: I read that Objective-C under the hood uses the C ABI? Is that correct? Question 2: But in that case how does Objective-C so easily interop itself with C++? I can build a static library with Objective-C and C++ while the public headers are purely Objective-C. Question 3: Is this stable enough to be used by ...
Question 1: I read that Objective-C under the hood uses the C ABI? Is that correct? Sort of. Objective-C has its own linkage rules for class registration at runtime etc. Function calling (message passing) conventions do match those of C, though. In any case, it's considered stable. Question 2: But in that case how d...
66,057,536
66,057,744
function pointers with void* argument casting
I have no idea on how to look this up, even the title is confusing, even I am confused about what I'm looking for, and the question has for sure already been asked but it's so specific to be found, so here a bit of context: int comparison(const int* a, const int* b) { return *a - *b; } int main(int argc, char cons...
why he (the compiler) is not happy . qsort() expects a function point of type int (*)(const void *a, const void *b), not int (*)(const int *a, const int *b). The compiler could guess its OK and beform a cast, yet it is more productive for the compiler to warn about such problems. Or just the compiler whining abou...
66,057,566
66,057,732
How can I compile a 32 bit program using a makefile
I'm attempting to make 3 separate programs mem_1.exe, mem_2.exe and mem_3.exe. I need to make them 32 bit when I compile them and the error message does not seem to be reflecting what I am writing. Below is my makefile. mem_1: memlayout.o mem_1.o gcc -o mem_1 memlayout.c mem_1.c -ldl -m32 mem_2: memlayout.o mem_2...
I'd advise thinking of your makefile as code (since it is) and follow the standard advice to avoid repeating yourself. It looks like you also have the flags a bit wrong. -m32 is a compiler flag. -ldl is a linker flag. If you're going to build for 32 bits, you need to tell both the compiler and the linker to built 32-bi...
66,057,833
66,057,893
I am getting error like [Error] cannot convert '__complex__ int' to 'int' in assignment
here is my code and I amgetting error cannot convert 'complex int' to 'int' in assignment #include<iostream> using namespace std; int main() { // Write your code here int x; cin>>x; int res=0; for (int i=1;i<=5;i++){ res = 3i+2; } cout <<res; }
Your code is syntactically incorrect. I assume the correct code is this--> #include<iostream> using namespace std; int main() { // Write your code here int x; cin>>x; int res=0; for (int i=1;i<=5;i++){ res = 3*i+2; } cout <<res; }
66,057,952
66,057,975
C++ embarassing question on passing iterators to functions
So, given this function definition: void xx(list<int> my_list, list<int>::iterator start){ list<int>::iterator _start = start; distance(my_list.begin(),_start); } Why does the following cause distance() inside the function to hang? list<int> L; L.push_back(0); L.push_back(1); xx(L, L.begin()); I though...
my_list is declared as pass-by-value, it's a copy from the argument. That means, given distance(my_list.begin(),_start);, my_list.begin() and _start point to two different std::lists, the behavior is undefined. If you change it to pass-by-reference, then both the iterators point to the same std::list and the code would...
66,058,016
66,058,393
What happens we create a nullptr and use it in a IF condition in C++
Hi i am trying to see what happens when i create a nullptr in C++ and use it in a if statement. For example, my code is as following: int *p=nullptr; if(p){cout<<"Inside IF";} My questions are as follows: What happens when we create a nullptr? I mean does a new pointer object is created that holds the value 0(as addre...
What happens when we create a nullptr? You can create a null pointer, but not a nullptr. The keyword nullptr denotes a literal value, not something that can be created. Based on your code, you meant to ask what happens when a pointer variable is assigned nullptr. The answer to that is that your variable becomes a n...
66,058,623
66,058,746
Difference b/w these 2 statements while finding height of binary tree?
Please let me know if I am doing anything wrong here. I am unable to understand the difference between these 2 statements, while finding the height of binary tree. if (root==NULL) return -1; and if (root->left==NULL && root->right==NULL) return 0; The first statement is giving me accurate result but if I use the...
The first one protects against NULL anywhere, in root directly and indirectly via recursion in left and right. The second is vulnerable against root being NULL, it potentially derferences a NULL, which plausibly gets you the observed error message.
66,059,010
66,059,149
2 Dimension Arrays memory segment fault in C++
I made dynamic allocation and array initialization functions with cpp, but I got a segmentation error The code I wrote is below. #include <iostream> #define User_Height 100 #define User_Width 100 using namespace std; void Creat_Array(int** _pp_Created_Array) { _pp_Created_Array = new int*[User_Width]; for ...
So the problem is that you never return the array from the Creat_Array function. and so when you come to use the array you are using an uninitialised variable. Write Creat_Array with a return value instead of a parameter, like this int** Creat_Array() { int** _pp_Created_Array = ...; ... return _pp_Created_...
66,059,374
66,074,019
Can someone explain what this pointer refers to here?
I came across a prime number generator in which they used this line of code bool *numberlist = new bool[size+1]; What does this create? The code also has this in a for loop: numberlist[i*j]=true; Isnt numberlist a pointer? how can you iterate through it like an array.
To break it down, the first line of code bool *numberlist = new bool[size+1]; declare a dynamic bool arrays that have for size [size+1]. The code in the for loopnumberlist[i*j]=true;means that the element i*j is true. In C++ array decayed to a pointer "more specificaly to a pointer to the first element"(meaning that ea...
66,059,461
66,059,633
Copy constructor of the lambda expression
Here is a toy code with lambda: #include <cstdio> #include <iostream> #include <functional> std::function<void(int)> func(const std::function<void(int)> f) { return f; } class A { int x{}; public: A(int a): x(a) { std::cout << "A::constructor\n"; } A(const A& obj) { std::cout << "A::...
Cppinsight is not an implementation of the standard, and it doesn't magically generate all the code that a compiler would. The class that it shows for the lambda expression is such that the compiler will generate a copy constructor. Nevertheless, it gives you a hint: // inline __lambda_22_16(const __lambda_22_16 &) noe...
66,060,224
66,060,600
GCC: How to customising warning and errors generated from compilation
My Usecase: I have two c language files: ApplicationCode.c and UserCode.c . Application code is something generated by my app and UserCode is available to my application user where he can write his own code. ApplicationCode.c internally uses UserCode.c and calls out its methods/function. One thing you can assume here t...
or if there any other better way to do solve my use case ? If you don't want to "expose ApplicationCode.c", then why are you showing its compilation output in the first place? Solution: Compile it in somewhere secret and let the user link their UserCode.c with it.
66,060,239
66,060,324
Arduino C/C++ Convert binary string to decimal
I wanted to post this on the Arduino forum but couldn't find any "new post" button... Anyway, I wrote this function to convert a binary string into an int/long. However, it doesn't always work with big numbers. The following code is supposed to return "888888" but returns "888.887" void setup() { Serial.begin(96...
You can use a simpler function to achieve that: long binary_to_int(char *binary_string){ long total = 0; while (*binary_string) { total *= 2; if (*binary_string++ == '1') total += 1; } return total; } void setup(){ Serial.begin(9600); String data = "11011001000000111000"; ...
66,060,383
66,062,830
How to lock an item in QListWidget Qt
is it possible to lock on an item in QListWidget, so when I press for example: a button, the item stays selected? I have tried to look it up but I failed
I really hope you can provide me with an example, since I am just a beginner Yes, I can. Here we go: testQListWidgetLockSelection.cc: #include <set> #include <QtWidgets> class ListWidget: public QListWidget { public: using QListWidget::QListWidget; virtual ~ListWidget() = default; void lockSelection...
66,061,053
66,061,107
Copy paste of const and non-const methods
Consider the following code: http://coliru.stacked-crooked.com/a/d89377889a8ff749 IStorage has const and non-const get methods. The concrete implementation defines them, but the definition is just copy-paste. I could not call one get method from another because of the const mechanics of C++. Is there any way to avoi...
This is one of the legitmate uses of const_cast const std::string* get(ID id) const override { return const_cast<ConcreteStorage*>(this)->get(id); }
66,061,251
66,061,549
Why access c_str returned from object on the heap get garbage value?
Sometimes I need to call C++ objects from C. After some search, I know I can use extern "C" to wrap some interfaces which can be called from C. Here is my code: #include <iostream> #include <string> class Dog { public: Dog(std::string nm = "Eddie"): name(nm), sound("woof") { std::cout << "Dog " << name...
The best solution is to modify the code as follows : std::string bark() { return sound; } into const std::string& bark() { return sound; } Which equally leads to a correct execution and a correct code. If however you want to stick to the method provided in your original code and only solve the problem, here is ...
66,061,340
66,066,970
How to implement a hierarchical structure in a Qt model using MV?
I recently started learning Qt and am studying models. I have the following hierarchical model. struct group{ QList<sample> samples; QString name; } struct sample{ QString name; } There are groups - a list of groups. Each group has several samples. This completes the hierarchy. The sample has no children, and the gr...
You can store pointers to your group and sample objects in the QModelIndex::internalPointer Adapting this example, you get class GroupModel : public QAbstractItemModel { Q_OBJECT public: explicit GroupModel(QList<group> groups, QObject *parent = nullptr); QVariant data(const QModelIndex &index, int role) ...
66,061,663
66,061,793
Adressing variables by variable names
I am currently writing a ROS 2 node to pass values from a PLC through ROS to a visualization: PLC System --> ROS --> Visualization Since ROS should only pass on the data, I want to be able to configure the interface here with as little effort as possible. The idea, which can be implemented best with ROS, would be a con...
You cannot use variable names like that. There are no variable names at runtime. If you want a mapping between names (strings) and variables, you need to add that yourself. If your "variables" are of same type, eg int, you can use a map: #include <vector> #include <string> #include <unordered_map> using MsgFile = ...
66,061,664
66,061,930
Why cannot I read data from a serial port?
I have faced the following problem: I wish to read data comming to my serial port on linux. Data are send from an external device with standard serial settings. I'm sure that the external device sends them, that has been already checked. However, on linux all i can read is an empty byte. What am I setting wrong? My set...
I'm not sure what has happened but the following settings finally worked. I will share it with you as I got a lot of help here on Stackoverflow: serial = open(name.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); fcntl(serial, F_SETFL,0); tcgetattr(serial, &options); options.c_ispeed = _baudRate; options.c_ospeed = _baudRate; ...
66,062,263
66,107,991
CGAL edge_collapse assertion failure
I'm using CGAL 5.1 with a kernel of type typedef CGAL::Simple_cartesian<float> Kernel; and a surface mesh type typedef CGAL::Surface_mesh<Kernel::Point_3> Mesh; I load the mesh via Assimp, and everything seems fine. But when I come to run an edge_collapse I get an assertion failure CGAL_assertion(resulting_vertex_count...
While trying to isolate the issue to post here, I started playing around and found that because my mesh is noisy and patchy - it's photogrammetric scan - that the standard simplification strategy was barfing on my borders. Ignoring the assert just produced a starfish. So I followed the example in the user manual and ma...
66,062,396
66,064,582
How to generate an exectutable file with netbeans 8.2 in linux
I installed NetBeans 8.2 (but the same is for any version of NetBeans C/C++) in a linux OS (Linux Mint Ulyssa, which based to what i know is ubuntu core. I can run successfully with the expected result a project (simple "hello world") but can't in the build folder of the project i can't find a file that i can execute ...
So I don't run netbeans 8.2, but I got a hold of 12.2. And they seem pretty similar. What I had to do to get the project running was to create the compile (build) command: g++ main.cpp -o main And in run I did: ./main This allowed me to run a hello world code example through netbeans. In case you're not familiar with...
66,063,164
66,064,301
How can I change GUI from std::thread?
Firstly, I tried to use setVisible() from thread There is an event: void MainWindow::OnShow(){ // Start OnShow actions ui->LoadingBox->setVisible(true); std::thread dThread(OnShow_threaded, ui, &(this->settingsMap)); dThread.join(); } There is a function OnShow_threaded: void OnShow_threaded(Ui::MainWi...
As you asked for the demo with QThread, in the comments, then here it is. As GUI, I have a mainwindow with two simple buttons and I want to show, hide the big buttons with a QThread (instead of just the slot clicked) I emit an intermediate signal from the clicked to hide/show the button. The role of the QThreadis only...
66,063,199
66,064,361
Can we just have a header file for the inline global function and that means no .cpp file?
I have to add a global function to my program. My global function body is quite small, so I'm thinking of using inline. As we can define the body of the inline function in the header, so to confirm, we don't need a .cpp file at all? Or I'm missing something? inline void foo() { //function body } I mean, can we jus...
we don't need a .cpp file at all main cannot be inline, so you need at least one source file.
66,065,169
66,065,710
Accessing the structure field in unique_ptr causes access violation
I have a class like this: template <typename T> class Store { private: struct pointNode { T data; std::unique_ptr<pointNode> next; }; std::unique_ptr<pointNode> head; public: Store() : head(nullptr) {} Store(const T& data); }; Trying to create a constructor that is an exampl...
Your Store(const T&) constructor is not creating a pointNode object to be held by the std::unique_ptr<pointNode> of the head member. The default std::unique_ptr constructor will set head to nullptr, so it never points to an actual object. Thus accessing head->data is undefined behavior. Construct the head using std::ma...
66,065,394
66,070,240
How to element-wise divide 2 sparse matrices in Armadillo?
I am new to C++ but I am working with R and RcppArmadillo and my goal is to divide element-wise 2 sparse matrices. I have read in the documentation of Armadillo that the operator is / but when I source my code with sourceCpp I am getting this error: no match for 'operator/' (operand types are 'arma::sp_mat' {aka 'arma...
Use transform/foreach to calculate the inverse then multiply. //' Sparse Matrix element-wise division //' //' @param X sp_mat // [[Rcpp::export]] arma::sp_mat sp_mat_div(arma::sp_mat X){ arma::sp_mat x_inverse(X); x_inverse.transform([](double val) {return (1.0/val);}); arma::sp_mat Y = X % x_inverse; return Y...
66,065,977
66,066,054
Best way to make both a compile-time and runtime version of a function
I have a function that will be called by both compile-time and runtime functions (gtest and python ctypes). I need a templated version and one with the templated variables as function parameters. For example template<int A, int B, int C> void function_compiletime(int a, int b, int c) { // code section 1 } void fun...
Best way to make both a compile-time and runtime version of a function How can enforce that the body of the functions should be identical? By defining a single constexpr function: constexpr void function_runtime(int a, int b, int c, int A, int B, int C) { // code section }
66,066,605
66,066,932
non-atomic operations on atomic variables and vice versa
Given the below code: static int x; static void f() { for (int i = 0; i < 100; ++i) atomic_fetch_add(&x, 3); } Further, assume that f is called by two threads concurrently. Does C/C++ memory model guarantee that the result would always be 600 on all hardware platforms? And what if I changed it to the below? Is ...
If you want to use atomic operations on non-atomic variables, you can use std::atomic_ref (C++20). You can see an example here. Your second example should be fine because a_x is atomic with memory_order_seq_cst memory model and += is defined for it as an atomic operation.
66,066,993
66,067,478
How can I take a class out of a namespace automatically with Eclipse CDT?
I have a class A that is inside a namespace N in C++, so I can refer to it in the code with N::A. I need, in Eclipse CDT, to take that class out of the namespace N. Of course, I also need to edit all the occurrencies that refer to such class with the N::A notation in the codebase, so that the part referring to the name...
One plausible method is by using using N::A to load the class A to the global namespace. And then you can use the Eclipse CDT's find and replace feature to edit out all the N::A occurrences to A. You can either place using N::A only in the files where you want the class to be in the global namespace or else you can def...
66,067,052
66,067,230
C++ quadratic congruential generator
I'm rather new to C++ and I'm trying to implement a simple quadratic congruential random number generator. It seems to work alright but when I test it's period (repeat interval) it doesn't seem to repeat at all. I store the first random number in a variable and then compare the new numbers until the first one is encoun...
It goes in a 'rho' shape - first there are some unique numbers, then there is a loop. It doesn't loop back to the first number, but to some further number. Look up Pollard's rho algorithm, or Brent's cycle detection algorithm
66,067,390
66,068,416
How do I manage declarations that require template parameters derived from recursive functors/lambdas?
I am attempting to build a clean and neat implementation of recursive-capable lambda self-scoping (which is basically a Y-combinator although I think technically not quite). It's a journey that's taken me to, among many others, this thread and this thread and this thread. I've boiled down one of my issues as cleanly as...
The easiest solution is: uint evaluate(std::function<uint(uint)> func) const { return func(m_val); } a step up would be to write a function_view. uint evaluate(function_view<uint(uint)> func) const { return func(m_val); } (there are dozens of implementations on the net, should be easy to find). The easiest an...
66,067,554
66,107,935
memory_order_relaxed only guarantees atomicity and not visibility?
Given the below C code: static atomic_int a_i; static void f() { for (int i = 0; i < 100; ++i) atomic_fetch_add_explicit(&a_i, 1, memory_order_relaxed); } And two threads concurrently calling f(). Is it the case that a_i may end up having a non 200 result in hardware platforms with a relaxed cache coherency ...
The resulting value is guaranteed to be 200. The memory order argument is only about which other modifications are made visible to other threads. memory_order_relaxed means that no guarantees are made. But the variable itself is still updated atomically.
66,067,994
66,068,374
Why does this loop in my decryption function not work?
So the problem I'm facing is that a loop which is supposed to be converting a bunch of numbers(f.e. 12345) to an integer, so that the integer would have the value of 12345 in this case, but it just behaves weirdly...sometimes it works, sometimes it doesn't or sometimes it just fails in the middle...f.e.: (numbers separ...
Well, strictly speaking your problem is that you're using cint = +x within your switch statement, which sets cint to x, whereas you want to use cint += x which would add x to cint. You should throw out the whole switch statement altogether though, and replace it with cint += text[j] - '0' which does the same thing. You...
66,068,007
66,227,016
CppUnitTestFramework: Variable value set in TEST_CLASS_INITIALIZE does not persist in TEST_METHOD
I have a std::string declared in my TEST_CLASS that should be initialized once for the class that is to be used in two other TEST_METHODs. However, when TEST_CLASS_INITIALIZE is called (which does run before any TEST_METHOD), projectDirectory is properly set. Yet, the issue is that when I debug what the value is of pro...
There are at least a couple of issues with your example code. You are declaring a local variable projectDirectory in the TEST_CLASS_INITIALIZE, which hides the class member projectDirectory. TEST_CLASS_INITIALIZE cannot be used to initialize class members (unless they are declared as static). You should use TEST_METH...
66,068,038
66,071,406
getting `undefined symbol` errors when trying to import shared library written in c++ in python session
I was following this tutorial from boost.python to create a shared library. Here's a simple code defining the methods that I want to expose to python. #include <boost/python.hpp> #include <iostream> const int oneforth(int num, int bound) { if (num < bound) {return num;} return oneforth(num * (1/4), bound); } ...
I tried to reproduce this and got two different error messages 'like undefined symbol'. I'll explain both since I'm not 100% sure which one you encountered. this first was: Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: /mnt/tmpfs/py.so: undefined symbol: _ZNK5boost6python7objects...
66,068,151
66,072,388
AActor set mobility in ue4
How to set Actor by default in the Mobility section change from static to movable in c++. I know that you can just change the engine to select an item, but I want to understand what method in c++ allows you to change the Mobility section. I read the documentation and couldn't find it.
Actors are made up of Components, the RootComponent gives the Actor its Transform and Mobility within the Scene. Each component can have its own Mobility. Use the following function to change Mobility of a given component. MySceneComponent->SetMobility(EComponentMobility::Movable);
66,068,435
66,068,576
Why is it not printing in the right order?
#include <iostream> using namespace std; int output_1(string s, char c); int output_2(string s, char c); int main() { string str; char c; cout << "Enter a string: "; getline(cin, str); cout << "Enter a character: "; cin >> c; cout << "[1] the number of times the character appears: " <...
Instead of printing value in main, Try this : //call this from main output_1(str, c); output_2(str, c); Then: void output_1(string s, char c) { int count = 0; for (int x = 0; x < s.length(); x++) if (s[x] == c) count++; cout<< count<<endl; } void output_2(string s, char ...
66,069,429
66,069,473
Disadvantages of turning off cin synchronization with C scanf
I recently learned something from this question about cin in C++ and its speed was compared with the speed of scanf in C. Calling cin object is much slower than calling scanf function as usual but when I was reading the accepted answer, I understood if we call std::ios::sync_with_stdio(false);, cin synchronization with...
If you use both sets of I/O functions (header <cstdio> or <stdio.h> and also <iostream>) on the same stream (e.g. the stdin stream is associated with both scanf and cin), then you'd better leave them synchronized. If any one stream only uses one I/O family you can turn off synchronization (you can still use fscanf with...
66,069,619
66,070,220
No default constructor exists for class "class"
I have a diamond-shape set of derived classes: A / \ B C \ / D class A { //this is an abstract class protected: const double commonVariable; public: A(const double& commonVariable) : commonVariable(commonVariable) {} virtual double foo() const = 0; //pure virtual method }; class B : vir...
If A didn't had its default constructor deleted (by defining any constructor), this code would work. Either you have to call A constructor in initialization list of D. In case of virtual inheritance, instances of B and C are subobjects of class D, but they don't contain subobject of class A. Instead a single instance ...
66,069,781
66,069,975
User defined container not working with std::ranges
I cannot get my user defined containers to work with std::ranges. My container works if the iterator is simply an int* but as soon as I make my own iterator class I get compiler errors. This works. #include <iostream> #include <ranges> using namespace std; struct sentinel {}; class my_iota_view_a : public std::ranges...
The problem is that your iterator is not an iterator. The best way to answer this question is to use a static assertion: static_assert(std::input_iterator<my_iota_view_b::iterator>); If you do that, you'll see all the things your iterator is failing to satisfy. The first one is that it's not move-assignable. This is b...
66,070,159
66,076,776
what's the difference between callstack and stack?
I think I might be asking a very wrong question, but I really tried to understand it by googling, but with no luck. As we know, we have a stack and heap. Heap for the dynamically allocated ones, stack for local variables and e.t.c. Let's say I have the following c++ code. void bla(int v1, int v2, int v3) { int g = ...
Stack denotes a data structure which consists of a set of usually similar items and has the following abilities: push: adds an item to the "top" of the stack, which will become the new top pop: removes the item from the top, thus the item which was previously the top will be the top again; this operation returns the i...
66,070,211
66,070,625
When are fold expressions as template parameters allowed?
I have the following code: #include <type_traits> // ok template <typename... Args, std::enable_if_t<(std::is_same_v<int, Args> && ...), int> = 0> void foo(Args ...args); template <typename T> struct Type { // syntax error template <typename... Args, std::enable_if_t<(std::is_same_v<int, Args> && ...), int> ...
Use /std:c++latest not /std::c++17. It looks like a MSVC bug. template parameters are a bit strange, but not that strange. There are limitations on declaring lambdas in some cases, but most of everything else is "constant expression" and types.
66,070,825
66,072,765
threads that not working to copy a file into queue in C++
I'm trying to do a function that reads information from a file into a queue and then another function that reads the information from the queue to a file. Both functions are enabled by threads. The problem is that the first function does not store the information correctly and I do not know why? can anyone help me? Thi...
Your threads use copies of the MessagesSender. std::thread read(&MessagesSender::saveMessages, mess); std::thread write(&MessagesSender::sendMessages, mess); These bind by value. Use std::ref to prevent copying mess: std::thread read(&MessagesSender::saveMessages, std::ref(mess)); std::thread write(&MessagesSender::se...
66,070,908
66,071,033
Why is my static_cast of a pointer failing?
Why is my static_cast of a pointer failing? int iDog = 456; int *piDog = &iDog; long *plDog = static_cast<long*>(piDog); // invalid type conversion long lDog = static_cast<long>(iDog); // ok long* plDog = (long*)(piDog); // this is OK too... very weird!! (Dynamic cast... and we aren't allowed to use this one in ou...
TL;DR: If your cast worked, the language would provide no type-safety guarantees for pointers, and is a key part of the motivation for introducing the C++ style casts instead of sticking with the old-school C cast. In the language of the C/C++ Standard, long* and int* are not "pointer-compatible". You can't implicitly ...
66,071,098
66,071,294
Is there a way to refer to child classes with the parent classes namespace/classspace?
Suppose I have the following Mouse Event class with a Button event and extending Button Press and Button Release events: namespace Event { namespace Mouse { class Button : public Event { public: inline Input::Code::Mouse get_mouse_button() const { return m_Button; ...
Yes, you can do this. Forward declare these types in your Button class. That gives the types the scope you want. class Button : public Event { public: class Press; class Release; }; Then, outside the class you may define them. You must define them outside the class, so the parent class Button is co...
66,071,277
66,071,456
Win32 Edit control scrollbars not working in Windows 10
I'm currently trying to implement some scrollbars in a Win32 control but they just don't work when setting the WS_HSCROLL flag. From what I've read on other sites, they should "in theory" work because the class takes the message and does not push it to the parent window (Also that is how Rich controls work). To add a...
Fixed it! Seems like both scrollbars work only when ES_MULTILINE is defined. The original documentation does not say anything about it but that seems to be the case. I solved it by trying out this example and then removing stuff until it broke.
66,071,651
66,071,861
STL "sort()" doesn't sort adequately
I want to make an array out of a number's digits and then sort it, however when compiling it doesn't sort my array adequately. example : for n = 1432 array is "2, 3, 4, 1" NOTE : m is the number of digits n has (for n=1432 m=4) The following piece of code extracts every digit and puts it into the v array. Afterwards I ...
I must say that I cannot find any issue with your code and from what I can see it is working as it should (at least for me). However, I would do this in some other way. Like this #include <iostream> #include <vector> #include <algorithm> int main(){ std::vector<int> numbers; int n; std::cin >> n; ...
66,071,966
66,072,014
C++ GTKMM, getting a weird output in a text-buffer
I'm new to Gtkmm and trying to load a txt-file into a Text-Buffer. When I start my program I get a output like this: Output My code for filling the Text-Buffers looks like this: void ExampleGui::fill_buffers() { FILE *fp = fopen("/home/User/Documents/Gui/test1.txt", "r"); if (fp == NULL) exit(EXIT_FAILU...
The main problem here is the assignment output = line followed by free(line). Because output points to the same memory as line that means output becomes invalid. Either don't free the memory until you're done with the string, or duplicate the string in line (which the assignment doesn't do).
66,072,350
66,075,445
CMake: set warning flags for my project, but not included headers
I am building a project that includes llvm. I want to enable warnings for my code, but ignore warnings from code in llvm headers. I have a source file like: // main.cpp #include <llvm/IR/Instructions.h> void foo() { // blah blah blah } and a CMake file like: add_executable(prog main.cpp) target_link_libraries(pr...
You need to correctly configure include dirs in your CMake file. Something like this should do the trick: target_include_directories(prog <your project-specific include dirs>) target_include_directories(prog SYSTEM ${LLVM_INCLUDE_DIRS}) This way compiler will treat LLVM headers as "third-party" and won't emit any warn...
66,072,510
66,080,719
Why is there no std::data() overload for std::valarray?
C++11 introduced std::begin(std::valarray&) as well as std::end(std::valarray&). C++17 introduced std::data() which works with std::vector, std::array, C-style arrays, etc. But why wasn't an overloaded std::data() introduced for std::valarray? std::valarray is specified to have contiguous storage, which can be accesse...
As 1201ProgramAlarm stated in the comments, the proposal to add std::data does not make any mention of std::valarray. Unless someone can point out why &(a[0]) can't be used to obtain the valarray's data pointer, the simple answer is that valarray was either forgotten or ignored in the proposal.
66,073,146
66,073,221
enable_if not triggering in the constructor?
I am trying to implement very basic shared_ptr (most functions skipped in question for simplicity), and for the case we have a pointer of base and create a derived pointer I created a separate constructor. template<typename T> class shared_ptr { public: shared_ptr(T* resource) :pointee_(resource), refCount_...
This declaration is wrong: template<typename U, std::enable_if_t<std::is_base_of_v<T, U>>> When instantiated, enable_if_t yield void. This is not a valid non-type template parameter. Try using int instead: template<typename U, std::enable_if_t<std::is_base_of_v<T, U>, int> = 0> Also, remember that even if you're doin...
66,073,211
66,073,817
Is assignment to a std::atomic<double> variable guaranteed to be atomic?
I have the following scenario // first assigned a value greater than 0 std::atomic<double> var=1; //thread 1 while (True) { var = 1; } //thread 2 if(var >0) { //do something } My question is when thread 1 doing assignment, is there a possibility thread 2 sees var other than 1? Possibly some random number or ...
Yes, writes to atomic types are atomic. The bug in your code is elsewhere. Because it has never been set to anything other than 1, and the additional writes of 1 are atomic, there can't be any sort of "split read" where it reads some other value (as can happen on some architectures where the value may be written acros...
66,073,420
66,073,553
Why do alignment restrictions change the behaviour of clang while vectorising?
Can anyone explain the behaviour of clang? Array4Complex64 f1(Array4Complex64 a, Array4Complex64 b){ return a * b; } This function calculates for each element in a and b the complex product. I compiled it twice once with alignment restrictions on the type Array4Complex64 and once without. the results are the follo...
The first way is uselessly aligning RSP (and setting up RBP as a frame pointer in the process, so naturally it uses it). This is obviously a missed optimization since it's not actually spilling any of those function args to the stack. (Since this is not a debug build). You could report this to http://bugs.llvm.org/. ...
66,073,448
66,073,494
Something like python's __init__ in C++?
Is there something like __init__ in C++? Python let me pass arguments to class easily with __init__. Like This: class Book: def __init__(self, title, author): self.title = title self.author = author def printData(self): print(f"Title: {self.title}") print(f"Author: {self.aut...
You're talking about the constructor of classes in C++: #include <iostream> #include <string> class Book { std::string private_variable; public: // Equivalent to __init__ (it's what you're asking) Book(std::string value) { private_variable = value; ... } printVariable() { std::cout << private_va...
66,073,460
66,074,787
Checking if the first character of all the strings are same or not in a array of strings
I have an array of strings, I want to check whether the first characters of all the strings are the same or not. I know how to retrieve the first character of a string, by this method char first_letter; first_letter = (*str)[0]; Initially, I thought to go the brute force way, by checking for the first letter for every...
You needn't use a nested for loop.Rather modify your code this way for(int i = 0;i < size_arr - 2;i++){ f1 = (*str[i])[0]; f2 = (*str[i+1])[0]; if( f1!=f2 ){ printf("not same characters at first position"); break; flag=1; } } if(flag==0)printf("same characters at first position");
66,073,488
66,078,115
How to capture and modify mouse events in linux?
I want to write a program that changes the behavior of mouse when certain key is pressed. But I am not quite familiar with event mechanisms in linux. My guess is that I need to filter through the "event queue" looking for "key press" and "mouse press" events, and somehow modify the mouse event before passing it on or d...
My problem was solved using python-evdev Turns out it's quite simple. Just grab mouse and create another uinput to write desired event. import evdev from evdev import ecodes key=ecodes.KEY_LEFTSHIFT kb=evdev.InputDevice('/dev/input/event1') # keybord mouse=evdev.InputDevice('/dev/input/event3') # mouse dummy=evde...
66,073,601
66,074,128
What is wrong with this implementation of bubble sort using linked lists?
So this is the thing, I need to implement the bubble sort algorithm on linked lists. Yes, I saw many answers written in Stack Overflow that addresses this question. Almost all of them are implemented using pointers-to-pointers. Here, I tried to implement this using a referenced pointer rather than double pointers. I've...
Swapping is a bit special for lists. Swapping 2 consecutive nodes involves touching 4 nodes, the 2 swapped nodes, and the nodes preceding them. That's why the length of the list output from your sort() was not the same length as its input. Taking this in consideration, the swap operation then becomes: void swap_nodes...
66,073,893
66,074,470
Add element to function in place C++
Add element to function in place C++ Python code: l1 = [1, 2, 3] l2 = l1 + [4] print(l2) #[1, 2, 3, 4] l3 = l1+l2 print(l3) #[1, 2, 3, 1, 2, 3, 4] Is there a way to do this in C++
You clarified in a comment that you want to do it "in place". In C++17 there isn't an operator or function in the standard library for concatenating two vectors (or containers), but it is pretty easy to create one yourself: template <class T> std::vector<T> concat(const std::vector<T>& v1, const std::vector<T>& v2) { ...
66,074,014
66,074,042
implicit instantiation of undefined template error
I'm using Programming: Principles and Practice Using C++ (2nd Edition) for study and having some problem. Trying out the code written below gives me a implicit instantiation of undefined template error. I tried addding #include<vector> but adding the code gives me a new compile error of no matching function for call to...
You have two core problems. The first one is you're missing several headers: #include <string> #include <vector> #include <algorithm> string is for, well, std::string, and similarly, vector for std::vector. algorithm is for std::sort. The second one is that's not the how std::sort should be called, since it needs a pa...
66,074,109
66,074,464
How to "delete" original linked list when splitting the linked list into odd and even?
Here is the original code that I used: void split(Node*& in, Node*& odds, Node*& evens) { /* Add code here */ if (!in) { odds = NULL; evens = NULL; return; } else if (in->value % 2 == 1) { odds = in; return split(in->next, odds->next, evens); } ...
You may move Node to one or another list, by erasing pointer in original one: Not a perfect but working solution (print added for illustration if you wan run it in your compiler to see how it works) void split(Node*& in, Node*& odds, Node*& evens) { Node* temp = in; if(!in) { //std::cout << "\n"; ...
66,074,159
66,074,245
What is the purpose of declaring a function as a pointer?
I was looking through the source code of a project called CrossWindow-Graphics today when I saw an interesting function declaration. The code seemed to be declared as a function pointer. Here is a similar example I wrote. #include <iostream> using namespace std; void (*Test()) { cout << "Test Called!" << endl; } ...
All you've really done here is add an extra pair of () that doesn't do anything. We could write the same functin as void* Test() { ... } It's a function that returns a void*. So the function should have a return statements where it returns a void pointer. Some compilers will warn about this as seen here.
66,074,788
66,076,407
Regex expression for matching $(..)
Suppose I have a string that looks like this std::string str = "I have $(xb) books and $(cs) pens"; What is the easiest way to extract xb and cs (extract characters surounded by $() ) from the statement ? Is it possible to do some regex magic that would return a vector that contains xb and cs ? I am trying something l...
$ has a special meaning and * applies to the opening brace in your regex. You could use a capturing group and match starting at the char after the opening brace that's not a closing brace in the brackets, i.e. use the regex \$\(([^)]*)\): std::string str = "I have $(xb) books and $(cs) pens"; std::regex rgx("\\$\\(([^)...
66,074,820
66,077,613
How does printf("%d",x) work/interpreted?
I am wondering how exactly printf("%d",x) is interpreted. All I know that the compiler reserve a memory to put '%','%d','\0' and returns its address to printf, and then it prints the second argument x based on the format specifier that we indicated. So if I use for example int x=5; char *p="%d"; printf(p,x), is it t...
How is printf("%d",x) is interpreted? OP's explanation is one potential partial description of code. Yet C and C++ are typically compiled, not interpreted. Compilers today can examine printf("%d",x) and emit code like print_an_integer(x);. With OP's example, the 2 codes are functionally the same, yet a compiler ma...
66,074,829
66,074,909
Why do some LLVM standard library headers include other headers but GCC does not
While making a project compile across both GCC and Clang, I've noticed that functions like fabs were causing compilation issues on GCC, since I had never included <cmath> myself. I was developing on Clang, so I never noticed this, since the llvm <cstdlib> header file I was using includes <cmath> itself, seemingly witho...
For every function you use, consult the C++ reference to find out which header you should include. The reference for fabs says that you have to include <cmath>.
66,074,911
66,074,926
Undefined behavior when converting char to std::string c++
My program takes in a vector std::vector<std::string> vector and a character char separator and returns a string with all of the strings added together between the separator character. The concept is: vector[0] + separator + vector[1] + separator The Code std::string VectorToString(std::vector<std::string> vector, char...
This line std::string separator_string(&separator); tries to construct a string from a 0-terminated C string. But &separator is not 0-terminated, because it depends on the other bytes of memory following separator if there is an 0 byte in there (probably not). So you're getting undefined behavior. What you can do i...
66,075,175
66,075,243
CPP console applications exits without providing error information
When I compile and run the below piece of code the exe crashes yet doesn't provide information of any sort regarding why it crashed. (Seg faults etc. not reported). Here is the sample code that I tried: #include <iostream> #include <vector> using namespace std; int main() { vector <int> values; int temp = val...
Calling std::vector::back on an empty vector is undefined behavior. The compiler or runtime aren't required to emit a diagnostic. There might be a tool or sanitizer that could help depending on the compiler you're using.
66,075,464
66,075,813
Is there any way that I can directly turn the bitwise representation of an integer into a vector in c++?
I want to turn the bitwise representation of an unsigned integer directly into a vector<int> or vector<bool> in c++ for example: unsigned un = 203;//bitwise representation: (multiple 0) 1100 1011 //…… //I want a vector like this: vector<int> unv = {1,1,0,0,1,0,1,1}; //or vector<bool> unv2 = {1,1,0,0,1,0,1,1}; is there...
You may use the function std::generate from the standard library. Description of the function can be found here. This, we will use with a statefull Lambda and mask out bit by bit. The result will be stored in the std::vector So, this is a typical one-liner. I am not sure, if this is "directly" enough for you. But as sa...
66,075,472
66,075,575
Count new lines from file doesn't work properly
I am trying to count new lines from my file, but it doesn't seem to work. It gives me result 0 when there is 1 new line. How can I fix this? getline(file, newstring); char line; int lines = 0; for (int i = 0; i < newstring.length(); i++) { if(line== '\n') { lines++; } } cout << lines;
As I understand it, this may also provide what you need: #include <iostream> #include <algorithm> #include <fstream> int main() { std::ifstream inFile("file"); // DISPLAY number of `\n` characters std::cout << std::count(std::istreambuf_iterator<char>(inFile), std::istreambuf_ite...
66,075,738
66,077,804
How to get typename aliases from an argument passed via concept?
Let's take a look at the following code: #include <iostream> #include <vector> #include <iterator> template<typename T> concept Iterable = std::is_same_v<decltype(begin(std::declval<T>())), decltype(end(std::declval<T>()))>; void print(const Iterable auto& c) { std::copy(begin(c), end(c), std::ostream_iterator<???:...
Assuming that what you mean to do is get the nested typedef of the type, just don't use the abbreviated function template syntax: template <Iterable C> void print(C const& c) { std::copy(begin(c), end(c), std::ostream_iterator<typename C::value_type>(std::cout, ", ")); } This gives you the opportunity to n...
66,075,804
66,076,601
static_assert in production code header: bad for compilation time?
I wrote a few "compile-time math" functions in a utility header file and I'm using static_assert statements to test them. Whether to keep these statements with the production code or with the test code (in a dummy 'unit test' *.cpp) is probably mostly a matter of style/preference (comments welcome, though). But what ab...
If I keep the static_assert in the production code header, will they be run for every compilation unit I include the header in? Yes. An include does nothing else then inserting the content of the included file into the including file. To the C++ compiler there's no difference whether your code comes from a header or ...
66,075,808
66,075,862
Сreate a shared_ptr from a unique_ptr containing the structure
I have a class containing such a structure: class Store { private: struct pointNode { T data; std::unique_ptr<pointNode> next; pointNode():data(std::move(T{})),next(std::move(std::unique_ptr<pointNode>{})){} pointNode(T n_data, std::unique_ptr<pointNode> ptr) : data(std::move(n_dat...
unique_ptr cannot share the data with shared_ptr. That's the point of a unique pointer. But if you want to transfer the ownership, you can do it like so: #include <string> #include <memory> int main() { std::unique_ptr<std::string> up( new std::string("Hello, World!\n") ); // up owns the object // Transfer owne...
66,075,900
66,075,964
Assign type to a variable and pass it to template
I have the following code template <typename T> auto CallMe(int param) -> void { ... } auto Test(int userInput) -> void { int paramToUse = SomeFunction(userInput); if (userInput == 0) { CallMe<__int32>(paramToUse); } else if (userInput == 1) { CallMe<__int16>(paramToUse); } else if ...
How about: decltype(CallMe<__int32>)* callable; // function pointer // set the function address as necessary if (userInput == 0) { callable = CallMe<__int32>; } else if (userInput == 1) { callable = CallMe<__int16>; } else if (userInput == 2) { callable = CallMe<__int8>; } else { // ... } callable(paramToUs...
66,076,162
66,076,261
Type deduction of ternary operator with mixed lvalue and rvalue usage
Recently, I came across own code that I wrote accidently this way (much simplified here): #include <iostream> #include <string> void foo(std::string&& value) { std::cout << value << std::endl; // for instance modify value here somehow optionally and move it further on ... // foo2(std::move(value)); } int main()...
According to cppinsights.io the compiler is creating a temporary std::string. foo((idx < 1 ? std::basic_string<char, std::char_traits<char>, std::allocator<char> >(value) : std::basic_string<char, std::char_traits<char>, std::allocator<char> >(std::move(value)))); And here the version that separates the ternary operat...
66,077,662
66,078,216
Optimizing loop for better performance
I parallelized my code like that: for (int i=0; i<size; ++i) { #pragma omp parallel for for (int j=i; j<size; ++j) { int l = j+1; float sum = a[i*size+j]; float sum2 = a[l*size+i]; for (int k=0; k<i; ++k) { sum -= a[i*size+k] * a[k...
Without redesigning the code you can try something like: #pragma omp parallel { for (int i=0; i<size; ++i) { #pragma omp for for (int j=i; j<size; ++j) { int l = j+1; float sum = a[i*size+j]; float sum2 = a[l*size+i]; ...
66,077,872
66,077,927
Are some std classes in C++ used in real life applications?
I have a question, in real applications like: companies, software development, etc... Do they use some std classes(or containers, I'm not sure about the correct name) such as std::vector, std::array and std::string in the code? Or do they implement new ones?
It depends on the platform that your building to. If its for embedded applications, you might use a custom implementation to fit that platform and to get better performance. If its for a desktop application, you'll most likely use the provided STL containers (why reinvent the wheel?). Or else there could be scenarios l...
66,077,916
66,082,061
How to find out the type in internalPointer?
I have model like this(in treeView): data1 - one type hello - second type data1 struct Group { QString name; QList<Sample> samples; } hello struct Sample { QString name; } I have slot void MainWindow::on_treeView_clicked(const QModelIndex &index) { Group *group = static_cast<Group *>(index.internalPointer()); ...
I highly recommend using one common base class for all your tree items, as was pointed out in the comments. This base class should declare virtual functions for any piece of data that you'll need in the tree (name, icon, number of children, etc.), which you then override in the derived classes that represent specializa...
66,078,020
66,078,062
Qualifiers on =delete methods
When marking special methods as =delete do the qualifiers of the method come into play ? In other words are: inline constexpr myClass(const myClass&) noexcept = delete; and myClass(const myClass&) = delete; equivalent ?
As often it is, it's usually to just try it and ask the compiler: class myClass { inline constexpr myClass(const myClass&) noexcept = delete; myClass(const myClass&) = delete; }; int main() { return 0; } 1 bla.cpp|4 col 5 error| ‘myClass::myClass(const myClass&)’ cannot be overloaded with ‘constexpr myCl...
66,078,347
66,078,430
Is "pointer to const int" same as " const int* "
I am reading about pointers and got confused in one part. The code given is as follows: int i=0; const int ci = i; auto *p = &ci;` Now the question is what will be the type of p? I am thinking that p will be a pointer to const int. Is this correct? And if yes will this be equal to const int*? Is a pointer to const int...
In C++, the const keyword generally applies to the part of the type to its left. So int const* is a pointer to a constant integer, and int*const is a constant pointer to a non-constant integer. The type of p in your example is a int const*. The habit of putting const to the right is known as east const. Now there is an...
66,078,352
66,078,908
Conan error: Incompatible requirements obtained in different evaluations of 'requirements'
Greetings to my C++ heroes, I am trying to use Conan package manager to build dependencies of my C++ application (specifically libraries OpenCV and Tesseract). My conanfile.txt looks like this: [requires] opencv/4.5.1 tesseract/4.1.1 [generators] cmake When I run conan install ../src --build=missing command in my bui...
There is a version conflict : WARN: libtiff/4.1.0: requirement libwebp/1.1.0 overridden by leptonica/1.80.0 to libwebp/1.0.3 libtiff wants libwebp/1.1.0, but leptonica asks for libwebp/1.0.3 Conan will not solve it for you, because it could create a different behavior accord libwebp version. So it raises: ERROR: lib...
66,078,579
66,078,661
Error: "couldn't infer template argument '_Tp' " when passing in {} into
struct compar { bool operator()(const vector<int>& a, const vector<int>& b) const { return a[1] < b[1]; } }; ... auto it = lower_bound(events.begin(), events.end(), {0, events[i][0]}, compar()); This code gives me an error with the {0, events[i][0]}: /bits/stl_algo.h:2022:5: note: candidate...
Braced-init-list has no type itself, it can't be used for deduction of template parameter. This is non-deduced context: In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either...
66,078,754
66,079,085
C++17 how to test class has a member variable?
I am going down the route struct S { static constexpr int extra=5; }; struct V { }; template <typename T> void f() { if (std::is_same_v<decltype(T::extra), int>) std::cout<< "extra exists" <<std::endl; } but calling f<S>() fails as std::is_same_v<decltype(S::extra), int> == 0 and f<V>() does not compile
If you are stuck in c++17, there is some infrastructure that you can add to make detection like this much easier. Detection-idiom The most reusable/consistent way to detect features like this is via the Detection idiom, which leverages SFINAE through std::void_t in a template. This can be taken verbatim from std::exper...
66,078,990
66,079,124
how function overload when class can cast to function type
Recently I am reading c++ templates. There is a ambiguity example in appendix B.3.4 and I add some detail to compile. #include <stdio.h> typedef void FuncType(double, int); void f(double, int) { printf("call %s\n", __func__); } class IndirectFunctor { public: void operator()(double, double) { prin...
At the call site in activate, funcObj is a const reference. Because IndirectFunctor::operator() is not a const member function, it is not a viable candidate for funcObj(3, 5). Either make the function call operator const (IndriectFunctor::operator() const) or change the parameter to activate to not be const (void activ...
66,079,139
66,079,201
C++, modify value on the heap VS delete and new
In a class example in a C++ book, there is an overloading of the assignment operator with the following lines: delete m_pName; m_pName = new string(*(c.m_pName)); What is wrong with, instead, simply change the value in the already allocated space? *m_pName = *(c.m_pName); Thank you.
There is nothing wrong with your approach. In fact I would use it. I would even question why there is a std::string*, why isn't it a std::string or a std::optional<std::string>? The only difference that I see is that the original code makes sure that the memory is freed and freshly allocated. Your approach might reuse ...
66,079,598
66,081,193
Button to join thread causes win32/winAPI application to freeze
The title pretty much summarizes what my problem is. I have this function shown below and when I press the button to join the thread the application stops responding. I'm fairly new to multithreading in c++ and I don't really know what I am doing or why this is occurring. HWND hwnd; //this stops the declaration of the ...
joinThread.join() blocks the calling thread until JoinLoop() exits. If you do that call in your main UI thread, you will be blocking your message loop from being able to process new messages. That is why your UI freezes. JoinLoop() is waiting on 2 conditions - user input being entered, and stopRaidAction being true wh...
66,079,936
66,082,093
Why are files not found from parallel folders CMake
To have my .cpp and .h files a little bit sorted up pending on their responsibilitie I decided to put them into seperate folders I used the following structure: root | -CMakeLists.txt [rootCmakeList] src | -main.cpp .......| ....... math .......| .......-CMakeLists.txt[mathCmakeList] .......-Algebra.h .......-Algebr...
myProject doesn't seem to be a variable you set. Furthermore if you properly set up the library targets, you won't need to add any of the include directories to myProject manually. First set up the CMakeLists.txt file for math, since it doesn't depend on other projects. I recommend moving headers linking libraries use ...
66,079,949
66,080,075
Calculating Cash On Cash Returning 0 for the result
I am creating a class function where it returns Cash on Cash return which gives you a percentage and is a key indicator to see if you are getting a good ROI. I created the function, but for some reason its not giving me the answer I want which is "3%" or "50%. Cash On Cash return is usually (yearly cash flow / total ca...
yearlyCashFlow and cashInvestment are integers. Dividing two integers results in an integer - even if assigning the result to a double. ala double y = 3 / 5 results in y being assigned zero because 3/5 is an integer expression that gets evaluated as 0 instead of .6.. However 3/5.0 is a floating point expression. So th...
66,080,088
66,080,201
fatal error: 'Eigen/Dense' file not found
I am an Ultra Linux newbie, and I am trying to install this program and when I try to build the python wrapper I'd get this ~/Downloads/DeepMimic-master/DeepMimicCore$ make python clang++ -c -g -std=c++11 -O3 -Wall -fPIC -I./ -I../../libraries/eigen -I../../libraries/bullet3/src -I/usr/include/python3.6m -I/usr/lib/ -...
You're missing a dependency, Eigen, which is listed under 'Dependencies' in the DeepMimic readme. I see this problem has been encountered before: fatal error: Eigen/Dense: No such file or directory
66,080,371
66,080,776
How to write concepts that make use of ADL
I would like to write a concept that would allow me to verify if a given statement, using ADL, is valid and has a proper return type. In my specific case, I want to write a String concept that should enforce the following requirements: The type has begin and end semantics for both its const and non-const flavors: // ...
The idiom using std::X; X(...); is considered a bad idea post-C++20. The standard idiom now is to create a customization point object for X. Or in your case, use the existing customization point object: std::ranges::begin. The way you call such a customization point is by spelling it out in full; internally, it can mak...
66,080,409
66,081,347
Implementing a different method for different types of arguments
I am writing some code to detect collision between different shapes, RectShape,CircShape,LineShape all inheriting from a base class Shape. My current implementation works really badly. First, I defined a bunch of case-specific functions: bool LineLineCollision(LineShape& line1, LineShape& line2) { // do some math }...
A solution would be to use a callback. e.g. #include <iostream> struct Line; struct Circ; struct Shape { virtual void Collision(Line*) = 0; virtual void Collision(Circ*) = 0; virtual void Collision(Shape*) = 0; }; class Line : public Shape { private: void Collision(Line*) override { std::cout...
66,080,468
66,080,511
C++ unordered_set<insert function> return value
I am trying to check return value of unordered_set's insert() function, but stuck with below error: unordered_set<int> t; t.insert(1); t.insert(2); t.insert(3); t.insert(4); std::unordered_set<int>::iterator it = t.insert(1); **//Error** cout<<"size of t="<<t.size()<<endl; Error-->conversion from 'std::pair<std::__det...
Your understanding of the return value of unordered_set::insert is incorrect. Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place. (from cppreference) So the correct declaration is std::pair<std::unorder...