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
62,752,549
62,755,001
'Could not SQLConnect' error when connecting dockerised model and dockerised database
I'm trying to connecting a dockerised c++ application with a dockerised database so that I can get it running and get some outputs, the configuration can be found in this question when I try to run the model (which inside the application container) against the dockerised database: >docker run --net xxxxx-network -it x...
I am assuming that your running each docker container separately. In this case in order for your C++ application container to be able to connect to the Mysql container they will need to be on same network. Create Docker network docker network create mysql-network Run C++ application container like so: docker run -it -...
62,753,085
62,753,169
How can std::vector::clear() be called without an instance if it's not static?
I'm reading this code from OpenVPN3: class OptionList : public std::vector<Option>, public RCCopyable<thread_unsafe_refcount> { void clear() { std::vector<Option>::clear(); map_.clear(); } }; How is it possible that the class method clear calls std::vector<Option>::clear()? std::vector's clear is a metho...
OptionList derives from std::vector<Option>: https://github.com/OpenVPN/openvpn3/blob/f1a32af29cd41b62212829d6713198207ed5315c/openvpn/common/options.hpp#L385 class OptionList : public std::vector<Option>, public RCCopyable<thread_unsafe_refcount> So it's not calling clear() without an instance; it's calling the cle...
62,753,691
62,754,736
Underscore prefix problem in x86: Calling NASM function from C++ function works in x64 but fails in x86
I am using Visual studio 2019 in Windows 10, and I want to compile in x86 using MSVC(platform toolset 142) and NASM(version 2.14.02) the next code: foo.asm section .text global foo foo: mov eax, 123 ret main.cpp extern "C" int foo(void); int main() { int x = foo(); return 0; } But I got the error: ...
The _ prefix is a result of name mangling, which depends on the target platform ABI (OS, bitness, calling convention). According to Microsoft, the _ prefix is used in a 32-bit Windows cdecl calling convention, but not in 64-bit (source): Format of a C decorated name The form of decoration for a C function depends on t...
62,753,743
62,755,032
Clear naming for Signal and Slots in QT
I have difficulty giving clear names for Signals and Slots in one of my class It is an abstraction level for Controller to control Device: CommunicationAdapter It does: sending parameter from Controller to Device (eg. user entering value on UI) request parameter from Device (get initial data) informing about the chang...
I would argue, that a slot should always be named after what it does - not how you trigger it. The same goes for signals, they should be named in past tense, stating what happened. This is the common scheme that Qt uses in all its classes so for consistency it makes sense to do the same. For an adapter class, it might ...
62,753,864
62,754,486
How to declare a QWidget as object of an inherited class on QT Creator?
I have a MyComboBox class, inherited from QComboBox, in order to override the method focusOutEvent: mycombobox.h class MyComboBox : public QComboBox { public: MyComboBox(); protected: void focusOutEvent(QFocusEvent * e) override; }; mycombobox.cpp #include "mycombobox.h" MyComboBox::MyComboBox() { ...
Your instance on UI must have type MyComboBox. It depends on type in object creation procedure. For example if you did something like that: QComboBox* comboBox; // This was declared on UI ui->comboBox = new MyComboBox(); so you can use this instance as MyComboBox with qobject_cast: QComboBox *oMyComboBox = qobject_ca...
62,754,032
62,798,303
Problem creating multiple viewports in Qt3D using C++
I am trying to setup a Qt3DWindow with multiple viewports using C++. According to the documentation and the provided QML example, all I need to do is create a framegraph, where a main QViewport object branches into several RenderViews. The first RenderView contains a QClearBuffers object, and the remaining ones contain...
I still think it's kind of a bug that it draws ontop of the viewports but you can put a QNoDraw node in your framegraph as a child of the QClearBuffers: auto noDraw = new Qt3DRender::QNoDraw(clearBuffers); That solves the rendering issue.
62,754,378
62,754,487
converting/constructing vector of tuples into heap
- Construction i constructed a vector of tuples vector<tuple<int,int,int>> x. For sake of simplicity, lets assume it is constructed it this way. vector<tuple<int,int,int>> x; for (int ii=0; ii < 10; ii++){ for (int jj=0; jj < 10; jj++){ currpeak[0] = ii + rand() % 10; currpeak[1] = jj + rand() % 10;...
The easiest way is to pass a struct with the () operator. For example struct Comp { bool operator()(const tuple<int,int,int>& a, const tuple<int,int,int>& b){ return (get<2>(a) > get<2>(b)); } }; And pass this to make_heap
62,754,624
62,754,748
How exactly iterators are being compared?
#include <iostream> #include <set> using namespace std; int main() { set<int> numbers; numbers.insert(1); auto numbers_find = numbers.find(1); auto numbers_end = numbers.end(); cout<<*numbers_find<<endl; cout<<*numbers_end<<endl; cout<<(numbers_find==numbers_end?"true":"false")<<endl; return 0; } In th...
The end iterator does not point to the last element, it doesn't point to anything. Your program is ill-formed (has undefined behaviour). C++ expresses sequences as half-open intervals
62,754,728
62,756,199
Force CMake to use MSVC with Ninja
I am trying to compile aseprite on 64-bit Windows and using CMake and Ninja to compile it When I am running CMake I see that it is using MINGW64 to make the build files, even though it is mentioned that MinGW is not supported. I tried writing -DCMAKE_IGNORE_PATH=C:\MinGW\bin but it seemed to ignore it, and when running...
I fixed this by changing the environment variable CC to cl set CC=cl
62,754,896
62,757,616
std::iostream with a custom buffer doesn't allow me to write
I create a new struct that inherits std::streambuf, create my own buffer in it, create another struct which inherits std::iostream, use my first struct here, create some useful reading/writing functions here, but writing doesnt work. Writing functions put the buffer in the badbit state. Why so? Here is the full structs...
Thanks to @AlanBirtles; The solution is to call setp along with setg to setup the writing cursor.
62,755,138
62,756,236
Copy Constructors, Assignment Operator C++
I am very new to OOP and am still trying to comprehend all the concepts of the constructors. I have a class with some data and I have to make a Copy Constructor and Assignment Operator, however, since this is the first time I am doing something like this, I am not sure if what I have written makes sense. So, I am askin...
If your instructor insists you must declare special members, but gives no guidance on how, then the best way is: template <class T> class BKS final { public: ~BKS() = default; BKS(const BKS &) = default; BKS& operator=(const BKS &) = default; BKS(BKS &&) = default; BKS& operator=(BKS &&) = default; ...
62,755,660
62,757,072
Template metaprogramming - trying to implement Dimensional Analysis
For a better understanding and learning, I tried to use the boost mp11 library to implement the Dimensional Analysis from "C++ Template Metaprogramming" book (also found in the documentation of boost mpl library). A reason why was that C++11 has features that weren't available when the book was written, features that a...
There are multiple problems with the code. After fixing some, but not all, here is a working version: https://godbolt.org/z/3B9Sc4 Here are some of the modifications: The use of std::integral_constant is unnecessary. You can simply use constexpr ints. This allows simplifying your mp_plus significantly, and: The temp...
62,755,739
62,776,972
Libtorch on Raspberry can't load pt file but working on ubuntu
I'm trying to build a C++ program with libtorch on a Raspberry PI. The program is working on Ubuntu, but I've got the following error at build on Raspberry : error: use of deleted function ‘void torch::jit::script::Module::operator=(const torch::jit::script::Module&)’ In file included from /usr/include/torch/csrc/j...
TLDR : Compile libtorch in 1.6.0 and that works fine. How to compile Libtorch for Raspberry and use in my C++ Project ? Prepare to build Increase RBPi SWAP First of all, if you have a Raspberry PI 3 or lower, you need to increase the SWAP, since the build is a RAM eater. If you have a RBPi 4 or higher with more than 3...
62,755,862
62,756,066
Limits of C++ Vector
i've got a issue with std::vector class, i created a struct struct Triplet{ int first; int second; int third; }; And i created a vector<Triplet> T. My problem is that it won't contain as many elements as i need, even though T.max_size() = 357913941 i got only T.size() = 60540697 or T.size() = 40360465 us...
An std::vector needs a contiguous (=no holes) chunk of memory to exist in. Furthermore, when pushing elements to a vector you can overshoot the internal capacity, meaning that it has to allocate memory for another std::vector (usually double the size) and copy the elements over. Keep in mind that in 32-bit Windows prog...
62,756,093
62,764,838
Generating interrupt each 100 microsecond on windows
i want to generate interrupt every 100 microseconds on windows. Actually i couldnt do this on windows,because windows does not guarantee the interrupts less then 500 microseconds. So, i generate 2 threads. One of them is for timer counter(query performance counter), the other thread is the actual work. When timer count...
To avoid having two threads communicating when you have these short time windows, I'd put both the work and the timer in a loop in one thread. Take a sample of the clock when the thread starts and add 100μs to that each loop. Sleep until the calculated time occurs. Normally, one would use std::this_thread::sleep_until...
62,756,474
62,756,619
how to pass structure to function?
here is what i am trying to do: #include <iostream> void out(box boxx); struct box { char charr; float floatt; }; int main() { box boxx; boxx.charr = 'f'; boxx.floatt = 2.5; out(boxx); } void out(box boxx) { std::cout << boxx.charr << "\n" << boxx.floatt; } I want to make a function that...
Move function declaration to after struct. #include <iostream> struct box { char charr; float floatt; }; void out(box boxx); int main() { box boxx; boxx.charr = 'f'; boxx.floatt = 2.5; out(boxx); } void out(box boxx) { std::cout << boxx.charr << "\n" << boxx.floatt; }
62,756,475
62,758,412
c++ vector of function with template arguments
#include<iostream> #include<functional> #include <unordered_set> #include <vector> #include <unordered_map> #include <variant> class Button { public: Button(int _val):val(_val){} ~Button(); int val; template<typename F, typename...InArgs> void addListener(std::function<F(InArgs...)>(f), InA...
You have a member variable template listener, which means that you have one vector for each function type. The compiler can't infer which one you mean. You're also trying to push_back the result of calling the function, rather than the function itself, and you're not storing the arguments. You can't do this the way you...
62,756,545
62,757,544
Getting Device from ID3D11DeviceChild::GetDevice() method
I'm trying to return the ID3D11Device object in my application using this method: https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicechild-getdevice More specifically I'm using a returned Vertex Buffer to try and get the device like below: pContext->IAGetVertexBuffers(0, 1, &veBuffer, &Strid...
ID3D11Device *device = nullptr; veBuffer->GetDevice(&device); // Call device method device->Release(); Notes: You should be passing the device pointer around to code that might want to create resources, or creating a singleton to your device abstraction so you can call it from anywhere, rather than using hacks lik...
62,756,632
62,756,717
I create a tmp struct in a while loop,but some error happen,it looks like the tmp struct not be free at one loop end
I create a tmp struct in a while loop,but some error happen,it looks like the tmp struct not be free at one loop end,but when I create a struct pointer,it works. class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { struct ListNode node; ListNode* head= &node; ListNode* h=head; int...
I think this may because you are creating tmp on the stack inside the while loop, then assigning it's address to h->next. As soon as the while loop iteration ends, tmp is no longer in scope, but you have stored a reference to it inside h. You need to create tmp on the heap for this to work, as you have discovered by ...
62,756,734
62,757,087
glad causes glfwSwapBuffers to return error message
Code #include <glad.h> #include <glad.c> #include <GLFW/glfw3.h> int main() { glfwInit(); GLFWwindow* window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); } return 0; } Background information My Operat...
The behavior is totally correct. So what GLAD does is having a #define glFoo glad_glFoo for every GL function Foo in the <glad.h>, with glad_glFoo being a function pointer to the appropriate type. A;ll of these function pointers are initialized to NULL. So when you call glClear(GL_COLOR_BUFFER_BIT) you actually call gl...
62,756,886
62,757,164
constructing vector of tuples into heap
From here, i am able to convert a vector of tuples into a heap. However i want to go further back to construct tuples from scratch, eliminating the need to convert the vector. How i previously constructed the vector is as follows: vector<tuple<int,int,int>> x; for (int ii=0; ii < 10; ii++){ for (int jj=0; jj < 10; ...
You are using x as both the name of your heap and of your tuple. Plus operator[] isn't the way to access fields of a tuple. Plus you are trying to create the heap multiple times I guess you meant something like this for (int ii=0; ii < 10; ii++){ for (int jj=0; jj < 10; jj++){ tuple<int,int,int> y; ...
62,757,360
62,758,271
Usage of STL algorithm functions on more then one dimensional containers
I have a simple struct struct Point { Point(int x, int y) : x(x) , y(y) {} int x, y; }; And a two dimersional vector(it also can be a three dimensional vector or more) std::vector<std::vector<Point>> v(10, std::vector<Point>(10, Point(3, 4))); And I want to know the summary of all x v...
If you consider the STL as it stands now, then a nested range-for loop is probably the most readable (though it's still subjective). However, I am very much an advocate of not using range-for loops, unless you need a transform or a for_each. If the code is doing an accumulate, then you should write an accumulate. Here'...
62,757,700
62,757,832
Why does std::span lack cbegin and cend methods?
Why does std::span only have begin and end methods and not their constant iterator counterparts cbegin and cend? (standard) What I noticed too is that the proposals for span that I could find do have a definition for cbegin and cend: P0122R7. Why was it removed?
As an update, these are added back by P2278R4. The LWG issue pointed out below is still a problem, x.cbegin() and std::cbegin(x) would do different things, but now x.cbegin() and std::ranges::cbegin(x) do the same thing. This was removed as a result of LWG3320. The issue is that x.cbegin() should really do the same th...
62,757,803
62,757,885
Check if some type is instantion of template class std::optional
These are template constexpr bools to check if some type is instantiation of std::optional template<typename> constexpr bool is_optional = false; template<typename T> constexpr bool is_optional<std::optional<T>> = true; template<typename T> constexpr bool is_optional<std::optional<T>&> = true; // avoid this static_a...
In c++20, you can use std::remove_cv_ref_t, and a bit of indirection to do this easily: template<typename> constexpr bool is_optional_impl = false; template<typename T> constexpr bool is_optional_impl<std::optional<T>> = true; template<typename T> constexpr bool is_optional = is_optional_impl<std::remove_cvref_t<T>...
62,757,852
62,758,026
how read char array(with some space) from file in c++
I am trying to create a maze map in txt file here is the .txt file 7 7 e% %% %% %% %%% %%% %%% % % % % x % %% 7 and 7 are the number of rows and columns respectively. The spaces are the contents of the array too/ how can I print the spaces in c++ I have tried to code for it but it doesn't work with sp...
map >> arr[i][j]; is a formatted input. It skips whitespaces. You have to use a different method, e.g. std::basic_istream<CharT,Traits>::get or std::basic_istream<CharT,Traits>::getline Here is an example with get() #include <iostream> #include <fstream> #include <vector> using namespace std; int main() { ifstream...
62,758,132
62,759,251
How to read XML element using tinyxml2 in C++?
I am trying to read config.xml with following simple content: <?xml version="1.0" encoding="utf-8"?> <config> <languages> <language>cs</language> <language>en</language> </languages> <databases> <database> <domain>localhost</domain> <server>localhost</server> ...
Did you make tinyxml2::XMLDocument* config; a pointer? Because you write config->LoadFile("config.xml");. Try with an easier definition of config like so: tinyxml2::XMLDocument config; config.LoadFile("config.xml"); Can't say for sure what is wrong if no error message is present, but you're missing the std:: before en...
62,758,272
62,758,381
Function to randomly convert chars toupper case
Am revisiting an exercise from an online course where we created a 'Whale translator' which checks through each character that the user inputs and extracts / returns only the vowels. I thought it would be fun to have the returned values capitalized at random so the whole thing would feel a little like Dory speaking wha...
You converter function is returning the modified char but you never use the returned value in the for loop: converter(whale_talk[k]); You need to do: whale_talk[k] = converter(whale_talk[k]); Here's a demo. Alternatively, you can leave the call site as it is, but pass the char to be converted by reference, like this:...
62,758,277
62,758,760
Password login program loops forever and displays incorrect results
I'm trying to create a password login program in C++. So there is some mistake in looping. If the entered password satisfied all the conditions means it had to come out of loop but it doesn't end. So if anyone know means explain me properly. I just have started to learn programming. Look at the output first. It is show...
There are several defects in your code: The while(true) is a non-terminating loops, but no break is added. The alp and num weren't reset at the end of the loop iteration. Since the alp and num weren't reset, they're incremented in each iteration. A few notes on the code: You don't need to include string.h or ctyp...
62,758,453
62,799,027
Shared lock with two exclusive lock groups
I have two methods "log" and "measure" that should never execute at the same time. So I tried to use a "std::mutex" to do this as follows: void log(std::string message) { mtx.lock(); someLogFunctionality(); mtx.unlock(); } void measure() { mtx.lock(); someMeasureFunctionality(); mtx.unl...
Based on the reply from alexb I have written the following mutex class which currently works for me (only tried out in a simple multithreaded example application so far) Please note that it is not protected against "starvation". In simple words: It is not ensured that that lockMeasure will ever get the lock if lockLogg...
62,758,570
62,766,053
How to resize a std::vector of Eigen::MatrixXd
I need use a vector of Eigen matrices in my program. The size of the vector is known. However the matrix size corresponding to each member of the vector can have different size and need to be dynamically allocated. Based on https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html I guess I can declare my matrix a...
Why are you having this error ? Let's look at your code : std::vector<Eigen::MatrixXd> inv_K_mat2(A,B); You're trying to construct a std::vector of things (in this case, dynamically-sized Eigen matrices). But there is no constructor to std::vector that takes two integers as arguments. There's some versions of the con...
62,758,595
62,760,292
How to remove the vector object from the map
I have a map std::map<int, std::vector<Data>>myMap and my structure is defined as follows. struct Data { int x; int z; int y; }; in myMap key is int and value is vector of structure I'm given with x and key value. I want remove the object from the vector where the key...
Thanks for the time. I have tried with the following code and it worked for me. for ( itr = myMap[key].begin(); itr != myMap[key].end(); ++itr) { if (itr->x == 1) { myMap[key].erase(itr); break; } }
62,759,122
62,769,393
Calculate normalized coordinates for SendInput() in a multi-monitor environment
I want to send mouse input programmatically to anyone of my connected displays. I know I can use the SendInput function to do this, but my current approach doesn't work on a multi-display setup. I am using the following approach: Get pixel coordinates of the point to click, relative to the current screen; Get pixel co...
Get the pixel coordinates relative to the whole virtual screen: to do this, we sum the coordinates of the current screen margin (topleft pixel) with the coordinates of the point to click; It looks like you are using the coordinates(X,Y) relative to the monitor. How did you get the coordinates? If so, then the sampl...
62,759,628
62,760,585
Script to transform C++ code to webassembly is not terminating
I want to compile a CPP file to web assembly. I am using scripts in the following link https://github.com/wasdk/wasmexplorer-service/tree/master/scripts I am using the following command in my Linux OS ../scripts/compile2.sh ../test.cpp "-fno-verbose-asm -03 -std=c++98" 2>&1 The command never terminates. I have tried al...
running the following code works for me /* # run me with 'bash test.cpp' clang++ $0 --target=wasm32-unknown-unknown-wasm -nostartfiles -nostdlib -Wl,--no-entry -Wl,--export-all -o test.wasm exit 1 */ extern "C" double fact(int i) { long long n = 1; for (;i > 0; i--) { n *= i; } return (double)n; } testi...
62,759,640
62,780,979
Runtime mapping of values to types
I have no hope that what I'd like to achieve is possible in C++, but maybe I'm wrong since my previous question about bidirectional static mapping got an unlikely answer. I have a set of certain types, an enumeration with keys representing the types, and a template handle type that accepts mentioned types as template p...
std::visit is your friend here. Convert types to a certain std::variant/replace it with an alias to that type: // or std::type_identity template<typename T> struct proxy { using type = T }; template<typename T> constexpr inline proxy<T> proxy_v{}; using var_types = std::variant<proxy<foo>, proxy<bar>>; var_types mk_var...
62,760,079
62,760,178
Converting sharet_ptr<Derived> to shared_ptr<Base>
I have a class A: public std::enable_shared_from_this<A>{....} class B: public A{....} later in code, I'm doing this: std::shared_ptr<A> Construct(....){ class_field=std::make_shared<B>(...); return class_field->shared_from_this(); } With this code, I want to make sure that the object of B gets destroye...
Purpose of shared_from_this is to have access to shared pointer from class itself. You should not use this outside of class, so as a result your code in question is simply an overkill. it should be: std::shared_ptr<A> Construct(....){ return std::make_shared<B>(...); }
62,760,871
62,760,920
Exception thrown while trying to use smart pointers
A moments ago, I was exercising with design patterns, and recently, I've tried to implement a Factory Method pattern. My friend told me that I should always use smart pointers, so I've tried it, but my compiler throws an exception called "Access Violation". What am I doing wrong? There is one interface called "Shape", ...
The return statements like return std::shared_ptr<Circle>(); just returns an empty std::shared_ptr, which contains nothing. Dereference on it like shape->printShape(); leads to UB. You should construct an object and make it managed by std::shared_ptr. E.g. std::shared_ptr<Shape> Shape::Create(int num) { switch (num...
62,761,204
62,761,344
Passing a member function pointer as an argument to a template method
I am trying to write a templated method that will accept a member function pointer as an argument. Here is an example class, including my latest attempt to write said template method: class MyClass { public: int myMethod() { return 1; } template<typename T> T call(std::function<T(MyClass*)> m) { ret...
Apparently it cannot deduce T (template parameter from a very deduced ctor argument). If your goal is to simply do it in one call you can change method definition to something like template<class F> auto call(F &&f) { return std::invoke(std::forward<F>(f), this); }
62,761,320
62,761,365
Separating String Into three Separate Doubles
I have a string of a line I read from a file. String:("2021.2 12341.29 42.1"). I need to extract each of the three numbers into a double for each value which is shown by each space to insinuate a new number is there. The numbers will not always have the same spacing because I am doing this for multiple lines so I cant ...
Use std::istringstream: #include <sstream> #include <string> #include <iostream> int main() { std::string vert = "2021.2 12341.29 42.1"; double num1, num2, num3; std::istringstream strm(vert); strm >> num1 >> num2 >> num3; }
62,761,866
62,765,108
I'm developing a server and ip passed as parameter not working
I'm using: struct in_addr ip; #define HOST_PORT atoi(argv[2]) #define HOST_IP inet_aton(argv[1], &ip) sockaddr_in sockaddr; sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = htonl(HOST_IP); sockaddr.sin_port = htons(HOST_PORT); To get the ip and port numbers in cli. Th...
You are misusing inet_aton(). You are assigning the return value of inet_aton() to your sockaddr variable, rather than assigning the in_addr struct that inet_aton() outputs. The return value is NOT an IP address! inet_aton() returns a non-zero value on success, and 0 on failure. In other words, its return value is ba...
62,761,969
62,780,778
Detach a static const std::thread?
Is this illegal? How do I hide this global thread instance with private? It seems to work without const but I would still like to const it just for peace of mind. struct AbstractImage { private: static void LoadImages(); static const std::thread ImageLoader; }; ... const std::thread AbstractImage::ImageLoader( ...
You can't call detach() on a const std::thread object, since detach() needs to modify the state of the std::thread. In this case, I would suggest not using a static std::thread object at all. Especially since it is a one-time-use thread, so the std::thread object doesn't need to hang around once the thread starts runn...
62,761,997
62,762,497
What is the best way to boilerplate the "cold/never_inline" error handling technique in C++?
In this article, a technique is described to move error code out-of-line in gcc to help optimise the hot path for size as much as possible. An example of this would be: #define unlikely(x) __builtin_expect (!!(x), 0) bool testForTerriblyUnlikelyEdgeCase() { //test for error condition here } void example() { if ...
There are two approaches that come to mind: A function-wrapper approach, and A macro-based approach Function Wrapper The nicest in terms of design would be to wrap this functionality into a function that encapsulates the attributes and handling. To do this, you pass a callback that you want invoked as the cold handle...
62,762,126
62,764,004
how do I calculate cutoff frequency from sampling rate and single pole lowpass filter alpha coefficient?
I've been using some code which implements a low pass filter on audio signal data sampled every 100 microseconds (EDIT: i originally mistakenly typed nano) (aka 10Khz) and then subtracts that lowpassed data from the original signal to yield a highpassed signal. If I'm not mistaken, this code is an implementation of the...
In the article, the code for the filter is y += alpha * (x - y), so you are using an alpha of 1.0/64.0 = 0.015625. In the article, the equation for alpha is alpha = 1 - exp(-deltaT/tau) or, approximately, alpha ~= deltaT/tau when deltaT is small compared to tau. Solving for tau gives tau = -deltaT/log(1 - alpha) or, a...
62,763,245
62,763,451
How to make base class's operators visible with variadic number of base classes (please see code below)?
What is the best way to expose operators from base class like the following code is trying to do. I suppose with one or two base classes we'd use using syntax, but with a variadic number of base classes, is something like using Base<Ts>::operator=...; possible? template <typename T, typename Derived> class varU { p...
I'm not exactly sure, what you want to achieve with your code, so perhaps you want to go a bit more into detail in your question. But regarding your question in the code-comment, the answer is yes, it's possible in C++17. If you actually want to use your operators, you also have to declare the varU class a friend of va...
62,763,585
62,833,170
gtkmm display file contents
I am quite new to gtkmm please be soft, I need to read a file contents and display it. I have referred to this tut https://developer.gnome.org/gtkmm-tutorial/stable/sec-buildapp-opening-files.html.en, but not sure how to tailor these example to my scenario, I am reading Gtk::TextView, GtkWidget. Can someone point to an...
Have a look at this, it's in PHP but understandable https://www.kksou.com/php-gtk2/sample-codes/read-a-text-file-into-GtkTextView.php
62,764,275
62,764,653
Non-type pointer and reference template parameters and how/why they are resolved at compile time. c++
I ask simply why is it allowed to pass the memory location of an object/primitive through a non-type template when I would traditionally expect memory to be allocated and used at runtime. I am aware that the variable whose memory is passed must have external linkage but given that, does that mean the memory locations f...
This sort of thing is taken care of by fix-ups performed by the runtime loader, the address will indeed vary at runtime, but the location where the address will be found is always at fixed locations with regard to the loaded executable image. For example the ELF image format (which is very common on *nix these days( ha...
62,764,552
62,767,330
Variable not defined error, when trying to call a variable defined in a .h file
Already linked all my files to "Pusi.h" declared variables here "Pusi.h" private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { int strength = 0; int dexterity = 0; int money = 0; int smarts = 0; int magic = 0; int health = 0; int Belligerent = 0; std::string Politics; strength -= 2; m...
In your header file you want to define prototypes only not the entire function. And then in your cpp file you want to do: #include .../all other libraries go here #include "header.h"/Your header file class_name::prototype{ //do stuff } And than you want to create a tester file like so: int main(){ classname variab...
62,765,194
62,767,499
Drawing Clockwise Triangles Reordering Points
I was making a ray tracer in c++ and was coming across an issue when I downloaded objects because it would only render some of the triangles because they were drawn counter-clockwise. I looked up this being an issue since it would be back facing. But Im confused on how you are actually supposed to know just by the vert...
You can calculate the signed area formed by the triangle defined by the three points - this is equivalent to the 2D 'cross product' of the vectors representing the edges (sometimes called perp product): Here is a naive implementation in python that shows the calculation; you can transcribe it to C++ at your leisure. Fr...
62,765,311
62,765,404
Can you check why removing an Item from a linked list is not working in this code?
I've been asked by a friend to help him with an exercise, basically the idea is like below. Car number = fr50000 Car owner = AlexNelson Parking time = 3.5 hours. He was told not to use stuff like string or getline, so it's simple app just to learn the idea of working with linked lists. So I made this prog...
Your remove() function is not actually removing (or destroying) a node from the list. You need to update the link of the previous node in the list to point to the next node in the list. And you need to update the head too, if removing the 1st node in the list. Try this instead: void remove() { if (isempty()) ...
62,765,630
62,765,649
How to use c++20 modules with GCC?
I'm currently trying the new C++20's feature called modules as described here using GCC 10.1.0, however if i try to build the following snippet of code the compiler throw me a bunch of errors. This is the snippets i wrote so far: // helloworld.cpp export module helloworld; // module declaration import <iostream>; ...
GCC's language status page says it doesn't support modules yet. C++20 support is not complete (which is fair enough given that we're in 2020! And C++20 technically doesn't exist yet…). However, with some flags and a development branch you can play around with the in-progress implementation — read more about it on GCC's...
62,765,714
62,765,742
Is it safe to reinterpret_cast between a Type and a Wrapper<Type>?
Suppose we have class template Wrapper like this: template <class T> struct Wrapper { T wrapped; }; For what types is it safe to reinterpret_cast between a Type and a Wrapper<Type>? None? Standard-layout? All? Suppose we created an object of one of these (Type and Wrapper<Type>), and read and write this object through...
Reinterpreting T (that's not a member of Wrapper<T>) as Wrapper<T> is never allowed (the F1 example). On the other hand, I believe reinterpreting Wrapper<T> as T is allowed for standard-layout classes: (the F2 example) [basic.compound]/4.3 Two objects a and b are pointer-interconvertible if: — one is a standard-layout...
62,765,811
62,765,826
the characters in a c++ string are being ignored
I'm trying to write to a hid device using signal11's hidapi (here). In my troubleshooting, I've noticed that part of a string isn't being displayed to the console. Here is a sample of my code //device is a hid device and is assigned to in another part of the program. //dataBuffer is a struct with only a char array call...
This line: std::cout << "Write success: " + '\n'; will print the string "Write success: " with an offset of 10 characters, which is the ascii value of \n. Hence you see ess on the screen. You probably want: std::cout << "Write success: " << res << "\n"; assuming res returns 0 or -1 as needed.
62,765,947
62,766,665
Problem: Shortest path in a grid between multiple point with a constraint
Problem description: I'm trying to solve a problem on the internet and I wasn't able to pass all testcases, well, because my logic is flawed and incorrect. The flaw: I assumed starting to the closest 'F' point will get me to the shortest paths always, at all cases. Thinks I thought of: Turning this into a graph probl...
You can write a DP solution where you have a 4x4x8 grid. The first two axis represent the x and y coordinate. The third one represent the binary encoding of which food item you picked already. Each cell in the grid stores the best number of moves to get at this cell having eaten the specified foods. So for example, gri...
62,766,043
62,766,076
converting decimal to string and string to decimal using char type
My code is not giving me exact values. Can somebody tell me what's wrong? A few values give me the correct answer, but try 78, 79, 80 etc and you will know. If you could somehow correct it, that would be great. //hi // Example program #include <iostream> #include <string> using namespace std; int stringToDecimal(strin...
In this line: digit = (c + (10 ^ i) )+ digit; the ^ operator is not the exponentiation operator, it's the bitwise xor operator. You will need to use std::pow for this: digit = (c + std::pow(10, i) )+ digit; You have to do the similar thing in the other function as well. Instead of the pow function, you could also hol...
62,766,230
62,766,422
Undeclared identifier compiling diablo 2 program "muleview"
I get 4 undeclared identifier errors when compiling (Visual Studio 2013) and cannot figure out where and how to declare them. error C2065: 'IDR_MAINWND' : undeclared identifier error C2065: 'ID_FILE_EXIT' : undeclared identifier error C2065: 'ID_TOOLS_OPTIONS' : undeclared identifier error C2065: 'ID_HELP_ABOUT' : u...
I found there is another resource.h in res folder, so please modify mainwnd.cpp: #include "resource.h" -> #include "../res/resource.h"
62,766,515
62,767,058
putting non trivial items in a multiset
I have this class (I am making a task scheduler). This represents the items that are queued up. class QueueItem { friend class TimerQueue; std::chrono::system_clock::time_point when_; std::packaged_task<void(void)> what_; std::string name_; public: bool operator<(const QueueItem& other) { ...
Why can't you implement a comparison operator on a shared_ptr? (untested code) struct Compare { bool operator ()(const QueueItemP &lhs, const QueueItemP &rhs) const { return *lhs < *rhs; } }; std::multiset<QueueItemP, Compare> m;
62,766,813
62,766,867
How to initialize a class with a const pointer on a data object
I have problems with initializing a class instance of the following type: Object::Object(const double &a, const double &b, bool c, const uint8_t *data) I try it in the following way: a = 50; b = 40; c = false; data_ = std::make_unique<uint8_t[]>(a*b); Object a = Object(a, b, c, data); and I get this error message: no...
You are trying to pass a std::unique_ptr object where a raw const uint8_t* is expected. That will not work, as unique_ptr is not implicitly convertible to a pointer. However, you can use the unique_ptr::get() method to access the pointer it is holding. On a sidenote, you have 2 different variables with the same a nam...
62,766,860
62,778,756
How do I create a "hole" in my Qt window?
I would like to create a "hole" in my QMainWindow. Suppose the black rectangle is the "hole" of a QMainWindow. Inside the rectangle should be anything behind the QMainWindow. For example, if the QMainWindow is opened on top of my desktop, then inside the rectangle should be part of my desktop background image. Is there...
You should use QWidget::setMask or QWindow::setMask. There is a Qt Example for that: https://doc.qt.io/qt-5/qtwidgets-widgets-shapedclock-example.html
62,767,245
62,844,383
Does TMap::Emplace() overwrite when existing key is applied?
I read Map for STL does not allow to overwrite value of existing key by emplace() or insert() However, it LOOKS like Emplace() of UE4 TMap allows to overwrite when existing key with different value is applied. Am I understanding correctly, or overwriting should not be happened in TMap, too?
Keep in mind that Unreal Engine's TMap is not equivalent to C++'s map. You've already figured it out, but the Emplace method in the TMap class does differ from C++'s emplace method in the map class in that calling Emplace with a key that already exists in the map will replace the original value associated with that key...
62,767,544
62,799,340
Why do gcc and clang generate different symbol names for an instantiation of a function template?
Consider the following example: struct A { using type = int; }; template <typename T> using B = A; template <typename T> typename B<T>::type f() { return {}; } template B<int>::type f<int>(); Clang generates symbol named int f<int>() while GCC generates B::type f<int>() for the instantiation: https://godbolt.org/...
This is a known C++ CWG (Core Working Group) issue: https://wg21.cmeerw.net/cwg/issue2037, quoting Richard Smith: On the one hand, the alias template can introduce SFINAE conditions, so it should be instantiation-dependent and mangled. On the other hand, the language rules permit this template to be redeclared using t...
62,767,600
62,768,238
Printing all elements in array of Vector
int n=1000000; vector <int> divisors[1000001]; void solve() { for(int i=1; i<=n; i++) for(int j=i; j<=n; j+=i) divisors[j].push_back(i); } Now, I want to print all the elements of the divisors. How can I do this?
You need two loops to iterate first through the array of vectors, then through each vector. C++ has improved a lot over the years so there's now simple ways to do this: #include <vector> #include <iostream> constexpr int n=1000000; std::vector<int> divisors[n+1]; void solve() { for(int i=1; i<=n; i++) for...
62,767,720
62,768,124
Is there a way to prompt user what data type to use as template c++
I'm making a simple doubly-linked list with dynamic memory and templates, it is suposed to recive user input to generate it. Now I want to prompt the user if the list is made of ints, floats, double or chars. Is that posible? template <class T> class le { nodo<T>* head = nullptr; bool (*comp)(T, T); public: ...
The most straightforward way to deal with this would be to use the adapter pattern where the adapters all inherit from an "interface" type (pure virtual methods only). To do this, you need to know what adapted operations you need to perform on each list. For example, given the single operation "add an item to the list...
62,768,255
62,768,446
Undefined opnMP function when calling a openMP shared library from python
I want to write a small c++ - code with openMP, compile it to .so and call it from python using. The c++ source is - from ctypes import * import ctypes c_lib = cdll.LoadLibrary("libtest.so") c_lib.openmp_test() and the cpp file is as follows - #include<iostream> #include<omp.h> void openmp_test() { std::cout<<"in...
You should add the library omp into library dependency of program. g++ test.o -shared -lomp -o libtest.so
62,768,443
62,768,569
Insertion Overload with String to Object
New to C++ here. I have project that I am working on that is asking me to overload the insertion operator like this: someObject << “stringOne” << “stringTwo” << stringThree <<; The idea of this line of code is essentially adding some strings to an array that ‘someObject ’ holds. I am aware that the prototype for inse...
You can just make operator<< a member function to get the syntax you want: someClass& operator<<(std::string str) { // add the string to this return *this; } and you can do: someObject << "hello" << "world"; You can add additional overloads for any other types you want on the right hand side. Here's a demo.
62,768,521
62,769,125
G++ command throws "expected '(' for function-style cast or type construction"
Function foo takes a vector of strings. It's defined as bool foo(vector<string>& input); When I call foo with: foo(vector<string>{"abc"}); my compiler gives the following error: error: expected '(' for function-style cast or type construction and points to { as the start of the error. This compiles fine in Xcode but...
Your command line specifies that the output file ("-o") should be called "-std=c++17" – it does not say anything about the language version, so you're compiling as C++03. Remove the "-o" or add an actual file name. Also, note that your "g++" is an alias for clang.
62,769,199
62,769,503
Idomatic QT architecture for simple forms?
I am currently working on a medium-sized project that will need to utilize many form-like dialogs. I am developing this application using Qt5 widgets. (I am trying to implement a debugging tool for a class-based network protocol). Most of the logic behind the forms is very simple. The view for a form would look like th...
I don't want my dialog to be directly responsible for inserting the data into the send stream Exactly. And it should only be responsible for passing the data on to some service which is responsible for sending the message i.e., Separation of concern and single responsibility. Most tutorials like this seem to want th...
62,769,483
62,781,467
Libreoffice API (UNO): need to change user's xTextField text
Is there any proper way to change text in the user's created xTextField using C++ UNO? These fields names are com.sun.star.text.fieldmaster.User.[FIELD NAME] I tried this before, but it didn't help: Libreoffice API (UNO) : text and data from xTextField Also I've tried something like this but still didn't help: // curre...
Did you read section 5.18 of Andrew's Macro Document as recommended in my other answer? Here is Listing 5.49 translated into C++. It seems there is a bug in that listing because I had to add "." to make it work. OUString sName = OUString::createFromAscii("Author Name"); OUString sServ = OUString::createFromAscii("com.s...
62,769,590
62,769,832
Translation from binary into decimal numbers in C++
I tried to build a function that calculates a binary number stored in a string into a decimal number stored in a long long. I'm thinking that my code should work but it doesn't. In this example for the binary number 101110111 the decimal number is 375. But my output is completely confusing. Here is my code: #include <s...
'1' != 1 as mentioned in the comments by @churill. '1' == 49. If you are on linux type man ascii in terminal to get the ascii table. Try this, it is the same code. I just used the stringNumber directly instead of using const char* to it. And I subtracted '0' from the current index. '0' == 48, so if you subtract it, you...
62,769,697
62,769,778
C++ GetProcessTimes() does not change value over time
I'm writing a C++ function for get CPU usage of specific process in Windows. Many reference (like this) suggest using function GetProcessTimes for implementation. However, I tried with a sample program but the value of KernelTime and UserTime is not changed over times.Below is my code: #include <iostream> #include <Wi...
You're querying the time of the current process (GetCurrentProcess()), not the target process (processHandle). Since GetProcessTimes() returns the CPU time consumed by the process, but your process isn't consuming much time as it is mostly sleeping, the result changes very slowly. So, pass processHandle instead of GetC...
62,770,060
62,770,481
setting compiler/linker flags per target in CMake
I have created the following CMakelists.txt for my project which includes some files which need to be compiled with C and then will be linked with my C++ binary. I'm also using libasan. cmake_minimum_required(VERSION 3.0) SET(GCC_COVERAGE_COMPILE_FLAGS "-g3 -fsanitize=address -fno-omit-frame-pointer") SET(GCC_COVERAGE...
Ok, so after browsing through different answers here I've made the CMakelists.txt given below and it works in this case. cmake_minimum_required(VERSION 3.0) project(ABC_PROXY VERSION 1.0.0 LANGUAGES C CXX) add_executable(abc_proxy_with_asan src/file1.c src/main.cpp ) set_target_properties(abc_proxy_with_asan PROPERT...
62,770,230
62,772,467
std::strftime displays timezone UTC as UTC+1 using gmtime in windows
I am trying to understand why in windows (in linux works) std::strftime displays the timezone UTC as UTC+1. If I run the next code #include <ctime> #include <chrono> #include <string> #include <iostream> int main() { std::time_t t = std::time(nullptr); char utc_str[80]; std::strftime(utc_str, 80, "%H:...
Microsoft has been always famous for its implementations of C library functions to work somewhat differently than specified in standards. Other platform vendor doing that is Apple. As it has lasted for decades it must be is deliberate strategy. There are bugs reported about that time zone in Visual Studio implementatio...
62,770,234
62,770,396
Template class with conditional typenames
I would like to have a template class (e.g. float/double type), but I am using Nvidia CUDA and OptiX and have multiple other types (e.g. float2, double2, float3,...) that depend on the chosen template type. Something like this: #include <optixu/optixu_vector_types.h> #include <type_traits> template <class T> class MyC...
Typically you'd do this by creating a trait type whose specializations define the additional types. For example: // Base template is undefined. template <typename T> struct optix_traits; template <> struct optix_traits<float> { using dim2 = optix::float2; // etc }; template <> struct optix_traits<double> { ...
62,770,320
62,770,515
Does Asio's write_some really return immediately?
According to https://www.boost.org/doc/libs/1_73_0/doc/html/boost_asio/reference/basic_stream_socket/write_some/overload1.html, The function call (write_some) will block until one or more bytes of the data has been written successfully, or until an error occurs. Here's the function: template< typename ConstBuffer...
basic_stream_socket::write_some is equivalent of Berkley socket send()( or write()) function. Normally send() blocks until all bytes has been sent. But in rare cases, it can be interrupted by SIGNAL handler or timeout SO_SNDTIMEO at the moment when only part of the data has been transmitted. In this case, send returns ...
62,770,533
62,770,673
In C++17 should this code be producing warnings?
As seen on this godbolt link clang in c++14 mode(but not in c++17) and GCC in c++17 mode produce warnings about sequencing. I assumed that in C++17 all stuff on the rhs of = is evaluated before lhs so I am not sure if the gcc warning is correct. Code is: static int index =0; void f(int* pindex){ pindex[index] ...
This code could produce warnings before C++17 where it was undefined behavior, but should not with C++17 or later as the behavior became defined: In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value c...
62,770,643
62,771,191
Why is std::to_string() not templated?
As stated here std::string is not a template function but rather the standard choose to use function overloading to provide this function for different types. My question is why use overloading when template/specialisation seems to make more sense to me in this case? Consider that if the standard has defined something ...
why C++ decided to disallow people to implement std::to_string for their own type This is where ADL is useful. We already have the example of how to correctly do this with std::swap, which is successfully done in many codebases already: template <typename T> void swap_example(T & a, T & b) { using std::swap; ...
62,770,802
62,770,875
Why is only derived class member function called?
In the following code: Please tell me why only derived class member function is called, is it because of hiding? And why an error doesn't occur in b.func(1.1);, the parameter is int x. #include <bits/stdc++.h> using namespace std; class A { public: virtual int func(float x) { cout << "A"; } }; cl...
Yes it's because of hiding. This is one of the main reasons you should always add the special identifier override on functions you intend to override: class B : public A { public: virtual int func(int x) override // <- Note the override here { cout << "B"; } }; This will cause the compiler to comp...
62,771,341
62,771,745
c++ identifier "Luservar" is undefined
I am writing a little app that uses SMTP. And I got a weird error: identifier "Luservar" is undefined` code: o_smtp->BodyText = _T(uservar->get_h().c_str() + ":" + pass_str.c_str() + "\n" + get_mac().c_str()); Why is it saying Luservar if i say uservar? I have tried: o_smtp->BodyText = uservar->get_h().c_str() + ":" ...
DO NOT USE _T or TEXT(). Yegods. These are positively ancient and obsolete macros that Microsoft absolutely needs to remove from Windows.h (and they should have removed them decades ago). Even Raymond Chen, everyone's favourite Win32-centric blogger, doesn't know why _T exists! Just make sure #define UNICODE is en...
62,772,097
64,909,114
ISearchJob->Release() stucking
I'm using wuapi to find Windows Updates. I faced with the problem: pJob->Release(); stucking in the following code on some machines, but generally it works correct. What could be the reason of such behavior? I have tried to change ISearchJob* to CComPtr and remove pJob->Release();, but issue isn't gone. In this case pr...
As @JonathanPotter suggested in comments, using pJob->CleanUp() instead of pJob->Release() was resolved the issue.
62,772,590
62,772,654
Is this correct usage of static when auto deletion is expected in C++?
The code snippet is from Wikipedia. void WriteToFile(const std::string& message) { // |mutex| is to protect access to |file| (which is shared across threads). static std::mutex mutex; // Lock |mutex| before accessing |file|. std::lock_guard<std::mutex> lock(mutex); // Try to open file. std::ofstream file(...
it should exist until the whole program exit, right? yes So why would the mutex destructor be called when leaving the scope? mutex destructor will not be called. lock guard destructor will be called and it will unlock the mutex. from cppreference When a lock_guard object is created, it attempts to take ownership ...
62,773,562
62,775,097
Changing FOV(Field of view) while moving forward
I have situation. I want smoothly change FOV while moving forward. in Camera settings in parent class I set default value: FollowCamera->FieldOfView = 90.0f; Then in MoveForward function I set it like this void AStarMotoVehicle::MoveForward(float Axis) { if ((Controller != NULL) && (Axis != 0.0f) && (bDead != true...
FInterpTo will make this for you : https://docs.unrealengine.com/en-US/API/Runtime/Core/Math/FMath/FInterpTo/index.html Each times the "MoveForward" will be called, the fov will be increased until 140. To slow/speed the transition, decrease/increase the InterpSpeed value With your code : void AStarMotoVehicle::MoveForw...
62,773,935
62,774,651
Why C++ uses pointer for next node in linked list, but langauges like C# or Java use just the name of the class Node?
Most of the linked list implementations in C++ are like this, a pointer reference will be used as the type for the "next" node class Node { public: int data; Node* next; } But for languages like C#, Java and Python, why pointer is is not directly used? I could see only this kind of implementation: // C# class ...
After reading the posted answers and other stackoverflow stuffs related to references and pointers like this one C++ references Vs C# references This is what Makes more sense to me, C# References are Managed references. But in C++ there is no such manged environment hence we need to allocate and carefully de-allocate ...
62,774,413
62,774,984
Why it is printing only 1st value of doubly linked list and than my program is crashing
I am trying to create a doubly linked list and then printing its value but the output is showing only first value and then the whole program is crashing. I can't understand where is the problem in the code . Input 3 1 2 3 Expected output 1 2 3 current output 1 #include<iostream> #include<stdlib.h> using namespace std; ...
You aren't actually linking anything together. This line: if(head==0) temp=head=newnode; is the only reason your linked list contains a value at all. The very first value sets head equal to it and when you print head you get that value. In order to properly do a linked list you need a head and tail pointer. The head po...
62,774,544
62,774,665
break statement is not exiting the loop
this is a guess the number game ... the problem is that the "if" clause in the main function has break; statement and it is is not working properly... its purpose is that whenever the user guess is correct it displays the appropriate message and then exits the loop.... but somehow the break statement is not exiting it ...
Your code can never enter that if branch. There are two possible outcomes of result() function: "User guess matched\n\n\n\nyyyaaaaayyyyyyyyyy!!!!!!" or "guess is not correct\n". Neither of them is equal to "User guess matched". You should strongly avoid comparing strings for code flow, for this exact reason. Simple typ...
62,774,803
62,776,184
How can I change '\a' sound?
#include<iostream> #include<conio.h> #include<windows.h> using namespace std; int main() { while(getch()!=27){ cout << "\a\n"; Sleep(500); } return 0; } I heard I could change '\a' alert sound. It's echoing sound now, but i wanna change it. How can I? More question : Is way to change the so...
Yes, you can do that, you may use Beep() from windows.h as shown: #include <windows.h> int main(void) { Beep(500, 500); return 0; } The relationship between the number and frequency is directly proportional, i.e. Less frequency (like 400, 400) - less sound for 400 ms (0.4s) More frequency (like 1000, 1000) ...
62,774,917
62,775,348
Breaking of ODR inside one TU?
The following code compiles without any error, though it seems to break ODR: #include <iostream> template<long Num> class B; template<long Num> struct A { template<long Num1> friend void ffoo(A<Num1> a, B<Num>* = nullptr) { std::cout << "@A ffoo(A<" << Num1 << ">, B<" << Num << ">*)" << std::endl; ...
The friend of B is not a function template. That friend declaration is not a template declaration, so we have [temp.friend] (emphasis mine) 1 A friend of a class or class template can be a function template or class template, a specialization of a function template or class template, or a non-template function or clas...
62,775,089
62,775,460
C++ Can't Loop Through Pointer to Vector of Vectors
I'm trying to loop through a pointer to a vector of a vector of ints and get the value of the int in the nested vector, and am running into problems. This is my code: void test() { // base vectors std::vector<int> test_vect1 = { 1, 2, 3 }; std::vector<int> test_production_item = { 1, 2 }; std::vect...
Your problem is here: v3_size = pointer_to_test_production[v2].size(); pointer_to_test_production is a pointer not a vector and you need to dereference it. Try this: v3_size = (*pointer_to_test_production)[v2].size();
62,775,195
62,777,907
OpenGL rendering textured quad as a single pixel at (0,0)?
I have a renderer2D that is very basic but doesn't render my basic 2D quad correctly. It renders it as a single pixel at the bottom left of the window. The window size is 800x600 The orthographic projection matrices are calculated using glm::ortho(0.0f, 800.0f, 0.0f, 600.0f). For some reason it only renders a single pi...
The layout locations associate the vertex coordinates to attribute index 0 and the texture coordinates to attribute index 1: layout(location = 0) in vec3 a_Position; layout(location = 1) in vec2 a_TexCoord; When you specify the arrays of generic vertex attribute data, then the vertex attribute array 0 is specified t...
62,775,232
62,777,988
clean correctly a QVector
I have a QVector QVector<const ClassA*> list; and I want to know how it is what the best way to clean an QVector in this case. ClassA is not a QObject.
Here it is in two lines of code: while (list.count()) delete list.takeLast();
62,775,288
62,776,154
Restrict movement area of QGraphicsItem inside of polygon area
I am trying to limit the movement of QGraphicsItem inside of a parent object inherited from QGraphicsPathItem that has an arbitrary complex shape (not square). As I understand, I should extract each point of the moving object and check whether each of them is not contained in the parent QPainterPath. Then split the par...
Maybe you can check on QGraphicsItem move event if it is still inside QGraphicsPathItem. The check itself, you can do it with this QGraphicsItem method: bool QGraphicsItem::collidesWithItem(const QGraphicsItem * other, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const And to be sure that item is still fully ...
62,775,308
62,775,450
Using type traits with variadic template arguments
I am attempting to make a print function that functions like a python print function, and I am having issues with enforcing what type the variadic arguments can be, I would like them to be restricted to const char*. Here is my code so far: #include <tuple> #include <iostream> #include <utility> #include <type_traits> ...
You don't need std::tuple to do that and you can restrict your function to copy const char* only using std::enable_if, as follows #include <iostream> #include <type_traits> template<typename ... Args> constexpr std::enable_if_t<std::is_same_v<std::common_type_t<Args...>,const char*>, void> print(Args&&... args) { ...
62,775,857
62,809,942
bind non static templated member function in derived class
#include <functional> #include <iostream> class Plain { public: template <typename Type> void member_function(const Type& s) { std::cout << "Recived: " << s << std::endl; } }; template <typename Type> class Templated : private Plain { public: }; int main() { Plain b; b.member_functi...
I found a workaround #include <functional> #include <iostream> using namespace std::placeholders; struct Test { template <typename Type> void foo(const Type&) { std::cout << "I am just a foo..." << std::endl; return; } }; template <typename T> struct Foo { private: Test* obj; pu...
62,776,229
62,776,879
Qt custom QPushButton doesn't show up on layout
I wrote my own custom QPushbutton class to capture hover event. Thing is when I try to display my custom button it doesn't show up, but capturing hover event works just fine (it prints to console) and QPushButton also appears on the form. Also when I kill bool event(QEvent *) function button shows on display like it su...
Edit: As mentioned earlier, you ignore all the events and return false: default: return false; break; } return QPushButton::event(event); // this line is never reached Instead do this: default: break; } return QPushButton::event(event); //OR default: retur...
62,776,585
62,776,892
How to send an array to C++ function from Objective-C
I'm trying to send an NSMutableArray, or even just two strings to a function in C++ from Objective-C without success. I have no issues getting a string from C++ back to Objective-C, it's the other way around where I'm confused. Here's my code for getting a string from C++: WrapperClass.h #ifndef WrapperClass_hpp #defin...
As per my comment, hold the pointer to the C++ class: @interface WrapperClass () @property (nonatomic) HelloTest* helloTest; @end Better still consider using std::unique_ptr<HelloTest> to manage the memory. Add the set method in the C++ class (implementation omitted): namespace test { class HelloTest { public:...
62,777,049
62,780,161
Iterating through parallel array's to determine the largest number in C++
I'm new to Stack Overflow and C++, so please excuse if I am asking this question in the incorrect format. I am struggling to answer the below question, I have posted my code below as well, please may I ask for some guidance? Use two parallel arrays to keep track of the number of subscriptions for each of their 50 publi...
Two last parameters of findMostSub should be declared as reference to use them as output: void findMostSubs(string pubsP[NUM_PUBS], int subsP[NUM_PUBS], string& mostSubsP, int& nrMostSubsP) { for (int i; i < NUM_PUBS; i++) { cout << "Please enter the name of the publication: "; cin >> pubsP[i]; ...
62,777,133
62,777,241
Error while overloading operator + in myVector class
I know this question has appeared lots of times here and on the internet, but even by searching on this site I can't overload the + operator in myvec class. The strange thing is that I can overload the = operator, but as I write the declaration and definition of the operator +, I get an error. More specifically, I decl...
Move the overloaded operator out of the myvec class. Also don't return references to local variables, change the return type to myvec. class myvec{ ... }; myvec operator+(const myvec& v, const myvec& w); myvec operator+(const myvec& v, const myvec& w) { int d = v.size(); myvec x(d); for(int i=0;i<d;i+...
62,777,268
62,777,372
Is cfmakeraw() available on Macos X / Unix C / C++?
I used a C / C++ code from the Internet, but my IDE gives me the following error on macos: Use of undeclared identifier cfmakeraw I now face the question, whether cfmakeraw is available on Macos / Unix ? Thank you
On your Mac, fire up Terminal and run man cfmakeraw. SYNOPSIS #include &lttermios.h> void cfmakeraw(struct termios *termios_p); So it is available, but you must include <termios.h>.
62,778,313
62,778,665
For G++ on MacOS how to add default include dir /usr/local/include and default library search path /usr/local/lib?
I have installed libfmt with homebrew. Files could be found in /usr/local/lib/libfmt.dylib and and /usr/local/include/fmt. Formally they are links to /usr/local/Cellar/.... G++ does not search /usr/local/include/ and /usr/local/lib/ by default. And I would not like to add them on project level. ❯❯❯ g++-9 -print-search-...
You can do this by setting the relevant environment variables in your shell, e.g: export CPATH=... export LIBRARY_PATH=... Full documentation here
62,778,578
62,778,779
Unique struct as std::map key not inserting all data
I'm trying to fill different maps with "key data", then extract the "key data" as keys into a master map. However; the master map is skipping several unique entries as if there's already an existing key. Can someone please explain what's happening to the rest of the keys and why they are not inserting into the master m...
It's possible that you intended a comparison somewhat like this: bool operator<(MyStruct const &rhs) const { return ((unsigVar < rhs.unsigVar) || ((unsigVar == rhs.unsigVar) && (stringVar < rhs.stringVar) || ((stringVar == rhs.stringVar) && ...
62,778,690
62,779,236
Is there any solution for C++ goto definition in sublime text 3 on ubuntu16.04?
I've tried installing ctags package in sublime text 3 and exuberant-ctag in ubuntu16.04, but it was not feasible to finish goto c++ definition. So I want to know how to be able to jump to c++ definition in sublime text 3 of ubuntu16.04. Any advice will be appreciated.
LSP + ccls sublimelsp/LSP implements a Language Server Protocol (LSP) for Sublime Text 3, which you can use as the language client for your editor: Language Server Protocol support for Sublime Text 3 that gives you IDE features. ccls is an excellent C++ language server which speaks LSP. The ccls author has even answe...
62,779,242
65,706,937
Class Template Argument Deduction - clang and gcc differ
The following code compiles with gcc but not with clang: template<typename T> class number { T num; public: number(T num = 0): num(num) {} template<typename T1, typename T2> friend auto add(T1 a, T2 b); }; template<typename T1, typename T2> auto add(T1 a, T2 b) { // this compiles with both: ...
As mentioned by Barry in the comments, this was a clang bug 44468 (and 47870). Bug fixed. Code now compiles and works well in Clang trunk.
62,779,285
62,779,665
Cannot return vector by value in cpp
Having this: #include <iostream> #include <vector> #include <string> using namespace std; struct Info{ string word; unsigned int i; }; vector<Info> unique(vector<Info> &vec){ vector<Info> ret; size_t len = vec.size(); for(int i=0; i<len; i++){ int j = 0; for(; j<len; j++){ ...
break is used to break from loop not from if conditions so yes break breaks from the inner loop. It will be an easier approach to check for the value in ret vector if it exists don't push it. vector<Info> unique(vector<Info> &vec){ vector<Info> ret; size_t len = vec.size(); for(int i=0; i<len; i++){ ...