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,044,342
65,009,483
OpenCV Tracker property access fails with SEGFAULT on ARM, but works in X86_64
I'm trying to port my application to a raspberry pi 4, but had no luck with trackers. I basically use a tracker as a class member. While this works on my Ubuntu machine, it causes a segmentation fault in raspberry. I reproduced the problem with this minimal working example (it does not make any sense, but depict exactl...
It was a bug in Opencv 4.3.0, I opened an issue here but it's still unanswered, I don't know if it's been fixed. Anyway same code works in OpenCV 3.4.10 and fails in 4.1.2 confirming my idea, something should have broke from version 4. EDIT As of April 23, 2021 bug is still there with version 4.5.2, I opened a new issu...
62,044,565
62,045,508
How to comprephend these ways could eliminate most need for explicit std::move? Could anybody make it clear by some simple examples?
How to comprephend these ways(including not making variables’ scopes needlessly large, writing short functions that return values, returning local variables) could eliminate most need for explicit std::move? Could anybody make it clear by some simple examples?I am a novice in C++.I would be grateful for any hint on thi...
By creating sub-functions, you might change void consume(std::vector<int>&&); void foo() { std::vector<int> v; for (int i = 0; i != 10; ++i) { v.push_back(i); } consume(std::move(v)); } by void consume(std::vector<int>&&); std::vector<int> make_vector() { std::vector<int> v; for (int...
62,044,577
62,044,739
How to initialize the variable
hello i want to build a programme that finds even and odd number from given two numbers. when i build it it says succeed but still it says warning C4700: uninitialized local variable 'number' used when i debug it debug error appeared how to solve this? and can anybody tell me the reason it happens? thank you so much ...
The reason your program gives error is because you haven't initialized your variable number. I have corrected that. There were few other bugs too which would have given wrong output.I have corrected and reformatted your code a bit - #include<stdio.h> #include <iostream> using namespace std; int main(){ int numbe...
62,044,850
62,046,098
Event system: Inheritance with type-casting or unions
I am currently working on an event system for my game engine. I've thought about two ways I could implement it: 1. With inheritance: class Event { //... Type type; // Event type stored using an enum class } class KeyEvent : public Event { int keyCode = 0; //... } 2. With unions: class Event { stru...
Event seems more data-centric than behavior-centric, so I would choose std::variant: using Event = std::variant<KeyEvent, MouseButtonEvent/*, ...*/>; // or using Event = std::variant<std::unique_ptr<KeyEvent>, std::unique_ptr<MouseButtonEvent>/*, ...*/>; // In you are concerned to the size... at the price of extra indi...
62,044,979
62,045,014
C++ delete pointer allocated twice
I am trying to understand more about c++ pointers and freeing memory. Let's say we have the following piece of code int main{ int * A = new int[4]; int * B = new int[4]; A = B; delete[] A; delete[] B; return 0; } A is pointing to a new created pointer, whereas B is pointing to another one,so we have a t...
Therefore what happens to the other pointer in this case? It is lost. You dropped the last reference to the array A was pointing to (A and B are not pointing to pointers. They are pointers and they do point at the first element of the arrays, ie ints, respectively). And how can we delete it? You cannot. The memory ...
62,045,025
62,049,474
How to declare and instantiate class instances as class attributes
I'm designing an Arduino project that makes use of multiple sensors so I need to create classes to abstract each sensor functionality in order to make it scalable and easy to maintain. I should say that I'm not very experienced in C++ but I'm kind of fluent in Java and some patterns and techniques that can be applied t...
Global variables are vile. Keep them to a minimum. I find it cleanest to keep the entire system in a class, so: C++11 class MySystem { constexpr uint8_t lc_dout = 4; constexpr uint8_t lc_sck = 5; HX711_ADC loadCell{lc_dout, lc_sck}; //... public: MySystem() { /* initialization - additional */ } void loop() ...
62,045,704
62,047,765
Can C++ evaluation order optimizations imply using diferent cores for diferent operands?
C++ expressions do not define an order of evaluation for the operands. This is for the sake of potential optimizations. for the very simple case : int i = f() + g(); Does such optimizations include evaluating f() and g() on different cores ? and if such optimizations are possible, does it mean that the order of evalua...
Does such optimizations include evaluating f() and g() on different cores? Yes, even if I doubt it was the case in practice: starting thread is costly threading code has constraint and data race and other threading issue should not be introduced More probable optimization is with inlining and reordering instruction...
62,045,915
62,045,997
Subclassing std::chrono::duration
I have a piece of code where std::chrono::duration<int64_t, std::milli> is subclassed, and used to create a std::chrono::time_point, like so: #include <chrono> class my_duration : public std::chrono::duration<int64_t, std::milli> { /* snip */ }; int main() { typedef std::chrono::time_point< std::chrono::system_c...
std::time_point has always required that the duration type be a specialization of std::duration. If it isn't, then the program is ill-formed (aka: compile error). This may just be the first time GCC implemented that requirement. Deriving from duration doesn't really serve any useful purpose.
62,046,013
62,046,130
Find the missing number using XOR logic
Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found. I have seen that it can be solved using some interesting property of XOR. The interesting property is Assume a1 ^ a2 ^ a3 ^ …^ an = x and a1 ^ a2 ^ a3 ^ …^ an-1 = y Then x ^ y = an I...
a ^ a is by definition 0, and in your case you're calculating: x: a[0] ^ a[1] ^ a[2] ^ .. ^ a[n-1] ^ a[n] ^ y: a[0] ^ a[1] ^ a[2] ^ .. ^ a[n-1] ======================================= 0 ^ 0 ^ 0 ^ .. ^ 0 ^ a[n] = a[n]
62,046,351
62,046,605
Overflow in Lambda function in C++
I was solving a question on leetcode. The question is, Given a list of non-negative integers, arrange them such that they form the largest number. I have got the algorithm to write the comparator function and sort the list based on that. I had written the following, string largestNumber(vector<int>& nums) { auto c...
If you open the documentation on std::sort, you'll see following: template< class RandomIt, class Compare > void sort( RandomIt first, RandomIt last, Compare comp ); ... Type requirements Compare must meet the requirements of Compare. And the Compare requirements say: Establishes strict weak ordering relation wit...
62,046,647
62,088,834
Unreal Engine C++ Spawn Actor Bug
I have a simple Puzzle Game. It is a combination of multiple simple games. Since those games are rotated during the game, everything is spawned dynamically. I have a problem with SpawnActor. There is a class called XGame(AActor) spawned by level manager(APawn) . It is responsible for spawning actors for this specific X...
I manage to get it working correctly by changing base class of Stick, Ball and Circle to AActor. Because of the fact that Character classes automatically generates a capsule component. They were colliding and spawned characters are moved by 68 each time (default capsule movement radius of character is 34.0).
62,046,921
62,050,836
PPM wrong color display
I get weird results when displaying a PPM: pixeldisplay (this is actually an upscaled PNG) And here's what the file looks like: textdisplay The dimensions are fine (10 rows, 8 columns), just the colors are wrong (or am I wrong?). As it says in the 3rd line of the file, I want to use a value from 0 to 255 per channel. U...
This document: http://netpbm.sourceforge.net/doc/ppm.html describes the PPM image format. When the "magic" value P6 is found at the beginning of the file, the color of the pixels is stored as binary data. Quoting the previously mentioned document (emphasis mine): [...] A raster of Height rows, in order from top to bot...
62,047,185
62,047,914
How are lambda captures initialized in case of nested lambdas?
Okay, so this is right off the bat from [expr.prim.lambda]p16 in n3337.pdf. Below code is given as an example: int a = 1, b = 1, c = 1; auto m1 = [a, &b, &c]() mutable { auto m2 = [a, b, &c]() mutable { std::cout << a << b << c; // Shouldn't this print 113 or 133? a = 4; b = 4; c = 4; };...
First, note that whether a capture is by copy or by reference depends only on the lambda expression's own lambda-introducer (the initial [] part), per C++11 [expr.prim.lambda] paragraph 14 (or C++17 [expr.prim.lambda.capture] paragraph 10). The pieces you quoted from C++11 [expr.prim.lambda]/16 (or the same in C++17 [e...
62,047,324
62,064,206
Multi-dimensional datasets in C++: cleanest approach to go from a std::vector of 2D data, to a 2D grid of std::vectors?
Context: I've been processing scientific satellite images, currently keeping the individual end results at each timestamp as cv::Mat_<double>, which can for instance be stored in a std::container of images, such as a std::vector<cv::Mat_<double>>. The issue: I would now like to study the physical properties of each ind...
You could try something like std::views::transform (or it's precursors, range-v3 and boost range adaptors), with function objects to lookup each pixel [x, y](cv::Mat_<double> & mat) -> double & { return mat[y][x]; } However you should definitely profile if that is worthwhile vs copying, as I expect the cache locality ...
62,047,784
62,047,909
Moving members of class passed as a const reference argument
Considering: template <typename... Args> ResourceHolder& operator+=(const ResourceInserter<Key, Args...>& inserter) { if constexpr (sizeof...(Args) == 0) { insert(std::move(inserter.key), std::move(inserter.fileName)); } else { insert(std::move(inserter.key), std::...
Moving const objects is generally a simple copy (unless you overload Object(const Object&&)) so your usage of std::move seems useless. If the members of ResourceInserter are (non-const) references, your const ResourceInserter& is "misleading", and your move will actually happen.
62,048,085
62,048,434
Use of weak_ptr with cyclic references
So I'm having quite a hard time understanding why we have to use weak_ptr especially with cyclic reference problems, consider this code: class B; //forward declaration class A { shared_ptr<B> b_ptr; public: void set_B(shared_ptr<B>& b) { b_ptr = b; } A() { cout << "A constructor" << endl; }...
With all std::shared_ptr, you have: int main() { std::shared_ptr<A> a = std::make_shared<A>(); // ref_count_a = 1 std::shared_ptr<B> b = std::make_shared<B>(); // ref_count_b = 1 a->set_B(b); // ref_count_b = 2 b->set_A(a); // ref_count_a = 2 } // ref_count_a = 1 && ref_count_b = 1 // memleak due to the...
62,048,659
62,048,904
Can't stop recursion, while iterating a template type list
So I have a template type list like this : template <typename... Types> struct type_list { }; I've made an accessor function like this : template<class TypeList, size_t ElementIndex> struct at; template <template<typename...> class TypeList, typename Head, typename... OtherTypes, size_t ElementIndex> struct at< Typ...
The problem is when you do this: if_else_t < ElementIndex == 0, Head, typename at< TypeList<OtherTypes...>, ElementIndex - 1 >::type >; Even if ElementIndex is 0, the other two types still have to be evaluated to be passed to if_else_t (thus triggering the static_assert). You fix it by using specialisation instead:...
62,048,688
62,053,162
C++ Microsoft Visual Studio 2017 best and easiest way to detect memory leaks?
Currently I have a solution but I am not sure if it's alright in every scenario. Can I check if there is any memory leaks in the program with this solution? If anyone can offer a better solution please do not hesitate to share the answer. Thanks! My example code here: int *array = new int[5]; delete[] array; //so no me...
I found an other solution - Can someone agree with it? (source: https://learn.microsoft.com/en-us/visualstudio/profiling/memory-usage?view=vs-2017 ) 1st step - create 3 breakpoints. !!! The last breakpoint should have put after the return - not in line! 2nd step - Start debugging and creating snapshots. (Diagnostic To...
62,048,793
62,056,813
C++ copy list of chars to string exactly without ignoring multiple whitespace
I have a list of chars, L: {'h','e','l','l','o',' ', ' ',' ', 'm', 'y', ' ', ' ',' ', 'n','a','m','e'}; I want to copy it to a string. I want to maintain triple spaces and get a string S below: "hello my name" I tried this: string S(L.begin(), L.end()); but it somehow removes triple spaces and gives me single ...
This seems to work fine and doesn't ignore the spaces: string convertToString(list<char> lst, int size) { string s = ""; for (auto const& i : lst) { s = s + i; } return s; } Running this like... list<char> L = {'h', 'e', 'l', 'l', 'o', ' ', ' ', ' ', 'm', 'y', ' ', ' ', ' ', 'n', 'a', 'm',...
62,048,892
62,090,217
PX Transform Routine compile issues
I have a transformer routine written in C++ that is set to clear all whitespace and map to a value if the input string is either null or empty. The c++ code compiles and has tested properly, but I am having trouble getting the routine to work in Datastage. As per instructions, I have copied the exact compiler options t...
After a day or two of multiple attempts to try different compile and code approaches I found the solution to my problem. The below code was throwing a segmentation fault when passed a null column. Which makes sense in retrospect. if (InStr[0] == '\0') It has been corrected to the below and now everything works properl...
62,049,095
62,049,232
Specializing only one method of a class template
I have a class template that works correctly for all possible types T1, T2. template <typename T1, typename T2> class Basic { int a; float b; public: void foo(T1 t1, T2 t2) { // use a, b, t1, t2 } }; However, there is one case when T2 is char, and I expect foo to behave differently. So I tried...
You can use std::is_same to do something else in foo, when T2 is char: void foo(T1 t1, T2 t2) { if (std::is_same<T2, char>::value) std::cout << "char"; else std::cout << "not char"; } You don't need a full specialization of Basic for this, or even a specialization for foo. Here's a demo. From c++17, yo...
62,049,311
62,049,971
How do I set up this folder structure in CMake?
I'm trying to switch from an Xcode project to a CMake-based project. (Xcode automated all the project config stuff). I have this project setup: game/ (Includes the core utils used by the client and the server. Has libraries -llua, -lbullet, etc.) | util.cpp | CMakeLists.txt game-client/ (The client. Has libraries -lglf...
Here's how I would set such project: ./CMakeLists.txt: cmake_minimum_required(VERSION 3.0.2) project(my_game) add_subdirectory(game) add_subdirectory(game-client) add_subdirectory(game-server) Note that it is crucial that sub-directories should be added in reverse dependency order. E.g. game-server depends on game, s...
62,049,646
62,049,801
Is there a std::set function for determining the largest element that does not exceed a number x?
I read online that an std::set has useful member functions that can help search for elements. Specifically, std::set::lower_bound, which returns an iterator to the smallest element that is >= a number x, and std::set::upper_bound, which returns an iterator to the smallest element that exceeds x. However, I want to find...
Decrement the iterator returned from upper_bound: std::set<int> s; s.insert(3); s.insert(4); s.insert(5); s.insert(7); auto itor = s.upper_bound(6); if (itor != s.begin()) { --itor; std::cout << *itor << std::endl; } The above should print "5"
62,050,625
62,050,736
Why does a const std::vector apply const to the contained objects?
I know that const std::vector<int> applies the const to the ints, too, (e.g. begin() const will return a const_iterator). I am curious as to the reason for this. In my mind it would make more sense to apply the const only to the vector (e.g. no resizing), and leave contained object's constness to them (e.g. std::vector...
Const-ness in C++ is a semantic concept that means "the observable state of this object cannot be changed using this name." In the case of a vector, its contents are considered part of its observable state, so if the vector is const then its elements necessarily are also const. This also means you can give some other ...
62,050,886
62,053,005
How to open system menu in Notepad from separate program in C++?
I am trying to make the system menu in Notepad popup as seen here: It doesn't have to be the Help menu; any menu will do. This code brings the window to the foreground and logs 0x204a4 0x2bd041f 0 but doesn't open the menu. #include <iostream> #include <windows.h> int main() { HWND hWnd = FindWindow(NULL, "Untitl...
#ifndef UNICODE #define UNICODE #endif #include <windows.h> LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR pCmdLine, int nCmdShow) { const wchar_t CLASS_NAME[] = L"My Window Class"; WNDCLASS wc = {}; wc.lpfnWndPro...
62,051,199
62,054,290
Lock-free stack pop implementation in C++
In C++ Concurrency in Action, 2e, The author describes a lock-free thread safe linked list implementation. Right now, he is describing the pop() method and how to safely delete the nodes in a sort of "garbage-collector" like method to make sure that no other threads called pop on the same instance. Here is some of that...
The thread that calls try_reclaim has just removed old_head from the stack. The class ensures that any other uses of old_head must be inside pop calls from other threads, so if the thread discovers that there are no other concurrent calls, then it knows that it is the exclusive holder of the old_head pointer. Then, as...
62,051,249
62,051,505
What are the rules for when each user defined conversion method is called implicity?
A little context. In the world of classes, implicit conversions can be controlled by means of three member functions: Single-argument constructors: allow implicit conversion from a particular type to initialize an object. Assignment operator: allow implicit conversion from a particular type on assignments. Type-cast...
One of those, the assignment operator, does not implement a conversion. You simply modify the state of one type of object based on data from an object of another type. When does one override the others? When one is a better match by overload resolution. For example, if the source object is non-const, and converting c...
62,051,260
62,051,630
Operator overloads within a class heirarchy
Apologies if this has been asked and answered before, but I've been searching for an understandable solution now for hours with no joy. I'm trying to implement a simple class hierarchy with operator overloads defined within the base class (since these will not differ between the various derived classes). However, sinc...
Your comment indicates "in the implementation file" for the template, which is likely the cause of your issue. Function template declarations (e.g. T operator+(const T&, const&); declare the symbols that must be linked against -- but it requires an instantiation of that template somewhere. Simply defining the template...
62,051,399
62,051,750
How to detect a keystroke in the Window Procedure method?
I am a bit new to c++ and I am trying to create a gui application to tell me whether my caps lock is active or not. I have already set up the basic UI and it starts up according to plan (by showing me my lock state via colors) but I cannot manage to change the window color at runtime. here's my code : LRESULT CALLBACK ...
Don't call (Begin/End)Paint() in your WM_KEYUP handler, and don't call GetKeyState() in your WM_PAINT handler. Have WM_KEY(DOWN|UP) save the desired color to a variable and then call InvalidateRect() whenver that variable changes value to trigger a repaint of your window. Let WM_PAINT draw the window using the current ...
62,051,879
62,054,307
Why is the calculation of 1000 factorial so fast in Lisp (and shows correct result)?
I have tried to implement naive calculation of the factorial in Lisp. (defun factorial (n) (if (equal n 1) 1 (* n (factorial (- n 1))))) The code works for small numbers (< 10) as one would expect. However, I have been very surprised it also works for much higher numbers (e.g 1000) and the result is calculat...
Common Lisp has bignums and tries to use them when necessary (and unless told otherwise) so that results are mathematically useful for most users: non-computing people usually do not expect modulo arithmetics over powers of 2. You could have a look at how bignums are implemented (e.g. sbcl) to better understand how the...
62,051,936
62,052,002
Local variables name collision
If I define one variable in the enclosing block and another one with the same name in the nested block, how can I access a variable from the enclosing block inside the nested block? int main () { int i = 0; { int i; i = 10; } cout << i; // prints 0 }
You've "shadowed" the earlier definition, so it's basically gone. If you need access to it, pick a different name. As far as the compiler is concerned, within that inner block there's only one i and it has no idea about the other i that it replaced. Either give it a better name: int i = 0; { int ii; i = 10; } c...
62,052,408
62,052,439
How do I permanantly add a path to the g++ compiler?
I'm currently using a non standard c++ library in my programs, but linking the library everytime I run the code is getting annoying. Right now I'm using c++ file.cpp -o file -L/path/to/lib -lLibName I tried the following: CPLUS_INCLUDE_PATH=/path/to/lib export CPLUS_INCLUDE_PATH but it neither solved the issue nor ga...
A better option would be use a makefile and run make. You can edit the makefile to add the necessary compiler and linker options. GNU Make uses many implicit variables. For your use case, the contents of the Makefile can be as simple as: CXXFLAGS = -Wall LDFLAGS = -L/path/to/lib -lLibName
62,052,767
62,285,728
VS2019 : resource file error: Neutral (Default) (unknown sub-lang: 0x8)
I'm following this tutorial to get started with win32api GUI programming. My VS2019 is completely standard but when i try to add a resource file i get the error: A resource in this file uses an unknown language: Neutral (Default) (unknown sub-lang: 0x8). Unable to open this file. I found something similar posted befor...
As suggested by Jeaninez setting my Window display language to English (United States) fixed the problem. This seems to align with the default settings in Visual Studio 2019.
62,052,808
62,053,069
Partial-compare-and-full-swap for atomic values
The problem is as follows. Given a POD object that has two parts: index and data. I want to perform an atomic conditional exchange operation over it with a condition that checks equality for the index only. Something like this: struct Data { size_t m_index; char m_data; }; std::atomic<Data> dd; // some initialization D...
I think you have to do a load, then your custom condition, then a compare-and-swap, where the comparison is that the current value is totally equal to the read value. If the last step fails, loop. template<class T, class F> bool swap_if(std::atomic<T>& atomic, T desired, F&& condition) { for (;;) { T data =...
62,053,112
62,053,149
Inherited class destructor
I have a template class like this (with dynamic data): template <class T> class TemplateClass : public BaseClass { public: ... protected: vector<T> data; ... } It's derived from a BaseClass because in another container class I must have all this template classes within the same vector: class Container{ public: ... pro...
You need make the destructor of BaseClass a virtual destructor. class BaseClass { virtual ~BaseClass() {} }; With that change, the destructor of TemplateClass will be called when you delete the objects in Container::elements. In the destructor of TemplateClass, you can delete the dynamically allocated memory.
62,053,888
62,054,129
SFINAE based traits implementation issue with function template overload
I'm learning aboiut SFINAE and traits and I know that I can define SFINAE-baed traits (traits that use SFINAE in their implementation). A classic implementation of a trait that detects if a type is default constructible is: template <typename T> struct IsDefaultConstructibleH { private: template <typename U, typena...
Reference types as non-type template parameters must be the name of an object with linkage (usually a global variable). See https://en.cppreference.com/w/cpp/language/template_parameters#Template_non-type_arguments. It specifically cannot be a temporary. Thus const U& = U() is always invalid in a template, as U() isn't...
62,054,785
62,069,795
google test PrintTo for std::set<std::string>
In the google test Advanced documentation they say to write PrintTo in the same namespace that defines the value to be printed, which is great if it's your own class in your own namespace, but if it's std::set you aren't supposed to add new members to namespace std. So how do you customize the PrintTo behavior for std:...
What works is to define PrintTo in namespace testing::internal. This still feels a little dirty to me. Presumably the internal namespace is so that google test can change whatever implementation details they like in there without regard to backwards compatibility. At least it doesn't result in undefined behavior as ...
62,055,040
62,187,108
Problem in debugging templates. Build fails specifically for Linux GCC 7, GCC 6, GCC 5, GCC 4.9 error: template argument 1 is invalid
My Travis is only failing for Linux GCC 7, GCC 6, GCC 5, GCC 4.9 with error libs/astronomy/test/coordinate/equatorial_coord.cpp:22:57: error: template argument 1 is invalid RightAscension<double, quantity<bud::plane_angle>> ^ libs/astronomy/test/coordina...
There are multiple definitions of namespace bud = boost::units::degree; in the project which is causing the problem. Removing it from Equatorial_coord.hpp would do the magic for you.
62,055,109
62,055,627
C++: Template Template Member of a Template Parameter as a Parameter to a Template Class Expecting a Template Template parameter
First of all, apologies for the horrible title. I was experimenting with the C++20 is_detected functionality. is_detected basically takes two template parameters, one is a higher-order type which performs checking and the other one is the type to be checked. I ran into problems in the following scenario: #include <stdi...
Starting with C++17, you do not need the template keyword between a :: and a member template specialization name in certain contexts that can only name a type, including the typename-specifier syntax, which is used in the LocalChecker alias template. So clang and MSVC are wrong to reject that line without the template,...
62,055,273
62,055,933
Google Benchmark, how to call code only once?
I have a code snippet I need to benchmark composed of 2 parts, first the state needs to be set exactly once, next I need to actually benchmark a function. My code looks like this: static void BM_LoopTime(benchmark::State& state) { MasterEngine engine; for (auto _ : state) { engine.LoopOnce(); ...
This is a work around that I found that's good enough for my use case but I am still looking for better solutions: class MyFixture : public benchmark::Fixture { public: std::unique_ptr<MasterEngine> engine; void SetUp(const ::benchmark::State& state) { if(engine.get() == nullptr) engi...
62,055,599
62,055,787
Insert in unordered map when expanding a macro in global scope
I have a macro that creates functions which are then called from an executable via the function name in command line arguments. A minimal example is: #include <iostream> #define MAKE_FUNCTION(func_name, custom_message) \ void func_name(){std::cout << #custom_message << std::endl;} MAKE_FUNCTION(func_foo, "foo called"...
Hideous as it looks you could try do this, but I'm pretty sure it is afflicted by static-initialization ordering, which wouldn't be good: #include <iostream> #include <unordered_map> #include <string> static std::unordered_map<std::string, std::function<void()> > global_map; class AddNameToMap { public: template<...
62,055,879
62,056,073
Is the number of swap function calls and the number of swaps done while selection sort the same thing?
I know that for n elements, in selection sort: Best cases: 1 swap done. Worst cases: n-1 swaps done. Average cases: (n-1)/2 swaps done. So, if i were to say that the number of times the swap function has been called is same as the number of swaps done in 3 different cases, would I be correct?
Well, for a start, I'm not sure why the minimum swap count would be one. For an array that's already sorted, it should be zero. Any half-decent algorithm would detect that the fact that the current smallest item in the unsorted section was already at the right place, forget the swap and just move the boundary between t...
62,055,890
62,055,960
Does cudaMalloc() initialize the array to 0?
Or do I need to perform cudaMemset() if I want to make sure the array contains all 0? I can't find it in the documentation. Thank you.
The cudaMalloc documentation says: Allocates size bytes of linear memory on the device and returns in *devPtr a pointer to the allocated memory. The allocated memory is suitably aligned for any kind of variable. The memory is not cleared. So, you will need cudaMemset to initialize the memory.
62,055,928
62,074,259
Add image to button when pressed
button1_on_image = Gtk::manage(new Gtk::Image{"button1_on.png"}); // Load icon button1_off_image = Gtk::manage(new Gtk::Image{"button1_off.png"}); // images button1 = Gtk::manage(new Gtk::ToolButton{*button1_off_image}); // Create button button1->set_tooltip_markup("Select one stick"); // with ima...
Here is a code snippet that does what you want: When the window is initially created, the button is "Off". When the button is clicked, the button changes state to "On". Note that this is a minimal example, so clicking again on the button will not change its state back to "On", but I will leave this part to you, if it...
62,055,966
62,056,978
How to assign values to the data elements of a structure
I have a structure struct MyStruct { int intValue1; float floatValue2; std::string stringValue3; } Structure; Now based on the value input of two strings, I want to assign values to the data elements of the structure: std::string varName = "intValue1"; std::string varValue = "5"; So based on the two strin...
Yes, it is possible, using stringizing operator . Here is a minimalistic example: #include <string> #include <iostream> #define NAME_OF( v ) #v struct MyStruct { int intValue1; float floatValue2; std::string stringValue3; } Structure; int main() { MyStruct A; std::string varName = "intValue1"; std...
62,056,115
62,062,735
Knapstack implementation in c++ using memoization
What is the difference between doing int t[102][1002] = {-1}; vs running a for loop and doing for(int i = 0; i < 102; i++) for(int j = 0; j < 1002; j++) t[i][j] = -1; The code below does not work when the former method is used. It works only when we I loop through and initialize. Why is that? #inc...
this only sets the first cell of the 2D array t to -1. int t[102][1002] = {-1}; It is better to use either of these two ways for(int i = 0; i < 102; i++) for(int j = 0; j < 1002; j++) t[i][j] = -1; This you already know. Other way is using memset function. memset(t, -1, sizeof(t));
62,056,406
62,056,503
getch not reading keyboard input
Trying to get user input for a simple terminal game. I am on Mac OS. #include <stdio.h> #include <curses.h> #include <iostream> int main() { int ch; while (ch != 113) { ch = getch(); std::cout << ch << std::endl; } return 0; } In this example, I'm trying to simply print my keystr...
You need to first call initscr before any other curses functions. http://www.cs.ukzn.ac.za/~hughm/os/notes/ncurses.html #include <stdio.h> #include <curses.h> #include <iostream> int main() { int ch; initscr(); // <----------- this while (ch != 113) { ch = getch(); std::cout << ch << st...
62,056,559
62,056,583
Is declaring a reference and passing it in the same as just passing by reference?
Say you have a function like this: void func(int & arg) { std::cout << arg << std::endl; } Is doing something like: int x = 10; int & y = x; func(y); the same as: int x = 10; func(x) Does arg become a int && arg or does it stay a int & arg when you pass in a pre-declared reference like the first case?
Yes they're same. As reference, Declares a named variable as a reference, that is, an alias to an already-existing object or function. You can consider y as an alias of x, passing y to the function func has the same effect as passing x directly.
62,056,578
62,056,666
vector's destructor is called immediately and causes double free or corruption (out)
I have a function in which vector's destructor is called immediately and causes error. I saw this with QtCreator's debugger But when I comment out the next line, it works (not as expected but at least dont give error). #include <algorithm> #include <cmath> #include <functional> #include <iostream> #include <vector> ...
The program causes undefined behaviour: map[start] = cost; is executed when start is -1, which accesses out of bounds of the vector. Also you are misinterpreting the debugger output. The order of operations for the minCostClimbingStairs function is: Create map Call min_cost Destroy map Return The first two things...
62,057,125
62,057,279
C++ Null output when a function is called
Below is a snippet of code from my main program My H file class Person{ public: std::string name; int rangeStance; int initialStance; Person(std::string name, int rangeStance, int initialStance){ name = name; rangeStance = rangeStance; initialStance = initialStance; setName(getName(...
A couple of things wrong in this code Person(std::string name, int rangeStance, int initialStance){ name = name; rangeStance = rangeStance; initialStance = initialStance; setName(getName()); setRangestance(getRangeStance()); setinitalStance(getRangeStance()); } Firstly it's not necessary to cal...
62,057,277
62,057,725
enable_shared_from_this returns bad_weak_ptr error
I am using boost library in my project. While I was writing rest http client code I got this error. libc++abi.dylib: terminating with uncaught exception of type std::__1::bad_weak_ptr: bad_weak_ptr template <typename M> 21 class Http: public std::enable_shared_from_this<Http<M>> 22 { 23 M* message_; 24 bool...
If you take a look at std::enable_shared_from_this: Examples you can see this: // Bad: shared_from_this is called without having std::shared_ptr owning the caller try { Good not_so_good; std::shared_ptr<Good> gp1 = not_so_good.getptr(); } catch(std::bad_weak_ptr& e) { // undefined behavior (until C++17) and std...
62,057,431
62,057,640
What are the differences between `typename std::remove_reference<T>` and `constexpr typename std::remove_reference<T>`?
As per the documentation(https://en.cppreference.com/w/cpp/utility/move), there are two kinds of constructors for std::move<T>, which are posted below. What are the differences between these constructors? What confused me most is that why there needs the keyword(typename) in the second constructor. I am a novice in C++...
[...] there are two kinds of constructors for std::move<T>... No, they are not constructors, rather function signatures of std::move. One is prior to c++14(i.e. since c++11) and the second one since C++14. In the second one the specifier constexpr is used, meaning constexpr - specifies that the value of a variable o...
62,057,643
62,057,898
C++: undefined reference to the functor's overloaded invocation operator
template <typename T> class Predicate { public: bool operator()(const T& x) const; }; template <typename T> class LessThan : public Predicate<T> { public: explicit LessThan(const T& v) : val(v) {} bool operator()(const T& x) const { return x < val; } private: const T val; }; template <typena...
You need to provide definitions for all functions of your classes. That means even if you only derive classes from Predicate and Producer you still have to implement the operator() in those classes. If you don't want to do that (i.e. only have the function declaration but no definition), consider making these two class...
62,057,719
62,067,678
z3 extracting Seq Int as std::vector<int>
I'm trying to extract a Seq Int from a model to a std::vector<int>. I can print it with << but how can I do the extraction? void oren_example() { // context + solver context ctx; solver solver(ctx); // sorts sort int_sort = ctx.int_sort(); sort seq_int_sort = ctx.seq_sort(int_sort); sor...
Try: std::vector<int> output; int size = m.eval(projs[1](sigma).length()).get_numeral_int(); std::cout << "size = " << size << std::endl; for(int i = 0; i < size; ++i) output.push_back(m.eval(projs[1](sigma).nth(ctx.int_val(i))).get_numeral_int()); for(int i = 0; i < ...
62,057,831
62,057,996
Equivalent C++ struct for a SWIFT Hashable structure
What would be the equivalent C++ struct codes for this swift struct? struct MyStruct : Hashable { let rawValue: Int let x: UInt8 let y: UInt16 init(x: UInt8, y: UInt16) { self.rawValue = Int(x) << 24 | Int(y) self.x = x self.y = y } func hash(into hasher:...
unordered_map<uint8_t, uint16_t>
62,058,318
62,058,712
What is the function of node in linked list?
I am creating a linked list from scratch. Here is the code. at first, I have defined node *root=NULL; that means root node has no element. But when I append the first element I have to create root=new node(); is not it that node *root=NULL; has created a root node? then why I have to use root=new node();. actually i am...
First of you have to understand what pointers are. Basicall they hold memory adresses. is not it that node *root=NULL; has created a root node? No. root is no node, but a pointer to a node. It is initialized with NULL (in C++ nullptr should be preferred), so it doesn't point to any object yet. then why I have to use...
62,058,325
62,058,738
Memory location of a std::condition_variable can cause futex error
We had a bug in our software that ended in the dreaded: The futex facility returned an unexpected error code. We traced it down to a problem where the location of std::condition_variable within a malloc'd region of memory causes a futex error. If the std::condition_variable is not aligned on a 16 byte word - then it ...
why the alignment would cause this From C++ draft Alignment p1: Object types have alignment requirements ([basic.fundamental], [basic.compound]) which place restrictions on the addresses at which an object of that type may be allocated. The expression: new (bad_ptr + 1) std::condition_variable{}; invokes undefined...
62,058,501
62,059,071
Access violation reading location...,it made me confused
I want to read another program's variable in memory,a pointer point to an int.I want this int.But i got an error.The pointer's address is 0x420CEFFC40,its value is 0x420CEFFC30,buffer should be 123456,but access violated. #include <Windows.h> #include <iostream> using namespace std; int main() { DWORD pid; cout...
In modern operating systems every process has own map of memory. Each process under same address can have different piece of memory or even nothing. That is why you have to use system API ReadProcessMemory to be able to read other process memory. Now when you have read some memory from other process (value of ptr2int) ...
62,058,820
62,062,208
C++20 concepts how to define existence of a function with arguments?
In C++20, we can now use concepts instead of SFINAE to figure out whether a function exists in a template typename: template<typename T> concept fooable = requires (T a) { a.foo(); }; class Foo { public: // If commented out, will fail compilation. void foo() {} void bar() {} }; template <typename T> r...
You might have extra parameters in requires: template<typename T> concept fooable = requires (T a, int i) { a.foo(i); }; Demo
62,058,841
62,059,073
How does one move a std::unique_ptr between windows without risking a memory leak?
I want to do this project in C++ and be done with it once and for all: select a movie from a list in one window and display the movie's details in another window. I'd already arrived at Remy Lebeau's solution here and found his post because I'd realized the same limitation he did: it exposes the raw pointer to memory l...
SendMessage and unique_ptr are definitely not made for each other. I can give lots of hints here, but the best thing to do is to not be smuggling smart pointers through HWND messages. I don't know what a UWM_SendMovieBean, but I'm guessing that's a custom windows message you either based of off WM_USER or RegisterWind...
62,059,247
62,059,329
How to check if a file is already present in fstream C++
I've been writing a code using fstream to create a file having a specific number, now I want mmy program to check whenever a new entry is being made if the name of that entry has already been used or not, TIA for all your help. I've tried doing it myself as in the code attached, but I'm not sure if it's working properl...
If you only need to check if a file exists without actually using it, you can use the <filesystem> library if your compiler supports it. It provides an exists() function that will do that without opening the file. #include <filesystem> namespace fs = std::filesystem; if (fs::exists(file_path)) { std::cout << "Fil...
62,059,527
62,060,008
Why there is an infinite recursion when function parameter is not defined as const reference?
I am having troubles understanding what might be causing the infinite recursion. There are two points that play a role in my problem Depending on the place of definition of the global functions Whether we mark the parameter as const-ref of the second function (either global or class member) Here is the code #include ...
You are dereferencing a const optional<datatype>, you are using const value_type & optional::operator*() const, not value_type & optional::operator*(). A free function definition only looks at names declared preceding it. This is one of the reasons for having declarations of functions in headers. In the case of a memb...
62,059,640
62,059,695
Grammar to make unnamed instance
I'm making hashing function for pair < int,int > key. Anyway, I found the following implementation that uses std::hash<> : typedef struct hasher_t { template <class T1, class T2> size_t operator()(const pair<T1,T2>& key) const { //standard hasher for T1, T2 auto h1 ...
Yes, both construct temporary std::hash and then call operator() on the temporary object. std::hash<T1>() performes value initialization, 1,5) when a nameless temporary object is created with the initializer consisting of an empty pair of parentheses or braces (since C++11); The temporary is initialized by the defau...
62,059,728
62,060,711
How to kill/stop a running process in a terminal without losing its output?
I try to run a simple c++ code in a terminal and try to store its output in output.txt. CODE- #include<bits/stdc++.h> using namespace std; int main() { int n; while(1) { cin>>n; cout<<n; } return 0; } using a terminal commands: g++ code.cpp ./a.out > output.txt and input: 1 2 3 4 ...
for me even it is working as you expect. I think maybe your task is not closed! so try two things: 1- try to close the terminal after crtl+C. after again check the content of output file 2- please give a good name instead of a.out(testfile.out) and after crtl+c try below command in shell: sudo ps -aux | grep testfile ...
62,059,734
62,060,067
How to get rid of error c2061;syntax error cout?
hello i want to build a programme that display even and odd numbers from given numbers i get this message error which is error C2061: syntax error : identifier 'cout' i try again to look but i cant find any.i search online and says that i should using instead of which i did but it didnt work too. How to solve this be...
You have problem with your else statement. here is how you should write it: else { cout << "Odd numbers in given range are: "; for(number = firstNum;number <= secondNum; number++) if(number % 2 !=0){ cout << number<< " "; countOdd++; } cout << "\nTotal count of o...
62,060,881
62,061,085
How to get an index number by struct id in vector
struct person{ int p_id; }; std::vector<person> people; person tmp_person; tmp_person.p_id = 1; people.push_back(tmp_person); person tmp_person2; tmp_person2.p_id = 2; people.push_back(tmp_person2); person tmp_person3; tmp_person3.p_id = 3; people.push_back(tmp_person3); How can I find a index number of vecto...
Use std::find_if to find the element. This returns an iterator to the element. And if you really want to know the index use std:distance: int id_to_find = 1; std:size_t found_idx = std::distance( std::begin(people), std::find_if(std::begin(people), std::end(people), [=] (const person& p) { retu...
62,060,900
62,222,283
Debugging malloc(): memory corruption on new
I have a small to medium size application which combines Fortran and C++. The main is written in Fortran, but one module is in c++. This module returns pointers to class objects which are stored on the Fortran size. During the creation on one of these pointers the system is throwing the following error: malloc(): memor...
Memory corruption errors do not always manifest themselves in the place where the error was committed. As a result the gdb backtrace is often useless for finding the error. Instead a memory analysis/debugging tool such as Valgrind should be used.
62,060,979
62,062,687
I am trying to pass an DMA array and its size as an argument but it is giving an error
I am trying to pass a dynamic memory allocated array and its size to a function 'sum' but it is giving error of permissive what should I do? #include<conio.h> #include<iostream> using namespace std; int sum(int n[], int *m) { for(int z=0;z<*m;z++) { cout<<"\n the output is = "<<...
Your code should, probably, look like the following (Linux Ubuntu + gcc): #include <iostream> using namespace std; int sum(int n[], int m) { int s=0; for(int z=0; z<m; z++) { cout<<"\n array["<<z<<"]= "<<n[z]<<"\n"; s+=n[z]; } return s; } int main() { int *n,m; cout<<"enter the size of array ...
62,061,166
62,091,882
Prevent SC_METHOD from executing without event/trigger
My method fsm1 executes once even without event and therefore id1_cmd.read() and id1_value.read() contain 0 and not the correct values. //------------------------------------------------------------------ // Method: control::fsm1() // Parameter: None // @Sensitivity: ID_1_cmd (unsigned int) //---------------------...
Use the dont_initialize method see the Language Reference Manual SC_CTOR(control) { SC_METHOD(fsm1); sensitive << id1_cmd; dont_initialize(); }
62,061,242
62,062,011
Vector of different specializations of a templated class
Since I have been using templates in C++, I often encounter this problem: I would like to gather instances of different versions of a templated class in a vector. I understand this is not possible directly, but I wonder if there is some workaround to achieve this. For example if I have the templated class like so: enum...
If you want to store different template classes, you can make a parent class and inherit that class in the template class. And I don't know why you're using switch for types, just use template instantiation. #include <iostream> #include <vector> using std::cout; using std::endl; class Mother { public: virtual vo...
62,061,260
62,061,428
Assignment of unique_ptr inside member initializer list
Say if I have this definition: class A { A(); std::unique_ptr<B> m_b; }; class B {}; Is there a difference if I initialize A like: A::A() : m_b(new B()) {} vs. A::A() : m_b(std::make_unique<B>()) {} Additionally for the first case, can i be sure that I do not have to call delete explicitly?
The only difference is style. Since use of operator new is now considered old fashioned std::make_unique is recommended. For compiler there is no difference. By the way is should be: A::A() : m_b{std::make_unique<B>()} {} Also see CppCoreGuidelines/CppCoreGuidelines.md at master · isocpp/CppCoreGuidelines C.150: Use ...
62,061,364
62,061,549
noexcept constructor of std::string_view
According to the documentation, std::string_view has a constructor that takes a const char * and a std::size_t, that is not declared noexcept: constexpr basic_string_view(const CharT* s, size_type count); On the other hand, the documentation states also that the user defined literal operator""sv, that in all the imple...
For the constructor constexpr basic_string_view(const CharT* s, size_type count); you can pass anything as the string: char c{'X'}; std::string_view sv{&c, 100}; // oops Therefore, this function does not have a wide contract (i.e., accepts all inputs), and is not marked noexcept per N3279 Conservative use of noexcept...
62,061,433
62,061,731
How to avoid the "pessimizing-move" warning of NRVO?
#include <string> std::string f() { std::string s; return std::move(s); } int main() { f(); } g++ -Wall z.cpp gives a warning as follows: z.cpp: In function ‘std::string f()’: z.cpp:6:21: warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move] 6 | return st...
You should do std::string f() { std::string s; return s; } if NRVO doesn't apply, move is done automatically. See return#Automatic_move_from_local_variables_and_parameters.
62,061,493
62,061,514
Returning value from lambda in the same line with declaration
Sometimes it is easier to represent a value by function, and lambdas are good for this. But is there any way to return value from lambda declaration? for example: int i = []{return 2;}; generates an error. How to make that lambda declaration return 2 without any new lines of code?
Like calling any functions using the calling operator(), you need to call the lambda. int i = []{return 2;}(); // ^^
62,061,706
62,063,735
C++ Concepts - Concept in the requires parenthesis causes 2 conflicting error messages
I've worked hard this morning to understand concepts a bit more (still a newbie), and I've stumbled to something strange. I wanted to understand how good concepts work with Lambda functions, I've tried toying around with them a lot. Lets start with this code (that works!): #include <concepts> #include <stdio.h> templa...
First off, by doing this: requires(Operation&& op, Integral&& a, Integral&& b) you probably actually meant this: requires(Operation op, Integral auto a, Integral auto b) that is, to use the type-constraint auto form of a placeholder type specifier. However, auto parameters produce function templates, and the auto pla...
62,061,899
62,062,675
Easy way to learn data structures and algorithm
I'm trying to learn data structures/link lists using c/c++ to start a career in software programming...but the complexity is too much for a beginner level. My question here is: Is there an easy way of learning data structures/link lists ? Is C/C++ really suited for learning of data structures ? In the industry, which...
While it is common to see other languages using C/C++ for low-level implementations of data structures and algorithms, it doesn't mean that it is the easiest way to learn about them. You need to keep in mind that when you are talking about data-structures, there are two levels we use: Abstract Data Type (or ADT) which...
62,061,952
62,062,685
RETURN all the keypad subsequences
We have a phone keypad. Using it we have to find out all the possible strings thag can be made using digits of input n. We have to return the strings and not print it. For 0 and 1 return empty string. Have to use recursion. For eg for 23 output will be :- ad ae af bd be bf cd ce cf I tried alot to do this question but ...
What I will do recursively call the create a string class Solution{ public: map<int,string> KeyMapping; void generate_string(string &current, vector<int> &keys, vector<string> &ans){ if(current.size() == keys.size()){ ans.emplace_back(current); return; } int index = (int)curr...
62,061,998
62,073,736
My program doesn't want to write in a text file after DLL call
I have a DLL which expose a function : extern "C" __declspec( dllimport ) __stdcall int EP_ProtectedStringByKey( char* Key, char* Left, int Len); Head of the C++ file : typedef int (*GetString)(const char *Key, const char *Str, int Len); With this code, everything works fine. The program write in the "example.txt" wh...
To avoid two undefined behavior, I need to : Change the typedef to precise the calling convention typedef int (*GetString)(const char *Key, const char *Str, int Len); In typedef int (__stdcall *GetString)(const char *Key, const char *Str, int Len); Dpn't use std::string::c_str() cause in CPP-Reference "Writing to ...
62,062,123
62,065,719
Should I use high-resolution time types as parameters to avoid duration_casts?
I read that if the highest resolution type your program uses is, say, milliseconds and this type will cover the whole range your values are in, you should stick with it mostly, to avoid having duration_casts everywhere. Instead you would have only one, inside the function, if all you need is a precision of, let's say, ...
I don't think there's a lot one can say in general about this strategy except that yes, you don't want to needlessly litter your code with duration_cast. Reserve duration_cast only for those conversions where you want to truncate the precision. And in those cases recognize that duration_cast truncates towards zero. ...
62,062,184
62,063,528
Find euler function of binomial coefficient
I've been trying to solve this problem: Find Euler's totient function of binomial coefficient C(n, m) = n! / (m! (n - m)!) modulo 10^9 + 7, m <= n < 2 * 10^5. One of my ideas was that first, we can precalculate the values of phi(i) for all i from 1 to n in linear time, also we can calculate all inverses to numbers fro...
First, factorize all numbers 1..(2*10^5) as products of prime powers. Now, factorize n!/k! = n(n-1)(n-2)...(n-k+1) as a product of prime powers by multiplying together the factors of the individual parts. Factorize (n-k)! as a product of prime powers. Subtract the latter powers from the former (to account for the divid...
62,062,238
62,062,350
Why is the result type of a sum of two unsigned integers different in Clang and GCC
I am writing some low level code for my emulator which involves a lot of 16 and 8 bit unsigned integers. I enabled -Wconversion warning in my project and all warnings are considered as errors (-Werror). Consider this code snippet: #include <cstdint> int main () { uint16_t a = 4; uint16_t b = 6; uint16_t c ...
IMO, addition of two unsigned ints should not be implicitly converted to an int. Or is my assumption wrong? This assumption is not wrong. Unsigned int is never implicitly converted to int. However on your system, uint16_t happens to be unsigned short int. Assuming that unsigned short ints aren't implicitly converted...
62,062,610
62,062,986
Why do we use <iostream.h> in Turbo C++?
I have some doubt as to why we use ".h" after iostream and do not include using namespace std; because with any other compiler we don't use ".h" after iostream and we add always use using namespace std;. Why?
why do we use <iostream.h> in turbo c++ IDE Because turbo c++ IDE uses the turbo c++ compiler, which was written before c++ was standardised. In that ancient dialect of the language, the STL header is named differently from the standard library header that we have in the standard. That said, very few people use turbo...
62,062,733
62,064,858
Variadic templates in C++ and how they work
So I'm trying to understand how variadic templates work, so I have this code: template <typename Res, typename Type> void Sum(Res &result, Type &val) { result += val; } template <typename Res, typename First, typename... Rest> void Sum(Res &result, First val1, Rest... valN) { result += val1; return Sum(res...
I think that you might miss the point that when you step through this in the debugger, you're entering a completely different function each time. (Note that val1 is not used in the "next" call, so you're passing one argument less each time.) If there weren't variadic templates, you would need to spell these out as sepa...
62,062,897
62,063,442
Create alias template for any STL container
I need to create a template type to work with any container STL that is: Example: template <typename T> using STL_container = ...; And use: void PrintVectorOrList(STL_container<int> container) { ... } void PrintMap(STL_container<std::string, int> container) { ... } How to make alias template?
It seems you want template functions: template <typename Container, typename ValueType> constexpr bool IsContainerOf = std::is_same_v<ValueType, typename Container::value_type>; // Possibly extra check has begin/end template <typename Container, std::enable_if_t<IsContainerOf<Container, int>, bool> = false>...
62,062,968
62,066,680
Unreal 4.24.3 : How to Declare UPROPERTY() inside .cpp file
What I want to do: Create a USceneComponent at Runtime in an Actor class USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID)); What works: Defining UnitDesign at Header File(.h) works without issues.. UPROPERTY(VisibleAnywhere) //I can see UnitDesign in World Outliner USceneComponent* Unit...
If you always want to create the UnitDesign SceneComponent then you can use CreateDefaultSubobject (c'tor only) : /* .h */ UCLASS() class AYourActor : public AActor { GENERATED_BODY() public: AYourActor(FObjectInitializer const& ObjectInitializer); UPROPERTY(VisibleAnywhere) USceneComponent* UnitDesig...
62,063,005
62,063,677
Pointer casting with unknown array size in C++
how can I cast void pointer to a 2d array (array of pointers to arrays of ints), when I dont know array size at compile time? Is it somehow possible? (I am doing this because, I pass an 2d array of unknow size to a func. So I cast 2d array to a void pointer and then in that func I want it to recast back.) int i = 5; i...
First I suggest to don't use runtime size for array in C/C++, except you using STL vector as an array. so instead of: int i = 5; you must use: const int i = 5; except you use Vector that is safe and better than intrinsic arrays. how can I cast void pointer to a 2d array (array of pointers to arrays of ints), when I ...
62,064,288
62,068,061
Opengl:Unexpected behaviour when trying to draw a line to visualise mouse Ray cast
I was experimenting with ray casting to implement mouse picking in my application. What I wanted to do is literally draw the line that is cast from the screen when the mouse is clicked. Here's what i did: float xNormalised = ((float)200/w.getWidth())*2 -1; float yNormalised = -(((float)300/w.getHeight())*2 -1); glm::v...
You can use glm::unproject to get you far and near points : glm::vec3 near = glm::unProject(glm::vec3(mouseX, winSize.y - mouseY, 0), // the screen-space coordinate camera.view, camera.projection, glm::vec4(0, 0, winSize)); ...
62,064,910
62,067,420
How to run script with boost::process::system?
My script: ps aux | awk '{s += $3} END {print s}' So I'm trying to execute it namespace bp = boost::process; bp::ipstream out; bp::system("ps aux | awk '{s += $3} END {print s}'", bp::std_out > out); std::string line; std::getline(out, line); Output: error: garbage option What am I doing wrong?
Actually you don't need manually piping. You just need to inform a shell of your command: Live On Coliru #include <boost/process.hpp> #include <iostream> #include <iomanip> int main() { namespace bp = boost::process; bp::ipstream out; std::vector<std::string> args { "-c", "ps aux | awk '{s += $3} ...
62,065,571
62,065,751
Losing references to objects inside containers
I am struggling to fix a piece of code, even though I believe I know the cause. I did search a lot on Stack Overflow and many people had similar issues (and good answers were provided), but still, I am not sure I understand the problem with my code. I tried giving a smaller example, but the structure I have is not simp...
push_back on vector (might) invalidate previous reference/iterator. it happens in the loop there if (cmpXY(pts[i], pts[j])) segs.push_back({pts[i], pts[j], i}); else segs.push_back({pts[j], pts[i], i}); evts.push_back({segs[i], *segs[i].s, 0}); you have to reserve enough place in segs to avoid reallocation (or...
62,065,728
62,066,039
How do I access subclass variables in a baseclass vector? (for an entity component system)
So I have a vector with "Components". I can access the Component variables easily from the vector, but when I add a subclass to the vector, I cant access those variables. Maybe this is a really bold question and the solution is probably really complicated, but I don't know where to start and what to try so any help is ...
First of all you have a problem with object slicing, to sort that you could do something like : struct Component {}; std::vector<std::unique_ptr<Component>> components; struct Transform : Component { int x = 0, y = 0; }; void Start() { components.push_back(std::make_unique<Transform>()); } As for accessing m...
62,065,796
62,065,864
Correct way to loop through std::array<char*, N>
Consider the following std::array of pointers to char: std::array<char*, 10> m_arr; I know I can loop through the array using the following code for(size_t i {0}; i < m_arr.size(); i++) { std::cout << m_arr.at(i) << std::endl; } But this approach throws "Access violation reading location" exception, w...
Initialize your array: std::array<char*, 10> m_arr{}; // nullptr initialized then you might check safety for non-nullptr value: for (auto ptr : m_arr) { if (ptr) std::cout << ptr << std::endl; }
62,065,806
62,065,958
Reducing the time complexity of the program
I am doing this practice problem where given a string s of lowercase letters, and a position p, I have to print all the occurrences of the letter at position p which occur before the position p. Eg: If the string is "abaac" and p=3(1 based index) then output is 1 because 'a' occurs one time before the position p. There...
HINT ONLY The trick here is pre-calculate answers just after you read string. You can do it quite fast. So in exchange of memory complexity you will gain on time complexity. This can be done in linear time to string size. This way you will be able to provide an answer in following queries in constant time. OFFTOPIC Thi...
62,066,065
62,101,338
cmake and Visual Studio 15 2017 generator - defining a build type
I work on Windows 10. I use cmake with Visual Studio 15 2017 generator. CMakeLists.txt requires CMAKE_BUILD_TYPE to be defined because it is used by Conan command called from cmake (execute_process). Here is the cmake command: cmake -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 15 2017" .. When I run build command this...
Visual Studio is a multi-configuration system. It means that the build type is selected at build time, lets say when you are using the IDE, you can select at that time the Release or Debug configuration and build. So when you are generating the Visual Studio solution (project generation or configure step), with cmake -...
62,066,390
62,066,713
What is the behaviour of lParam when WM_KEYDOWN message recived?
I started learning winapi using c++ language. I am trying to understand the lParam on WM_KEYDOWN message. From the Microsoft documentation: 0-15: The repeat count for the current message. The value is the number of times the keystroke is autorepeated as a result of the user holding down the key. If the keystroke i...
I didn't test this, but your bit ordering appears to be reversed. According to MS Documentation, bits 0-15 are the LOW bits. case WM_KEYDOWN: cout << ((lParam & 0b00000000000000001111111111111111) >> 0) << ", "; cout << ((lParam & 0b00000000111111110000000000000000) >> 16) << ", "; cout << ((lParam & 0b0000...
62,066,610
62,066,650
Declaring array in C++ like array[1-00] by mistake but still code works, output is incorrect?
When i declare array as array[1-00] by mistake i didn't get the right answer. But when i change it to normal declaration like array[100] i clear all the test cases. Can anyone provide any explanation for this type of problem? Please.
You declared the array with a size of 1. int arr[100]; //100 elements int arr2[1]; //1 element int arr3[1-00] // 1 - 0 = 1 element accessing elements outside the array is undefined behavior, which means that the compiler can do whatever it wants. Read this for more information about undefined behavior.
62,068,126
62,068,278
How do I get a volatile function argument working?
I am completely unexperienced in C++, I use C all the time. In my recent hobby project I need to mix in a C++ library with my C code thus forcing me to have a C++ main.cpp. I am right now meddling my C code to compile as C++. This even works pretty well except for one problem I simply cannot solve. This is an interrupt...
Copy the time first into a non-volatile instance: time_t t = UNIX_TIME; tm local = *localtime(&t); TIME_CUR_LOCALTIME.tm_sec = local.tm_sec; TIME_CUR_LOCALTIME.tm_min = local.tm_min; TIME_CUR_LOCALTIME.tm_hour = local.tm_hour; TIME_CUR_LOCALTIME.tm_mday = local.tm_mday; TIME_CUR_LOCALTIME.tm_mon = local.tm_mon;...
62,068,264
62,068,760
Live on heap or stack when use new operator within a function block?
For instance: void Func() { int* i = new int; // the simplest case vector<int*> v = new vector<int*>; // another case, not sure if **new** is using correctly here vector<int*>* vPointer = new vector<int*>; } void main() { Func(); } So, if I allocate dynamic memory(by using new operator) for local v...
int i = 3; this creates an object of type int on the stack. (The C++ standard uses the term "automatic storage", and I'm usually a stickler for proper use of formal terms, but "stack" and "heap" are deeply embedded in programming vocabulary, so "stack" and "heap" are just fine as technical terms). int *ip = 0; this c...
62,068,883
62,070,380
c++ Why shouldn't I unlock a mutex from a different thread
Why shouldn't I unlock a mutex from a different thread? In the c++ standard it says it pretty clearly: If the mutex is not currently locked by the calling thread, it causes undefined behavior. But as far as I can see, everything works as expected on Linux(Fedora 31 with GCC). I seriously tried everything but I could no...
As you already said, it is UB. UB means it may work. Or not. Or randomly switch between working and making your computer sing itself a lullaby. (See also "nasal demons".) Here are just a few ways someone can break your program on Fedora 31 with GCC on x86-64: Compile with -fsanitize=thread. It will now crash every tim...
62,069,437
62,069,755
How to get Actor list by UActorComponent?
I want to get all scene actors filtered by a list of actor components. Kismet library has this. static void GetActorListFromComponentList ( const TArray < class UPrimitiveComponent * > & ComponentList, UClass * ActorClassFilter, TArray < class AActor * > & OutActorList ) But what I need is something like ...
Primitive component is actually an actor component so you can just copy implementation of this function into your code and replace UPrimitiveComponent entries with UActorComponent. void GetActorListFromComponentList(const TArray<UActorComponent*>& ComponentList, UClass* ActorClassFilter, TArray<class AActor*>& OutActor...
62,069,504
62,070,069
Using hex flag inside setiosflags function
int a=60; cout<<setiosflags(ios::hex|ios::showbase|ios::uppercase); cout<<a<<endl; The above code is not working but if I use cout<<hex and then cout<<setiosflags(ios::showbase|ios::uppercase) then it is working Why? and how i do know which one can be used inside setiosflags() ?
You need to call resetiosflags before you call setiosflags. The reason for this is that setiosflags(ios::hex|ios::showbase|ios::uppercase) just appends these flags into the stream as if calling setf and that gives conflicting flags in the stream. Using std::cout << std::resetiosflags(std::ios_base::dec) <<...