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,130,314
66,130,364
When using template and inheritance together, I do not know how to override a member function
I have the following code that mixes template and inheritance. Class Base has some utility function to build items (the work in the sample code), and Child call the work in its implementation of the API call. In this function virtual void call() override { Base<T>::work(); // Problem Here // work(); } ...
Replace Base<T>::work() with this->work(). When you are a template class inheriting from a base class dependent on your template parameter, the compiler doesn't look into your base when it sees something like work(). Instead, you have to tell it that it needs to do that. The easiest way I know of to accomplish that is...
66,130,541
66,130,586
C++ vector memory allocation
You can't have: int array[1000000]; but you can make a vector and store those 1000000 elements. Is this because the array is stored on the stack and it will not have enough space to grow? What happens when you use the vector instead? How does it prevent the issue of storing too many elements?
As defining those as global or in other places might not go in the stack, I assume we are defining int array[1000000] or std::vector<int> array(1000000) in a function definition, i.e. local variables. For the former, yes you're right. It is stored in the stack and due to stack space limitation, in most environment it ...
66,130,768
66,134,738
Running arbitrary SQL commands MySQL C++ (X DevAPI)?
I've connected my C++ project to MySQL and successfully created a session. I was able to create a Schema. My issue is that when I try to run simple arbitrary queries like USE testSchema SHOW tables; using the MySQL/C++ api, I run into SQL syntax errors. When I run the function directly in the MySQL shell, the query run...
You can do it in two steps: sess.sql("USE testSchema").execute(); SqlStatement sqlcomm = sess.sql("SHOW tables"); SqlResult res = sqlcomm.execute(); for(auto row : res) { std::cout << row.get(0).get<std::string>() << std::endl; } Also, you can use the Schema::getTables(): for(auto table : mySchema.getTables()) { ...
66,131,094
66,131,150
Issue turning int array into matrix class to complete operator-overloading
I'm trying to multiply 2 matrices together using operator-overloading but I'm getting an error when trying to convert my int array into my matrix class in order to use it. I'm not sure how to fix these errors #include <iostream> using namespace std; struct matrix{ int array[4][4]; public: void make(int A[][4],...
There are two problem with your code:- m1.make(a[4][4], 4); // should be m1.make(a, 4); make is expecting a 2D array you are passing an integer In the operator *function array[x][y] = (array[x][y] * m.array[x][y]); // your should assign to output[x][y] here
66,131,160
66,140,102
How to specify a custom class conforms to a standard or custom type trait
I feel like I am missing something. I cannot see anything about how I am supposed to specify my class has a trait. E.G. #include <type_traits> class foo { type_trait trivially_copyable = true; //? type_trait integral = false; //? public: foo(const int& val); int get_x() const; private: ...
C++ type traits are implicit. You opt into or out of them by satisfying their requirements. 1: is_integral only identifies standard integral types. A wrapper type never satisfies it, even if intended for mathematical use. 2-4: You would either delete the copy constructor and make the class uncopyable, or define the cop...
66,131,239
66,132,864
Store file pointer, and reset to that position based on condition?
I am not able to understand how I can reset the file pointer to a previously stored position. Here is the actual problem in pseudocode: I am reading characters from a file f in some function A (B and C are some other functions): void A (fstream& f) { char c = f.get(); while (c == ' ' || c == '\n')...
std::istream descendants, including std::fstream, have tellg() and seekg() methods for querying and setting the stream's input position, respectively.
66,131,383
66,131,495
What is the type of an rvalue reference parameter inside a function?
I have a really simple function definition here: void testRvalue(int&& r) { printf("rvalue ref is called\n"); testRvalue(r); // this line gives "no known conversion from 'int' to 'int &&' for 1st argument" } I mean inside this function, what is the type of r? Isn't it int&& (the parameter is int&& r so how com...
A very good read is Value categories. Yes, the type of the variable r is indeed int&&. However what matters here is the expression and: Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category. Each expression has ...
66,131,510
66,132,051
c++ call template class specialization member function
I am new in C++ and I am trying to implement template class specialization member functions. Here is the code which I did: #include <iostream> #include <map> using namespace std; using std::string; namespace std { template <> struct number_limits<Second> { using val_type = Second::value_type; public: ...
I would recommend researching classes in C++ more before coming back to this problem. I also would recommend not messing with namespaces yet as a beginner as they're only really useful when working in large teams of developers and only make the code harder to understand when used correctly. It doesn't seem like you qui...
66,131,690
66,133,008
How to use a custom heap with IMFSourceReader
In our application we are using an IMFSourceReader to handle the decode of a .mp4 file for us to play. What we would like to do is reserve an amount of memory in the application and then configure the IMFSourceReader to use this reserved memory as its heap when it allocates the IMFSampleObjects. I am wondering what mig...
I do not think it is realistic to supply custom memory heap without re-implementing Media Foundation primitives behind your source reader media pipeline (also, in the context of the question it would be worth mentioning its details). More importantly though, I suppose there is no real need or advantage in doing things ...
66,132,237
66,145,786
Launching the right number of CUDA blocks for a custom PyTorch activation function
I'm currently writing a CUDA kernel for a custom operation (an activation) for PyTorch, but I'm quite unfamiliar with any form of GPU programming. For reference, I was following the Custom C++ & CUDA extension tutorial. A simplified example of the sort of operation I want to do: Let's say I have an input tensor, X_in, ...
I'm speculating here, but - since your operations seems to be completely elementwise (w.r.t. X_in); and you don't seem to using interesting SM-specific resources like shared memory, nor a lot of registers per thread, I don't think the grid partition matters all that much. Just treat X_in as a 1-D array according to its...
66,132,350
66,132,458
Why does ~n give -(n+1)?
I wanted to test what happens when I write this code. I can not explain the following case: Input: 5 Output: -6 #include <iostream> int lastBit(int n){ return ~(n); } int main() { std::cout << lastBit(5); }
Computers express negative numbers in quite a specific way. Values are always stored as series of bits and there is no way of introducing negative sign, so this has to be solved differently: one of bits plays role of a negative sign. But this is not all - the system must be designed to handle maths properly (and ideall...
66,132,666
66,132,711
Unary fold with empty parameter pack
#include <iostream> #include <utility> template<std::size_t... items> constexpr std::size_t count() { return std::index_sequence<items...>().size(); } template<std::size_t... items> constexpr std::size_t fold_mul() { if( count<items...>() == 0 ) { return 1; } else { return (......
The problem is, when being specified fold expression with empty expansion, (... * items) is invalid at compile-time; even it won't be evaluated at run-time. You can use constexpr if (since C++17); then the else-part will be discarded when being specified fold expression with empty expansion. If the value is true, then...
66,133,421
66,273,916
Unable to display window via cv::imshow(). What am I missing?
I'm working simple intro OpenCV program. I'm running in Virtualbox (as Ubuntu 20.04). C++/ VS Code. LLDB debugger. Same fault if I run the virtualbox on MacOS or Windows. ---main.cpp--- #include <opencv2/opencv.hpp> // Catch all for all libraries within OpenCV int main() { cv::VideoCapture cap; //initialize c...
So here is a screen shot of the error noted when doing debugging step by step. That error note The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowIm...
66,133,744
66,134,172
Combine Python script with different GUI
I have script in Python containing several functions, and one Callback (when event occurs). I would like to release some "package" from my script , which could be importable and usable for other users. Lets say: Some one can use it for creating GUI app in JAVA, another it will incorporate to his own C++ Gui app, and s...
So you want to be able to call Python functions from Python, Java and C++? The Python case is just a matter of importing your module. To call Python functions from Java, try Jython: https://www.jython.org/index.html To call Python functions from C++, use the Python header files and this approach https://docs.python.o...
66,133,976
66,134,002
Why is there no "exists" functions within C++ map?
I find myself sometimes checking to see if an item already exists in a std::map, which I do with the following: if(myMap.find(item) != myMap.end()) ... I was wondering why there is not a function such as exists() which would return the same bool of whether the item is already in the map. It would save a bit of typing,...
Since C++20 you can use contains. Return value true if there is such an element, otherwise false. if(myMap.contains(item)) ...
66,133,993
66,134,975
Generic function using std::span doesn't compile
I wanted to make an isIn function that takes an std::span. This is my attempt: #include <span> template <typename T1, typename T2> bool isIn(const T1& x, std::span<const T2> v) { for (const T2& e : v) if (e == x) return true; return false; } // this one would work, but I want my function t...
There are no conversion/promotion for template deduction, so const int (&)[4] cannot be deduced as std::span<const int /*, 4*/>. You might still provide overload to do the conversion yourself (care to avoid infinite recursive call): template <typename T1, typename T2, std::size_t N> bool isIn(const T1& x, std::span<con...
66,134,120
66,134,255
Is there only one static variable between processes or each has its own?
I have declared a static variable, and use the static variable in two processes. Is there only one static variable between processes or each has its own? I focus on multi processes, not for static variable syntax
Is there only one static variable ... Depends on context. If it is a static member or a static variable in block scope then yes, there is only one instance. If it is a static variable in namespace scope, then there are as many instances of the variable as there are translation units using the variable. ... between p...
66,134,879
66,144,592
Is fullscreen really better than windowed mode in a Direct3D 12 application?
I'm trying to learn Direct3D 12 to do some simple 3D graphics for fun. I've heard that pure fullscreen is the way to go for maximum fps, but now that I'm testing it, fullscreen seems way, way worse than windowed mode. For example, a static color on a WS_BORDER window (with fullscreen size), and Windowed set to TRUE in ...
The story of "fullscreen" for Direct3D is a complex one, and from the other comments/answers in this thread continues be a confused one. For DirectX 12 on Windows 10, there is no FullScreen Exclusive mode (FSE). When you use SetFullscreenState with either of the modern DXGI_SWAP_EFFECT_FLIP_DISCARD or DXGI_SWAP_EFFECT_...
66,135,008
66,204,777
Missing VC_MFCSupport
I installed Visual Studio 2017 recently. Today, when I tried to load C++ Win32 Console Application project, I have got the following error: Project 'Test' could not be loaded because it's missing install components. To fix this launch Visual Studio installer with the following selections: VC_MFCSupport I reinstall Vi...
Click Repair VS to repair VS. When you finish it, close VS, delete .vs hidden folder under the solution folder, delete any Debug,Release,x64 folder under the solution folder, project folder. Then, reload the project again. Also, you could try to create a new c++ project to test whether the issue happens again.
66,135,101
66,135,388
mongocxx insert current date with microsecond precision
I want to insert a mongodb datetime object with microsecond precision using the mongocxx c++ library. How can that be accomplished? What I have so far: auto final_doc = bsoncxx::builder::basic::document{}; auto now = std::chrono::high_resolution_clock::now(); final_doc.append(kvp("ts",bsoncxx::types::b_date(now)); but...
I want to insert a mongodb datetime object with microsecond precision That's impossible. JSON/BSON Date type is specified in ECMA-262 as a fixed format with millisecond precision: 15.9.1.1 Time Values and Time Range Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. 15.9.1.15 Date Time String...
66,135,466
66,135,643
Inline code in C++: options and their advantages/disadvantages
What are the methods to achieve inline code in C++? I can only think about macros and inline functions. Are there more alternatives in C++11/17/20 (e.g. lambda) ? Advantages and disadvantages? // do macros still make sense in modern C++ standards? #define square(x) ((x)*(x)) // is this a good alternative to macros? te...
// is this a good alternative to macros? template <class T> inline T square(T x) { return x * x; } Yes, this is the preferred way. (Although templates in general don't require inline, whereas explicit template specializations and instantiations do, it is ok to be consistent and write what one means). Also note that co...
66,135,780
66,136,013
Is there a C/C++ equivalent for Python's "__init__.py"?
In Python when you create a module you create an __init__.py file (at least, usually). Is there a C/C++ equivalent of this thing? I mean is there a way to #include a directory actually including a file inside it?
No, there is no such feature in C++ itself. Nor it seems the typically used compilers support it. A feature similar to Python's modules is introduced in C++20: https://en.cppreference.com/w/cpp/language/modules You may want to look at build systems like SCons or CMake which will allow you to implement some preprocessin...
66,135,954
66,139,302
How to overload [] operator to initialize an object
I wanted to implement a class like std::map (just for exercise and learning purposes). I defined my std::map variant like the following one: template <typename Key, typename Value> class mmap { private: std::vector<DATA<Key, Value>> m_maped; DATA<Key, Value> m_elements; std::mutex m_mutex; bool m_repeat...
What you have there is a std::initializer_list of Key-Value pairs submitted to the index ([]) operator of the mmap class. By default, the compiler doesn't create an overload to the index operator like that, we need to explicitly define it. It may look something like this, void operator[](const std::initializer_list<DAT...
66,135,964
66,136,161
How to access nested class member function from enclosing class where all the members are public in c++?
I am using nested classes in a sensor library development and running into errors. Below is sample code and explanation. MainClass.cpp class MainClass { public: class nested_class; void func1(){ nested_class1.print(); } }; NestedClass.cpp class MainClass::nested_class { public: virt...
nested_class1.print(); isn't how you'd call the print member of an instance of nested_class1, even if it were declared before there. The definition of MainClass::func1 must be after the definition of nested_class1, which must be after the definition of MainClass::nested_class. #include <iostream> class MainClass { pu...
66,136,307
66,139,546
CPD pointcloud registration (CPD-Library) in conjunction with Point Cloud Library (C++)
I'm currently trying to understand the following C++ CPD Library: https://github.com/gadomski/cpd https://www.gadom.ski/cpd/index.html I already have a framework which uses the PCL library for registration of point clouds and am currently trying to introduce the CPD registration as another option. In the documentation ...
Every row of those matrices is a point and every column is a coordinate of this corresponding point. So a point cloud describing a 3-dimensional space would need to become a n x 3 matrix where n equals the number of points within the point cloud.
66,136,413
66,137,582
Function Pointers as Event Callbacks in a st
I am currently trying to implement an event system where layers can subscribe to certain event types. I am struggling with function pointers for the callback methods. In the layer.h file I have the OnEvent function and a function pointer which looks like this: void OnEvent(const Event& e); void(Engine::Layer::*...
Assuming I understand what you're doing... You have an EventDispatcher, and he needs to keep a registry of possible callbacks to make. I'm going to cut & paste a little code I use then explain it. First, this is the relevant portion of my Route object. class Route { public: typedef std::function<void(const HTTPServ...
66,136,447
66,140,307
How to make asynchronous read of a file with IOCP?
I have faced an implementation problem. I am puzzled on how to implement IOCP. I have read a lot on the Internet about it, but still missing one step. So far what I have learnt is as follows: In order to use IOCP: on an init function: CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); // to have a max thread n...
So the answer for my question is here: https://stackoverflow.com/a/680416/2788176 In very simplistic (and a little over-simplified) terms, you tell the IOCP about the IO jobs you want done. It will perform them asynchronously and maintain a queue of the results of each of those jobs. Your call to tell the IOCP about t...
66,136,586
66,136,667
Program is ignoring .cpp file and refuses to acknowledge Ship.cpp file. Keeps saying "this file does not belong to any project target"
My problem is that for some reason main.cpp refuses to acknowledge that Ship.cpp exists. If I add in main.cpp #include "Ship.cpp", the code works with no problems. What could be the problem? (IDE is CLion). It has never happened before. When I open ship.cpp, on top it says "this file does not belong to any project targ...
CLion uses CMake to organize and build your project, one of your project files should be CMakeLists.txt, and inside it, there should be a line that looks like that add_executable(target_name Main.cpp) You need to add your Ship.cpp file to sources there add_executable(target_name Main.cpp Ship.cpp) As a side note, you...
66,136,632
66,136,896
c++ macro parametrized (repetitive) expansion
Im using an enum set (c style) id_t to represent different test parameters T0, T1, ... These "parameters" are then "repeated" in two arrays; one idsenum holding the values T0, T1, ... themselves and another idstxt holding their textual representations "T0", "T1", ... #define enumsetmacro T0, T1, T2 enum id_t { enums...
using boost.preprocessor: #include <boost/preprocessor/seq.hpp> #include <boost/preprocessor/for.hpp> #include <boost/preprocessor/repeat.hpp> #include <boost/preprocessor/stringize.hpp> #include <string> #include <vector> #include <cassert> #define DECL_ENUM_IDENTITY(a_r, a_dummy, a_elem) \ a_elem, #define DECL_...
66,137,067
66,137,278
How is it possible that std::shared_ptr<Derived> casts to std::shared_ptr<Base> with no compiler errors?
I'm trying to implement a custom smart pointer. So I have something like this: // Base class for every object class Base { public: int n_holders {}; }; class Derived : public Base {}; // Custom shared pointer template<class T> class Sptr { public: T* obj; Sptr(T* obj_) : obj{obj_} {} }; void SomeFunc(Spt...
std::shared_ptr has a constructor (from cppreference): template< class Y > shared_ptr( const shared_ptr<Y>& r ) noexcept; (9) This overload ... Constructs a shared_ptr which shares ownership of the object managed by r. If r manages no object, this manages no object too. The template overload doesn't participate...
66,137,703
66,137,768
Don't understand what's going on in the "if" condition?
A bit strange question. But unfortunately. I can't understand the logic that is written in the condition in the Unreal C++ code. I have conditions in a member function: void MoveForward(float amount) { if (amount) { // do that } } What does "amount" parameter mean in a condition? What is the verification for? If it...
In C and C++ if tests for a nonzero value. Anything that's nonzero is considered true. When it comes to floating point values, what exactly is a zero is something books can and have been written about, so don't do it if you want reliable code. It's safe to assume that it tests for amount != 0.0f. But as far as the comp...
66,137,943
66,138,054
Does std::make_shared value initialize class members whose default ctor does not initialize?
Does std::make_shared value initalize members when there is a default ctor that fails to initailize its members? I stumbled upon this when using a class where the default ctor did not initialize members using RAII style gave a warning and wondered why no warning was issued when it was used before elsewhere. Elsewhere i...
No, make_shared does not do anything different, with respect to constructing an object, than otherwise happens when an object gets constructed in any other way. All objects follow the same rules when they get constructed in C++. Your constructor fails to initialize mode. Just because it happens to be zero, when it's co...
66,137,964
66,140,780
How to find the maximum length of string of particular fontsize that can come in a CEDIT rectangle in MFC?
I am trying to find out the maximum fontsize for a particular string that can come in a CEDIT Rectangle in MFC. How I want is : int maxFontSizeThatCanResideInCedit(string text){ do something return fontSize; } What I am thinking is if somehow I can find the pixel length/width and compare string with every font...
Won't code the answer, but will talk through it... First, an edit control will have a font. First thing you have to know is what font name and font size are going to be used for the edit control. You might want to default to GetStockObject(DEFAULT_GUI_FONT) or not. But, it might be a good place to start. You can create...
66,138,080
66,138,727
Placement new after cuda malloc managed memory
I have terrible errors with CUDA managed allocation. I'd like to confirm that the following code is correct: T* x; cudaMallocManaged(&x, sizeof(*x)); new(x) T(..) Is placement new syntax supported by CUDA version 11. Thanks.
yes, that should be usable, ignoring minor issues like the use of ellipsis and missing semicolon. You can find examples of proper and typical use of placement new in CUDA right here on the SO cuda tag with a bit of searching. Yes, placement new is supported/usable. The code you have depicted here is mostly host code ...
66,140,042
66,140,180
Detection of free '==' operator using std::experimental::is_detected_v : different behavior for std classes
I am trying to detect at compile time if some classes do have the 'equals to' operator defined. I don't understand the behavior of the following snippet: #include <iostream> #include <vector> #include <experimental/type_traits> template<typename T> using SupportsEqualsToOp_t = decltype(std::declval<T>().operator==(std...
You've messed up your operator precedence. std::cout << v0 doesn't compile, nor would (std::cout << v0) == v1 Not only that, your SupportsEqualsToFree_t finds any ==, not just free function ==. If you want specifically free function ==, you need something like template<typename T> using SupportsEqualsToOp_t = decltype(...
66,140,326
66,145,448
gtkmm widgets - use smartpointers or pointers?
I am trying to learn how to use gtkmm having got a basic grasp of C++ (I like a challenge!). I have been working my way through the tutorials (as well as other reading). I am trying to use the approach of using glade to design the UI and then write the code to do the work. So I have built a very simple UI (window and...
First of all, to understand the difference, and since you are new to C++, I would recommend reading on the following topics: Dynamic memory allocation (new/delete) Memory leaks Casting Templates First approach: get_widget With this approach, you are getting a raw pointer (as opposed to a smart pointer) to a widget de...
66,140,384
66,140,464
Dot in division (1./2)
This code solves the program : Create an algorithm in the form of a flowchart, write and debug the task using recursive and ordinary functions. Corresponding results. What is dot used for here "x = (1. / 2) * (f + (a / f));" ? #include <iostream> #include <iomanip> using namespace std; int main() { int k, e, x, a, d, ...
The dot in "x = (1. / 2) * (f + (a / f));" is used for assuring that the division is interpreted as a float division instead of an integer division, so the result of (1/2) is 0.5 instead of 0.
66,140,397
66,140,508
Writing zeroes to file block does not work
So I'm trying to write a sequence of zeroes from a file offset until the end of the file, here is my code: HANDLE hFile = CreateFileA((LPCSTR)"hello.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile < 0) return -1; DWORD fileSize = GetFileSize(hFile, ...
The line WriteFile(hFile, (PVOID)&zeroes, fileSize-offset, &check, NULL); is wrong. You are writing data in the pointer variable zeroes itself, not what is pointed at by the variable. Typically the pointer has only 4 or 8 bytes, so it may cause out-of-range access if the file is large enough. Remove & before zeros...
66,140,717
66,140,809
Problem using std::sort with custom class
Doing hackerrank problem "Attending Workshops" https://www.hackerrank.com/challenges/attending-workshops/problem I have the problem that I can't sort my vector. I tried with a lambda (in commentary) and then by overloading the operator >. My vector never turn out to be sorted. Can you help me find what I did wrong. Her...
workshops.reserve(n); is wrong. It just do allocation and not inclease the number of valid elements, so the end() iterator will still be the top of the array. You should use workshops.resize(n); instead.
66,140,737
66,141,093
Default template argument deducing to the wrong type in a conditional
I have the following testcase: #include <type_traits> template <typename Ty_> using conditional_ref = typename std::conditional<std::is_fundamental<Ty_>::value, Ty_, Ty_ const&>::type; template <typename Ty_, typename Ty2_ = conditional_ref<Ty_>> inline void f(Ty2_ arg1) { static_assert(std::is_same<Ty2_, cond...
Ty2_ is deducible, so default is not used at all. you might use directly: template <typename Ty_> void f(conditional_ref<Ty_> arg1) { static_assert(std::is_same<decltype(arg1), conditional_ref<Ty_>>::value, "uh-oh!"); } Demo
66,140,767
66,166,300
Why does auto works differently in "range for" in 2D and 1D arrays in C++
Hi I am working with 2D and 1D arrays in C++ and using range for to access elements.The code that i am using is as follows: For 2D Arrays int ia[3][4] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (auto& row : ia) { for (auto col : row) { cout << col << endl; } } For ID Array int base_array[2] = { 1...
Case 1(Without reference symbol infront of row) For the outside loop, the loop variable row is initialized to the first element of ia which is itself an array, so array to pointer conversion will take place and row will become int*. And since we cannot loop through an int*, we get an error when we try to do so in the i...
66,141,542
66,141,623
c++ perfect forwarding with universal reference prevents type deduction?
I consider the following 2 snippets which do the same thing. In the first case, I don't use a universal reference, and so I have to write the function set twice. In the second case, with a universal reference I can write the function once, but the user of the class has to specify explicitly the type passed to the funct...
In this case, you can add a default value to the U template parameter like template<typename U = T> void set(U&& a) { a_=std::forward<U>(a); } and now if it can deduce the type, like with {} which has no type, then it will fall back t using T as the type for U.
66,141,546
66,142,313
Using a non-static data member as parameter
I have this code: #include <set> #include <vector> struct Comp { const std::vector<int> & xs; Comp(const std::vector<int> & xs): xs(xs) {} bool operator(int a, int b) const { // Sort based on data in xs. } }; class Foo { public: Foo(); private: std::vector<int> xs; std::set<st...
You can either provide the reference to xs to Comp and Comp to ys in the member-initialisation-list of the constructor or once for all where the ys member is declared. !!! if you change the content of xs while ys is not empty, then ys will certainly become unusable !!! In this adaptation of your code, you can see tha...
66,141,615
66,141,855
What is the class keyword without a body for?
I don't understand what "class" means in Unreal C++ class USpringComponent* BoomArt; class UCameraComponent* Camera; As I know the class must have a body, but there is no such thing. Why write a class? What is the general logic of this key word? I'm used to seeing this: class MyClass { // body... } Why write the c...
class USpringComponent* BoomArt; Declares a variable named BoomArt. The type is a USpringComponent*, or at least that's what we want the type to be. Presumably, class USpringComponent has no been declared yet, meaning if we wrote USpringComponent* BoomArt, we'd get a compilation error ("Unknown type USpringComponent" ...
66,141,784
66,142,295
What is the best way to save function arguments and call the function later?
In C++14, I would like to be able to save function arguments and call the function at a later time. My goal is to be able to do something like: auto delayed_function{ some_callable }; delayed_function( 1, 2, 3 ); // arguments are stored, but some_callable is not called yet delayed_function.call(); // some_callable...
There are couple ways to do it. Using future: auto value = std::async(std::launch::deferred, delayed_function, 1, 2, 3); ... value.get(); Or just using lambda: auto f = [arg]() { return delayed_function(arg, 2, 3); } ... f();
66,142,095
66,142,162
c++ csv comma delimited file entries, trouble with mixed types
test file 11111,Smith,Bob,10,9,8,10,9,10,92,89,90 11112,Doe,Jean,8,9,8,7,9,9,84,88,89 11113,Hardy,Joe,9,9,10,9,8,9,88,90,95 information stored in struct Student { std::string ID; std::string lName; std::string fName; int quiz1; int quiz2; int quiz3; int quiz4; int quiz5; int quiz6;...
Your problem here is that unlike getline, which throws out the delimiter, stream >> student.quiz1; doesn't so there is a , in the stream when you try to do stream >> student.quiz2;. You need to get that comma out of the stream. You can do that by using get to "eat" the character, or use a named char like char eat_com...
66,143,188
66,143,317
Why is my program failing for numbers larger than 2^29?
I made the following program that takes a list 'a' of length 2^i (initialized as all 1's), and adds all the numbers it contains together. When i is at least 30, it returns a nonsensical answer. I don't understand why, I used long's for everything and on my machine the size of a long is 8 bytes = 64 bits, so I would say...
We can, you just need to the correct types. Compile and execute the following code. #include <iostream> #include <limits> int main() { std::cout << "Max int value: " << std::numeric_limits<int>::max() << '\n'; std::cout << "Max long value: " << std::numeric_limits<long>::max() << '\n'; std::cout << "Max lo...
66,143,289
66,143,381
Error in accessing the right node pointer (Reference pointer) in tree
Doing a problem on how to convert a binary tree to a doubly linked list tree in the void po() function we are passing root node and 2 nodes as their address and now i want to set the right of one of the reference node i am doing the below way and getting error anyone know how to solve this ??? void po(Node* root,Node *...
This statement *(q)->right=root; actually looks like *(q->right) = root; because the postfix operator -> has a higher precedence relative to the unary operator *. But q is a pointer to pointer. So the pointed pointer does not have a data member right. It seems you mean ( *q )->right = root; In this case the expressi...
66,143,333
66,143,439
Can SDL2 capture global keystrokes?
I'm trying to make simple background/console tool in C++ which would listen to my keystrokes. SDL_PollEvent nor SDL_GetKeyboardState listens when foreign window is focused. Question is, if it is possible to do this with SDL2 or do I need to use other multi-platform library or should I just do it from scratch per OS? No...
I don't believe that global keystroke capture is in scope for SDL. You'll have to use some other platform-specific means. For Linux and Unix, libX11 is one of the options, another would be to use /dev/input/event# (see e.g. here for examples).
66,143,516
66,237,002
Incomplete Type is not Allowed QApplication
I am learning C++ with Qt. I have installed Qt 5.15 and am using VS2019. I have the below code (as per an example in a textbook I am working through): #include <QtGui> int main(int argc, char* argv[]) { QApplication app(argc, argv); QTextStream cout(stdout); //declarations of variables int answer = 0;...
The correct headers to include are the following: #include <QtWidgets/QApplication> #include <QtWidgets/QInputDialog> #include <QtWidgets/QMessageBox> Once declaring these, the compiler accepts the code.
66,143,725
66,143,788
C++ public enum in namespace of class
I am making a class and I want to create an enum inside that class so that it can only be accessed through the namespace of that class. I would want users to be able to access the enum outside of the class like so: GpioPin pin(23, GpioPin::OUTPUT); where GpioPin is the class and OUTPUT is one of the enum values. I tri...
Look at enum class (google for c++ enum class). Class Foo { public: enum class Color{ Red, Green, Blue}; }; Then, you reference things as: Foo::Color::Red Works great.
66,143,752
66,144,018
Why aren't C++ constructors capable of adding in new member variables?
It would make more intuitive sense to me if you could add in member variables in the constructor. This way, the class can adapt to changing input.
In C++ an object always has a fixed size. If constructors can add members at runtime, that guarantee goes out the window. In addition, in C++ all objects of the same type have the same size. Since a class can have multiple different constructors, the different constructors could specify different sizes. This single, fi...
66,143,794
66,144,026
Why do we need the last two definitions for the grammar production base-specifier?
In [class.derived.general]/1 we have the following definitions for base-specifier: base-specifier:     attribute-specifier-seqopt class-or-decltype     attribute-specifier-seqopt virtual access-specifieropt class-or-decltype     attribute-specifier-seqopt access-specifier virtualopt class-or-decltype Why do we need the...
Why do we need the second and the third definitions above? Syntactic sugar. Thanks to this, both class Derived: public virtual Base and class Derived: virtual public Base are valid. Much better than having to look up the order once a year when virtual inheritance is needed. Why is the virtual required in the second ...
66,144,256
66,160,834
How to make a pointer matrix getter in C++
As I say in the title, how can i writte the function getBoard() which has to return the private variable m_board. M_board is a non-dynamic matrix of pointers to other class called Box class Board { public: Board() {} void initializeBoard(); void putPieces(vector<vector<Pice*>>& player1, vector<vector<Pice...
It looks to me like you are trying to build a two dimensional cellular automaton. https://en.wikipedia.org/wiki/Cellular_automaton As several comments have suggested, this is more easily done using modern C++ code, which means std::vector and smart pointers. I have found that doing this comes up again and again. So it...
66,144,404
66,144,576
cpp Simulating a smooth mouse drag
So for one of my projects I need to be able to hold a key down on my keyboard and for aslong as i hold that down it slowly moves my cursor down. I have no clue on how to perform this action. I know that SetCursorPos instantly moves the cursor but im looking for a smooth drag. Thanks
You do not tell us what kind of library you are using. But here is an idea: If you know that the SetCursorPos instantly moves your cursor somewhere else. You could try incrementing the position by calling SetCursorPos(current_cursor_pos + 1) everytime a button is pressed, whether or not the button is pressed, you will ...
66,144,954
66,145,788
Why aren't cmath's pow and sqrt templates?
As a matter of curiosity, why are std::sqrt and std::pow overloaded just for a single type of parameter? Why are they not implemented as function/functor templates?
They are overloaded for types float, double, and long double. There are no other floating-point types, so there would be no advantage in a more general solution using templates. The C++ <cmath> header is almost, but not quite, a copy of C's <math.h> header. C doesn't have overloading, so it provides three different squ...
66,145,012
66,145,475
Insert vs. emplace_back for appending new element to vector/list if you want an iterator to the newly inserted element
I understand the general differences between insert and emplace_back for std::vector and std::list. Normally, I would just use emplace_back any time I want to append an element. For some applications, I need to append the element and have an iterator pointing to that newly appended element. So typically, I've been doin...
I have no clue about any impact on performances (although I cannot imagine any difference) but if you want to append a new element and obtain a reference on it, you can write auto &r=v.emplace_back(a, b, c); if you prefer to obtain an iterator on it, you can write auto it=v.emplace(cend(v), a, b, c); As far as I can ...
66,145,314
66,145,415
Remove duplicate elements from std::vector but starting from the front?
How can I delete duplicate elements from a vector but starting from the front? So 2 3 4 5 2 5 would become 3 4 2 5 1 5 3 1 would become 5 3 1 I would like the solution to be easy to read, and it would be nice if it had good performance as well.
If a container supports bidirectional iterators then it is unimportant from which side of the container you are trying to remove duplicate elements because you can use reverse iterators. Here is a demonstrative program. #include <iostream> #include <vector> #include <iterator> #include <algorithm> template <type...
66,145,719
66,146,214
istream loop makes the program jump over cin statement
Here is a program that takes a sequence of space-separated numbers and stores then in a vector. The problem is when putting the cin loop before the input of x0, the program jumps the next cin statement, but the reverse is working very normally. Can you explain to me what I am missing here? State of jump: vector<int> V{...
In the first example, you are calling cin >> temp in a loop until the read fails, either because a non-integer is entered, or the user explicitly ends input (with Ctrl-C or Ctrl-Z or whatever your platform uses). And then you are trying to call cin >> x0 without first clearing cin's error state, so that read will also...
66,145,826
66,146,996
Returning a char array of initially unknown length from a function in Arduino
I need to send json to a server. The code works perfect, but as I need to invoke it on two locations and as such want to make a function our of it. However, I cannot get it to work with a char array. A possibility is to convert the char array into a String I would expect, but that is not memory efficient I would expect...
You're passing encoded by value char* encoded; int contentLength = generateData(encoded); which means that when you assign it in generateData() encoded = (char*) malloc(newLength + 1); encoded[newLength] = '\0'; you're changing only a local variable. The quickest fix would be to change generateData() to take its para...
66,146,377
66,178,102
MS MPI does not have the folder of includes
I have downloaded the latest version of MPI from here version 10.1.2 on my windows 10. I followed this video to install it. But, for mine, there is no folder of lib and includes when I want to modify the properties of my project. Any suggestion?
after installations, two folders will be created! one is in program files named "Microsoft MPI" and the other one will be in programfiles(x86) named "Microsoft SDKs" which include both "includes" and "lib"
66,146,592
66,160,447
C++ disable an overloaded operator in child class
I have this String class where I overloaded the operator + to concat strings. class String { private: char* value; public: String(char*); String operator+(String&); }; int main() { String s1("Hello"); String s2(" world!"); String s3 = s1 + s2; cout << s3 << endl; return 0...
You have two possibilities. Override with private visibility class GoodString : public String { private: String operator+(String&); }; delete the operator (since c++11) class GoodString : public String { public: String operator+(String&) = delete; };
66,146,740
66,146,784
Why is the copy constructor called after the simple constructor is called?
I was trying to understand the copy constructor, and read this (https://www.tutorialspoint.com/cplusplus/cpp_copy_constructor.htm) tutorialspoint article about it. However, I'm having trouble understanding when the copy constructor was called in the code below. Doesn't Line line(10) only call the Simple constructor, wh...
Doesn't Line line(10) only call the Simple constructor Yes. Is it because we passed line as an argument to display? Yes. So does passing an object as an argument always invoke the copy constructor? Not necessarily. For example, some types don't have constructors so copying them won't invoke a constructor. Further...
66,147,215
66,147,310
More complex diamond problem instance. How to make it work with constant fields?
Let us consider ordinary diamond problem but slightly improved. Now class A have constant fields. struct A { const int a; A (int _a): a(_a) {} }; struct B: virtual A { const int b; B(int _b, int _a): A(_a), b(_b) {} }; struct C: virtual A { const int c; C(int _c, int _a): A(_a), c(_c) {} }; str...
The constructor may be written as follows: D(int _a, int _b, int _c): A(_a), B(_b, _a), C(_c, _a) {} Because A is a virtual base class, the D constructor must initialize it despite the fact that it is not a direct base class. When an object of most derived type D is being constructed, D::D will first initialize A, and...
66,147,370
66,147,414
Reversing a vector using functions
I'm trying to reverse a vector using functions but whenever I run the program it terminates and outputs nothing. Can anyone please tell me what I am doing wrong? #include <iostream> #include <vector> using namespace std; void reverseavector(vector<int>& vec) { for (int i = vec.size() - 1; i >= 0; --i) { ...
In your code, you declared the following statement: vector<int> vect; This statement means that a vector of integers named vect get created, but you didn't specify a size for it, therefore when the following loop is reached: for (int i = 0; i < vect.size(); ++i){ vect.push_back(input); } vect.size() return 0 beca...
66,147,712
66,165,063
Type casting objects without pointers
I'd like to type cast from a base class to a derived class. For example: class A {}; class B : public A {} A a; // do stuff with a B b = (B)a; This works fine with B* b = (B*)&a; but I'm trying to avoid that. Is this possible?
Jedi mind trick This is the answer you are looking for. /Jedi mind trick B b = *(B*)&a; It's the same concept as getting the value of an unsigned char (byte) array at a specific offset (e.g. int foo = *(int*)&bar[0xC];) but with objects. #include <stdio.h> class A { public: bool m_bIsB; public: A() { this->m...
66,147,788
66,147,912
Sorting Algorithm for Class
I am quite new to programming, and I have tried restlessly to figure out how to do this, but Alas I have yet to find anything. In my program, I have a struct. It is a sport sim, so the struct looks a bit like this struct Team{ string name; int reputation; } I have over one-hundred teams declared in an array Team tea...
in your structs you have the member int reputation; assuming this is your "way to arrange them" you could declare a nested loop that iterate throug your array to find which team have the highest reputation for the outer loop to iterate through each team. and the inner loop to iterate through each team reputation"to fin...
66,147,941
66,148,061
How to enabled gdb -g3 debug level with CMake?
When you would like to enable debug on CMake, you use cmake .. -DCMAKE_BUILD_TYPE=Debug, but this only sets -g which is the default debug level. -glevel Request debugging information and also use level to specify how much information. The default level is 2. Level 0 produces no debug information at all. Thus, -g0 nega...
set the CMAKE_C_FLAGS "-Og -g3 ...
66,148,196
66,148,863
Why do we need primitive assembly after vextex post processing?
The output of Vertex post processing is in Window space, here after (based on standard pipeline ) primitive assembling comes, why? I know primitive assembly happens in many stages like before clipping, but why do we need PA at this stage.
Primitive assembly happens before clipping, but the specification isn't clear on exactly where before it. In fact: After a primitive is formed, it is clipped to a clip volume. That's all it says about its location (outside of needing to do it for tessellation or GS's).
66,148,259
66,148,948
I have an error in my c++ code Adress Sanitizer errer keeps poping up
I keep getting this error ==27398==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000030 (pc 0x55b3e7f5a676 bp 0x7ffc3378c600 sp 0x7ffc3378c520 T0) ==27398==The signal is caused by a WRITE memory access. ==27398==Hint: address points to the zero page. #0 0x55b3e7f5a675 in Inventory::addItemStackNoCheck(It...
You want to see if the node is empty, not whether the data member occupied is 0. if(this->head = nullptr) In addition you're going to want to have, in your copy constructor: this->occupied = 0;
66,148,559
66,150,164
How i make function like void loop and void setup in arduino?
I want make function like void loop or void setup like arduino main function which that function can input another execution code. unsigned long NOW; void setup() { } void loop() { void doEvery(2){ //do Every 2 second //Put Code that Execute every 2 second } void doEvery(4){ //do Every 4 second //Pu...
Taking THIS as initial idea: unsigned long previousMillis2 = 0, previousMillis100 = 0; void setup() { } void loop() { unsigned long currentMillis = millis(); //doEvery 2 if (currentMillis - previousMillis2 >= 2) { previousMillis2 = currentMillis; //stores last execution's timestamp //CODE EVERY 2 mill...
66,149,124
66,150,214
(Rust question) C++ double pointer to void meaning
I'm trying to work with active directory from Rust by following the c++ examples Microsoft posts for the ADSI API and the Windows-RS crate. I'm not understanding quite what is going on here: https://learn.microsoft.com/en-us/windows/win32/api/adshlp/nf-adshlp-adsopenobject They create an uninitialized pointer to IADs (...
Pointer parameters are often used in FFIs as a way to return data alongside the return value itself. The idea is that the pointer should point to some existing object that the call will populate with the result. Since the Windows API functions often return HRESULTs to indicate success and failure, they use pointers to ...
66,149,438
66,238,505
Using the UE4 headers/classes in a separate C++ project without the editor
I'm working on a C++ .dll plugin that gets passed UE4 classes like FName, UClass, FPlatformTime, etc for a game that I do not have the source code of. I would like to access the passed objects and view/modify their class members in my plugin. Adding UnrealEngine\UE_4.25\Engine\Source\Runtime\Core\Public as additional i...
Inside the UE4 solution, take a look at various programs, such as "BlankProgram" and "SlateViewer". These use UE4 modules and are built using UnrealBuildTool, but you could create your own program and only link to the UE4 modules that you need. This will effectively let you create a lightweight program without unneeded...
66,149,582
66,151,394
How would I use execute code to solve matrices while measuring the runtime of the code?
Preferably I would use C++ to execute the code, but I would be open to any suggestion for a better language for the situation. I essentially want to use Strassen's algorithm to solve matrices, and I want to know how I would solve a matrices and measure its runtime. # Version 3.6 import numpy as np def split(matrix): ...
Time measurement measuring of time depends on platform so what OS? On windows I would use Performance Counters. If you got access to x86 assembly you could also use RDTSC instruction but that needs some knowledge to use properly like setting affinity to single CPU, obtaining and stabilizing CPU frequency etc. The OS t...
66,149,774
66,149,897
Why am I getting this runtime error: member access within null pointer of type 'Solution::node' (solution.cpp)
I was solving a question on leetcode 1409. Queries on a Permutation With Key, but I am getting this runtime error I don't know why. I am unable to debug this error. Problem Statement:Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) accordi...
Your add_node function is bugged. Just take a deep breath and look at the code. add_node should allocate a node using new every time it is called. Ask yourself how many times and under what circumstances your version allocates a new node? I'm sure you can see that your code only allocates a new node when head equals NU...
66,150,303
66,150,338
C++ pure virtual class inside class template
I am trying to pass a pure virtual class(DataSource) into a custom datastruct(AVLTree) that is a member of a class (dataManager); the pure virtual class has both children RealTime and Simulation however I couldn't figure out how to instantiate both of them: AVLTree.h: public: T& info; AVLnode* left; ...
With &Data::RealTime(loc + name) you're attempting to take the address of a temporary object, one which will be destructed immediately (making that pointer worthless). In C++ you simply can't take the address of such object. What you need to do is to create an object using new, as in new Data::RealTime(loc + name) Don'...
66,150,316
66,150,534
Cheap Travel (466A) Problem from Codeforces
Full problem: (from https://codeforces.com/problemset/problem/466/A) Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need...
if (m * a <= b) covers the nonsensical case (in the real world) where the special ticket is at least as expensive as regular tickets for the same number of journeys. Eg a=1, b=10, m=5. Here m * a <= b so it's cheaper to buy the regular tickets. Having established that it might be worthwhile to buy the regular tickets y...
66,150,593
66,150,890
Performance of pow(x,3.0f) vs x*x*x?
The following program... int main() { float t = 0; for (int i = 0; i < 1'000'000'000; i++) { const float x = i; t += x*x*x; } return t; } ...takes about 900ms to complete on my machine. Whereas... #include <cmath> int main() { float t = 0; for (int i = 0; i < 1'000'000'000; i+...
The doc page about gcc builtins is explicit (emphasize mine): Built-in Function: double __builtin_powi (double, int) Returns the first argument raised to the power of the second. Unlike the pow function no guarantees about precision and rounding are made. Built-in Function: float __builtin_powif (float, int) Similar...
66,150,792
66,154,794
Remove extra whitespace from c++ issue
I have this code snippet from online. void ShortenSpace(string &s) { // n is length of the original string int n = s.length(); //pointer i to keep trackof next position and j to traverse int i = 0, j = -1; // flag that sets to true is space is found b...
Because it indiscriminately deletes the last character. The last conditional should check if the last character is a white space as well: // Trim string to result if (i <= 1 || s[i-1] != ' ') s.erase(s.begin() + i, s.end()); else s.erase(s.begin() + i - 1, s.end()); I corrected the comment as well, as it does ...
66,151,042
66,152,083
How to increment each printed row to the power 2 to the power of n and n-1 in C++?
Trying to write a program in C++ that prints rows of "*" based on the result of 2^n then after a certain number is entered decrease 2^n-1. For example any where between 0 and 6 (both of these being n) a row of stars is printed from *, **, **** and so forth. Then anything between 7 and 12 the number of stars decreases 2...
Ok so the problem is that you need a loop, i tried to not edit your variables this is the best i could do: #include <iostream> #include <cmath> using namespace std; int main() { int base = 2, exponent, result; char star = '*'; int aux=1; cout << "Enter a number between 0 and 12: "; cin >> exponent;...
66,151,081
66,151,424
error LNK2001: unresolved external symbol __CxxFrameHandler4 and __GSHandlerCheck_EH4
I'm trying to build a library and link it to an app. Library build is fine, but linking to the app throws these errors: clipper.lib(clipper.obj) : error LNK2001: unresolved external symbol __CxxFrameHandler4 clipper.lib(clipper.obj) : error LNK2001: unresolved external symbol __GSHandlerCheck_EH4 Cause According to...
As commented by @Tsyvarev , the errors got resolved by replacing cmake .. with: cmake -G "Visual Studio 15 2017 Win64" ..
66,151,600
66,151,629
Force compilation error on "0" argument (C++)
Can anybody tell me if there is a way to force a compilation error when a const wchar_t* function argument gets passed a 0 pointer? As example: void func(const wchar_t* a) { ... } int main() { ... func(0); // <- this should generate a compilation error ... } My intention here is not to skip any val...
You might add overload for std::nullptr_t: void func(std::nullptr_t) = delete; Or maybe a catch all one: template <typename T> void func(T) = delete;
66,151,769
66,152,343
Polymorphic r-value references?
If I wanted to store a polymorphic object in a class, my first thought would be to something like the following: struct Base { virtual void print() const { std::cout << "Base !"; } }; struct Derived: public Base { void print() const { std::cout << "Derived !"; } }; struct PolymorphicW...
std::move creates an rvalue reference to an existing lvalue, which marks it explicitly as ready to be moved from. You can initialize another rvalue reference from that, however you are not in the special lifetime-extension case for two reasons: It requires an actual rvalue (i.e. an object that was just constructed wit...
66,152,218
66,152,455
How to sort a 2d array in cpp by values of two columns?
I have a std::vector< std::vector<double> > array, the entries of which are 1 80 -0.15 -0.9 -0.15 0.6 0 -1.5 1 81 -0.15 -0.9 -0.15 0.7 0 -1.6 1 82 -0.15 -0.9 -0.15 0.8 0 -1.7 1 83 -0.15 -0.9 -0.15 0.9 0 -1.8 . . . 79 155 0.15 0.9 0.15 -0.9 0 1.8 79 156 0.15 0.9 0.15 -0.8 0 1.7 79 157 0.15 0.9 0.15 -0.7 0 1.6 79 ...
Your sort criteria looks off. I think you need something more like this: auto sortfunc = [](std::vector<double> const& va, std::vector<double> const& vb) { if(va[7] == vb[7]) return va[6] < vb[6]; return va[7] < vb[7]; }; Sort by the first column unless the first column is equal in which case sort acc...
66,152,815
66,157,097
Failed to create GLFW window?
I tried to create a window with the simplest code possible: #include <stdio.h> #include <stdlib.h> #include <GL/glew.h> // Always include it before glfw.h #include <GLFW/glfw3.h> #include <glm/glm.hpp> int main(void) { glfwInit(); glfwWindowHint(GLFW_VERSION_MAJOR, 3); // OpenGL 3.3 glfwWindowHint(GLFW_VE...
GLFW_VERSION_MAJOR & GLFW_VERSION_MINOR are not valid arguments to glfwWindowHint: glfwWindowHint(GLFW_VERSION_MAJOR, 3); // OpenGL 3.3 ^^^^^^^^^^^^^^^^^^ nope glfwWindowHint(GLFW_VERSION_MINOR, 3); ^^^^^^^^^^^^^^^^^^ also nope Use GLFW_CONTEXT_VERSION_MAJOR & GLFW_CONTEXT_VERSION_MINOR i...
66,153,037
66,153,350
c++ error: call to 'g' is ambiguous. By reference and regular function argument
In this code I want to call second function (with reference argument). How I can do this? This is even possible? void g(int){ std::cout << 1; } void g(int&){ std::cout << 2; } int main() { int i = 42; g( i ); // want to output "2" }
Do you want to have 1 when calling g(42) and 2 when calling g(i)? Then you should change the prototype of the first function to get a const int &: #include <iostream> void g(const int&){ std::cout << 1; } void g(int&){ std::cout << 2; } int main() { int i = 42; g( i ); // want to output "2" } For g(i) the int & ...
66,153,071
66,206,091
How to create a Gaussian kernel of arbitrary width?
How to create a Gaussian kernel by only specifying its width w (3,5,7,9...), and without specifying its variance sigma? In other word, how to adapt sigma so that the Gaussian distribution 'fits well' w? I would be interested in a C++ implementation: void create_gaussian_kernel(int w, std::vector<std::vector<float>>& ke...
I found a simple (arbitrary) relation between sigma and w. I want the next value outside the kernel (along one axis) below a very small value epsilon: exp( - (half_width + 1)^2 / (2 * sigma^2) ) < epsilon with half_width the kernel 'half width'. The result is sigma^2 = - (half_width + 1)^2 / (2 * log(epsilon)) I use...
66,153,083
66,154,230
Access templated "using" in templated parent class
I have a class hierarchy like this: /* Base templated interface class */ template <class T> class InterfaceClass { public: // Normal using sentence using InnerType1 = SomeClass<T>; // HERE1: Templated using sentence that I want to use in other places template<typename SomeType> using TplInnerType...
You should drop typename: template <typename T> class Class : public InterfaceClass<T> { public: using BaseType = InterfaceClass<T>; using typename BaseType::InnerType1; using BaseType::TplInnerType; }; Demo
66,153,505
66,153,764
Deleting all lvalue conversion operators
I want to avoid all lvalue conversions from a type to another type: struct A {}; struct T { A a; operator A() { return a; } //operator A&() = delete; how to delete lvalue conversions to A? }; void bar(A) {} void foo(const A&) {} void foo2(A&) {} int main() { T t; bar(t); // fine foo(t); //...
You might do struct T { A a; operator A() { return a; } template <typename T> operator const T&() = delete; }; Demo
66,153,694
66,158,861
Parsing ipv4 address with Boost Spirit X3
X3 newbie here. Two questions: Why the result contains repeated "1,1,1"s, like so: <attributes>[[1, 9, 2, ., 1, 6, 8, ., 1, 1, 1, ., 1, 1, 1], [8, 0]]</attributes>, when I expect something like this <attributes>[[1, 9, 2, ., 1, 6, 8, ., 1, ., 1], [8, 0]]</attributes> What would be not-so-awkward way to define a single...
Q. 1. Why the result contains repeated "1,1,1"s, like so: [[1, 9, 2, ., 1, 6, 8, ., 1, 1, 1, ., 1, 1, 1], [8, 0]], when I expect something like this [[1, 9, 2, ., 1, 6, 8, ., 1, ., 1], [8, 0]] It's been 7 days since the last time people ran into this pitfall: It's the age-old "container attributes aren't atomic" pit...
66,154,253
66,154,381
vector resize seems to require default constructor in C++ >= 11
I have the following test code where I create a std::vector of class foo and later resize it. #include <iostream> #include <vector> #include <algorithm> class foo { public: foo(int n) : num(n) {} //foo() : num(42) {} ~foo () { std::cout << "destructor" << std::endl; } void print() { std::cout << num <<...
Yes and no. The overload that you are currently using does. There is however a second overload where you can supply a value for the new elements - which is needed even if you know that you'll be resizing it to a smaller size. constexpr void resize( size_type count, const value_type& value ); So either: v.resize(2, 0);...
66,155,377
66,161,078
Improving a solution
The description of a task goes like this: We have n numbers, and we have to find quantity of unique sums of all the pairs in the array. For example: 3 2 5 6 3 The sums of all the pairs(non-repeated) are 5 9 8 6 8 7 5 11 9 8 Unique are 5 9 8 6 7 11 Therefore output is 6 I have come up with this really primitive...
As mentioned above what you need it is difficult to do this without computing the sum of all pairs, so I am not going to handle that, I am just going to advise about efficient data structures. Analysis of your solution Your code adds everything in advance O(n^2) then sorts O(n^2 log(n)), then remove duplicates. But sin...
66,155,449
66,199,158
Min sum of distances (absolute differences) between array element and set of k array elements
I need to find the minimum sum of the distances between an element in the array and the set of k-elements of the array, not including that index. For example: arr = {5, 7, 4, 9} k = 2 min_sum(5) = |5-4| + |5-7| = 3 min_sum(7) = |7-9| + |7-5| = 4 min_sum(4) = |4-5| + |4-7| = 4 min_sum(9) = |9-7| + |9-5| = 6 So, a naive ...
We can solve this problem efficiently by taking the sliding window approach. It seems safe to assume that there are no duplicates in the array. If it contains duplicates, then we can simply discard them with the help of HashSet. The next step is to sort the array to guarantee that the closest k elements will be within ...
66,155,574
66,158,060
Problem using boost::object_pool boost version 1.56 with visual studio 2019
I am trying to convert boost::object_pool usage on my old project to new visual studio 2019 project, I am using boost version 1.56 ObjectPool.h class BOOST_OBJECT_POOL_CHECKER { boost::object_pool< T > m_sObjectPool; template <class Arg1> T* contruct(Arg1& sArg1) { T* temp = m_sObjectPool.construct(sArg...
Frankly, this code cannot have compiled under any compiler. Note: I'm ignoring numerous typos, omitted semi-colons, omitted template declarators, typedefs and access specifiers to focus on the real issues. You're passing *this which is Material&. However, the contruct [sic] function takes a MaterialServer*. So, in fa...
66,155,648
66,156,893
Parameter pack extension for variable number of std::pair elements does not work as expected
My use-case: I want to build a constexpr map with constant content and size declared at compile time. I'm using C++ 14. This is my current basic approach on that container: template <typename KeyType, typename ValueType, size_t size> struct ConstantMap { using PairType = std::pair<KeyType, ValueType>; using St...
Maybe passing through an old C-style array? template <typename KT, typename VT, std::size_t Dim, std::size_t ... Is> constexpr auto mcp_helper (std::pair<KT, VT> const (& arr)[Dim], std::index_sequence<Is...>) { return ConstantMap<KT, VT, Dim>{{ arr[Is]... }}; } template <typename KT, typen...
66,155,878
66,155,947
Is there a workaround for template template arguments being invisible?
Consider the following code: template<typename... Args1> constexpr size_t direct = sizeof... (Args1); template<template<typename... Args1> typename A1> constexpr size_t nested = sizeof... (Args1); // compile error ☹️ Nested line does not compile since (I presume) Args1 is a nested argument. Is there a way to work a...
You can write a primary variable template, and then specialize the variable template for template template parameters. This allows you to explicitly name the template parameters of the template template parameter separately: template<typename ...> constexpr size_t nested = -1; // any value will do, ...
66,155,890
66,155,922
C++: How to create 2 classes which use each other
This question gives answer only when the classes use each other as the member types, but not when they use the functions of each other. How to do it in the following example? Bar is a singleton container which handles the operations done on all Bars. // Foo.h #include "Bar.h" class Foo { public: Foo() { Bar::get_...
Forward declaration will do the trick, forward decalre in .h and include the header in cpp. // Bar.h //#include "Foo.h" #include <vector> class Foo; // <---- this one class Bar { public: Bar(const Bar &other) = delete; void operator=(const Bar &) = delete; static Bar *get_instance(); // move defin...
66,156,300
66,157,757
Rotation of the matrices parallel to the global axes
Now I'm doing the following transformations on the object: Rotate along the X-axis Rotate along the Y-axis Moving along the Z axis by -2.5 //create model matrix model_matrix = glm::mat4(1.0f); //create view matrix view_matrix = glm::mat4(1.0f); //create projection matrix projection_matrix = glm::mat4(1.0f); //settin...
Why is this happening [...] The matrix multiplication is not Commutative. The order matters. If you want to rotate the object step by step, based on the previous rotations, you must store the model matrix and apply the new rotations to the stored model matrix. You need to keep the model matrix beyond frames instead o...
66,156,425
66,156,532
C++ Class object as argument of function
I have two functions in two different files in file A.cpp void func(int x, A a){...} in file B.cpp void func(int x, B b){...} These two functions do pretty much the same thing, so I would like to merge them, i.e., create a function in file C.cpp who will look like this void func(int x, AorB c){...}. I don't want my fun...
Templates could help here, if the processing is the same: template <class X> void func(int x, X b) { ... } But beware, templates have to be resolved at compile time, so they have to reside in header files and not in separate compilation units.
66,157,098
66,157,713
Byte packing for WinAPI STARTUPINFO 64 bit (QB64)
I am programming in QB64, which is a programming language that allows for QBASIC-like syntax, and is translated into C++ code and compiled. If we want to use a struct in our code, then we have to declare it and create it manually. In 32-bit, no problem, as it matches the WinAPI MSDN pages and will almost always work. F...
The field sizes and positions for the STARTUPINFOW structure in 32-bit and 64-bit builds are summarized below. (Note that these sizes and offsets are the same for the equivalent STARTUPINFOA version of the structure, used for non-Unicode builds.) 32-bit Windows (note that no padding is required – almost certainly by de...