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
63,856,515
63,856,720
How can I use template template type as an function argument?
I want to implement the following code: template <int i> void f() { ... } template <template <int i> typename Func> void g(Func func, int i) { if (i == 0) func<0>(); else if (i == 1) func<1>(); else if (i == 2) func<2>(); else assert(false); } int main() { g(f, 0); } However, this code can not ...
Templates can be used as arguments to templates, but they cannot be used as arguments to functions. Hence the error; when you tried to use a template name (Func) as the type of a function parameter, the compiler complained that a template name by itself is not enough. A template argument list is needed to get a type ou...
63,856,631
63,857,985
what happened after call std::thread::join()?
I'm a beginner in multithreads,and there is something I don't understand in cpp standard multithreads library: void func(){ //do something } int main(){ std::vector<std::thread> threads; for(int i=0;i<std::thread::hardware_concurrency();i++) threads.push_back(func); for(auto& thread:threads) thread.join(); //do it ...
On doubt, it's always good to check the documentation: https://en.cppreference.com/w/cpp/thread/thread/join Blocks the current thread until the thread identified by *this finishes its execution. So, your second loop will wait till all threads in the vector have finished execution. Once all that work has been done, yo...
63,856,642
63,857,943
C++ - Best way to create a non-local variable pointer
I have recently been relearning C++ as I develop a game in the Unreal engine. Its been about 3 years since I have touched C++, and I have been mostly using Java since then. Due to the differences between java and c++ I can already tell there are different best practices for similar concepts. I have 2 methods like this....
C++ changed a lot in the last few years to make life easier for those using it. Looking at your code, it raises a lot of questions: Why is the value of your map a raw pointer to ControlNode instead of a ControlNode by value or a unique_ptr to it In your for-loop, why do you write the explicit type of pair (which is di...
63,857,060
63,877,072
Why does this double buffering scheme generate audible clicks each time the audio file is read from disk?
The following double-buffering scheme seems like it should work to me, but for some reason there's an audible click every time the for-loops starts again at the top. Here is a test wav file you can use: https://github.com/JoshuaD84/jwaveform/blob/master/test4.wav, but the bug is not specific to any one test file. #incl...
The problem is not the double-buffering scheme; that's fine. The problem is that you are assuming that the rest of the audio file is valid audio data, but there is junk data past the audio data at the end of this file. When you play that junk data, it sounds like a click. In order to avoid the click, only read as many ...
63,857,665
63,858,363
What is "JAVA exception handling mindset" in comparison with "C++ exception handling"?
In https://isocpp.org/wiki/faq/exceptions, it talks about some wrong exception-handling mindsets, one of which is the "JAVA exception handling mindset", described as follows: In Java, non-memory resources are reclaimed via explicit try/finally blocks. When this mindset is used in C++, it results in a large number of u...
In C++ we can use RAII for all resource management. In Java we have GC for memory resource management and manual explicit code for non-memory resource management. To do that manual non-memory resource management on case of exceptions we have to use explicit try/finally blocks in Java. Doing same in C++ however loses t...
63,857,859
63,858,045
Is write guaranteed with one thread writing and another reading non-atomic
Say I have bool unsafeBool = false; int main() { std::thread reader = std::thread([](){ std::this_thread::sleep_for(1ns); if(unsafeBool) std::cout << "unsafe bool is true" << std::endl; }); std::thread writer = std::thread([](){ unsafeBool = true; }); reader...
UB is and stays UB, there can be reasoning about why things are happinging the way they happen, though, you ain't allowed to rely on that. You have a race condition, fix it by either: adding a lock or changing the type to an atomic. Since you have UB in your code, your compiler is allowed to assume that doesn't happen....
63,857,983
63,858,051
Unresolved External Symbols in DLL using lambda
I have the following structure part of a DLL: Utils.h #ifdef _EXPORTS # define UTILS_API __declspec(dllexport) #else # define UTILS_API __declspec(dllimport) #endif namespace Utils { static auto MyCustomComparator = [](std::shared_ptr<IMyType>& o1, std::shared_ptr<IMyType>& o2) { // do some stuff and...
You have to ensure this: By creating DLL the macro _EXPORTS should be defined. In the client code using DLL the macro _EXPORTS should not be defined. Also note regarding lambda: the 2 compilation units including the same header file, will see the different lambda types, because every lambda has different type. For exam...
63,858,174
63,858,213
Pointer address and address of variables to which pointer points
I am a newbie in c++ and my question may seem basic, but your answer could help me and help others. I created to char pointer myPointer1 und myPointer2 so const char *myPointer1 = "Hallo"; const char* myPointer2 = myPointer; I thought that pointer stored the address of the variables they point to. In this case we have...
You are printing the address of the pointer, not the address that the pointer points to. std::cout << myPointer << std::endl; This would print the address the pointer points to. Since a char* is treated as a string when passed to std::cout it will print Hallo. If you want to print the address itself you can achieve th...
63,858,264
63,858,504
Dynamically load jvm.dll without linking it
So, lately I've been thinking about calling Java Methods through C/C++ but a great issue that comes is having to add jvm.dll to the path, I've been thinking wouldn't it be possible if I found the jvm.dll by getting JAVA_HOME and putting "\bin\server" or "/bin/server" in case of Linux/MacOS, then I would find it and for...
You would just have to use JNI_CreateJavaVM to create a JVM and from there, you get often a structure of function pointers, so you only have to use dlsym for some functions. I used the dl* functions, but it's quite the same on windows with LoadLibrary and GetProcAddress. #include <jni.h> //For the typedefs, struct defi...
63,858,552
63,858,636
How to invoke command-line tool in C++
I want to develop an improved version of OpenSSH, and it depends on OpenSSL to generate the RSA and DSA keys to encrypt and sign the connection data. But it seems that I cannot call OpenSSL with fork(). Can someone tell me how to call openssl genrsa 8192 in my C++ code so I would not need to write a shell script for it...
You can use system library function to invoke external programs. You pass the command line in a string, like system ("openssl genrsa 8192 >key.rsa"), then you need to read the result back from the file "key.rsa".
63,858,906
63,874,414
App crashes on AppendCollumn() with a Virtual List Control
I am a hobby programmer still learning C++ and wxWidgets. I use Code::Blocks 20.3, wxWidgets 3.1.4, and MinGW 17.1 on a Windows 10 Pro computer. I am trying to make a virtual wxListCtrl work in Code::Blocks, I followed the code in the ListCtrl sample and a simple example in the wxWidgets Discussion Forum. The sample (1...
Here's a second answer that uses wxFormbuilder's subclass feature. The advantage of this approach is that it will let you set up event handlers with wxFormbuilder. First we'll need to have a slightly different declaration for the constructor for the derived class class MyListCtrl:public wxListCtrl { public: MyLis...
63,859,556
63,859,665
error occur when I call execvp to run java
I use chdir() to switch the directory, and then use execvp() to execute "java Main". I'm sure there is Main.class, but something went wrong. I want to know why. #include <cstdio> #include <unistd.h> using namespace std; int main(){ char buf[80]; getcwd(buf,sizeof(buf)); printf("current working directory: %s...
This works as intended on my system, maybe you need to add -cp . to your java call. EDIT: to elaborate: -cp (for classpath) tells java where to look for user provided .class files. This does not necessarily include the current working directory by default.
63,859,622
63,862,758
goto() function with for loops
I'm making a simple guessing game where the user has to guess one of the keys locations in a hidden map (an array) and he has 12 tries to make his guess i almost made it but the only problem is the counter isn't changing i want the TryCounter to actually count the tries when the user doesn't guess the location of a ke...
Looking at your code, it looks complicated. I've tried to understand it by doing some refactorings and I expect that you already have some bugs into it. My suggestion would be to extract some functions out of this code. I've already identified some duplicated code to print out the array to the std::cout. This reduces t...
63,860,271
63,876,300
Can't connect to my Oracle database from a SQLAPI++ program in C++
I'm kinda new to using database. I've been learning oracle sql and have installed oracle express edition 18c from their site. I generally perform sql queries through the provided SQL*Plus tool. Now, i really want to be able to connect to the database from my c++ program for a project. I heard about odbc and I went and ...
I know I'm a total noob at this but i'll post what worked for me anyway. I didn't manage to use odbc to connect to my oracle 18c database in the end but occi did the trick. I used SA_Oracle_Client as the 4th parameter and "host_name:port_no/service_name" as the connect string(1st parameter). These values i just copied ...
63,860,586
63,860,650
Rvalue and Move Semantics with Unique Pointer: error for object 0x7ffee5c7b670: pointer being freed was not allocated
I am trying to understand how unique pointers and move semantics. Now, I have created a dummy example below to show what the issue is. My question is, why does this code throw a pointer being freed was not allocated error?: #include <iostream> #include <memory> using namespace std; template <class T> class Object { p...
This has nothing to do with std::unique_ptr. The reason you get the "pointer being freed was not allocated" error is because the shown code is trying to delete something that was not newed. delete[] this->values; values = new_values; This properly deletes the old values, but then just blindly sets values to po...
63,861,179
63,861,273
Recalling the previous value of a variable?
I'm a little new to c++ and I hate running across situations where I need to store a previous value in another variable. So my question is, can I make a variable in a sense store two values. I wish I could have the ability to recall previously stored values and use them in other functions. ex) Current way int x1 = 5; i...
Here's a minimal class that works for your particular use case: struct Int { int val = 0, old_val = 0; Int(int i) : val(i) {} operator int() { return val; } void operator=(int i) { old_val = std::exchange(val, i); } int old() { return old_val; } }; and you could use it like this: Int x = 5; x = x +...
63,861,517
63,862,604
Make Windows32 API members expand to A, or Change Character set in vs2019 (c++)
My problem is as follows. When I pass in strings into the methods/classes of the win32 api, I get the Problem, that the type "const char*" cannot be used to assign variables of type LPCWSTR. I than made a helper method, that converts const char* manually to LPCWSTR. In the most cases, this did the trick, but In the Cre...
CreateWindow expands to CreateWindowW if UNICODE is defined during compiling, otherwise it expands to CreateWindowA. Same with TCHAR (wchar_t/char, respectively) and all other W/A-based APIs. So, either set the project's character set to ANSI/MBCS, or you can simply #undef UNICODE where needed. Prior to Windows 10 ver...
63,862,428
63,862,866
Prevent implicit conversion from bool to char
I noticed that in C++ bool is implicitly converted to char. I realize that they're both stored as 1 byte, but they're fundamentally different types. Is there some compiler flag or something I can set to prevent an implicit conversion between the two? char being automatically converted to bool makes sense, but not the o...
This conversion is mandated by the C++ standard (part of the integral conversions), so it is not possible to disable this conversion and remain a compliant C++ compiler. It is possible for compilers to offer non-compliant extensions, but for something like this they would probably prefer a warning to going non-complian...
63,862,677
63,865,466
How do I access a shared set in boost::interprocess?
What's wrong with the following code? I am trying to create a shared set and add some strings to it. The compiler throws a very verbose error, which is beyond my limited understanding in c++ , let alone boost. //g++ test.cpp -lboost_thread -lrt -lpthread #include <boost/interprocess/containers/set.hpp> #include <boos...
Note that the set definition is: template <class Key ,class Compare = std::less<Key> ,class Allocator = void ,class Options = void> class set; So, according to this, the compilation step passes if you change SHM_StringSet typedef this way: typedef boost::interprocess::set<SHM_String, std::l...
63,862,845
63,863,071
Specify base class template parameter depending on the derived class fields
I want to be able to set the type of a data member in a base class to as smaller as possible depending on the number of data members in the derived class. So, if the number of data members in the derived class is 5, type of data member in base class should be std::uint8_t. Here is what I have tried already: #include <i...
Workaround when you need complete type in CRTP is to not use CRTP :), but regular inheritance the other way: template <typename T, typename U = min_t<T::end__ - T::begin__ + 1>> struct Wrapper : T { U a; }; struct FooImpl { static constexpr int begin__ = __LINE__; static constexpr int F_A = 0; static c...
63,863,259
63,863,347
I can't reproduce the function memoization from Functional Programming in C++
The following code should be almost a copy of what the book Functional Programming in C++ presents at the end of Chapter 6 section 1: #include <iostream> #include <utility> #include <mutex> template<typename F> class lazy_val { private: F m_computation; mutable decltype(m_computation()) m_cache; mutable ...
You must be using Linux and gcc. An "undocumented" feature of this implementation is that any C++ code that uses any thread-related stuff must be explicitly linked with -lpthread. I reproduced your exact crash on Linux, after compiling (with -std=c++17) and linking without -lpthread. The shown code runs fine, if explic...
63,863,698
63,864,372
Problems to access/change private variables in an operator overload of a different class
I have a problems with the following initial situation: I have 2 classes. For example a class A and class B. In these two classes I have a private variable var. I have created two objects of the two classes in the main (e.g. obj1 and obj2). Next I would like to make a statement of the form obj1 = obj2. To do this, I wa...
To access a class private data member (var in this case) you should add a get() function, as @Omid CompSCI first stated in his comment. A MWE (I preserved your assignment operators that double the given input): #include <iostream> using namespace std; class B; /* Definition of class A */ class A{ double var; pu...
63,864,107
63,864,626
std::function internal memory organization and copies; passing reference vs value
When a std::function is copied, are the code instructions it references copied as well? An std::function is initialized via some form of callable, that points to executable code in some way (like a function pointer typically does). Now, when a function-object is copied, is this executable code runtime copied or interna...
(Note: the whole discussion below is a little simplified. AFAIK, none of it is wrong, but I did omit some details and edge cases and definitions and implementation stuff.) The std::function does not copy any executable code. The executable code is always merely pointed to, by std::function. And when the std::function g...
63,865,049
63,865,145
Can we assign a value to pointer unsigned char array?
Hello everyone I'm trying to make a Tetris game with C++. I'm looking that tutorial #include <iostream> #include <string> using namespace std; int nFieldWidth = 12; int nFieldHeight = 18; unsigned char *pField = nullptr; //dynamic memory allocation for store game area elements int main(){ ... pField = new unsigned...
He explains it from 8:20 onward in the youtube video: pField is set to 0 if the slot is empty, otherwise 1 to 8 if it is occupied by one of the tetromini shapes. 9 is reserved for the board walls. So with that ternary condition he is initialising the board, setting it to empty (0) almost everywhere, unless the loop hit...
63,865,318
63,866,108
Normalize Vectors Before Performing Dot Product?
I have a classic exercise which asks me to check if a character was attacked from the back (backstab or projectile). I know I can use the dot product for this, I was just wondering if I had to normalize the vectors first or if it didn't matter. My reasoning was if the vector coordinates were huge numbers, if it would c...
You are right that in principle, some coordinates could be so large that the dot product computation overflows. However, the representable range of finite 32-bit floats is enormous, with a maximum of roughly 3 × 10^38 (Wikipedia). For instance supposing your vectors are in units of centimeters, that's enough to compute...
63,865,602
63,865,627
Result of value comparison in c++
In the following piece of code the output is 1 but I'm not sure why. Has i been implicitly changed to a boolean? How can an integer value be set to an expression like this? #include <iostream> using namespace std; int main (int argc, const char *argv[]) { int a = 1, b = 1, c = 1, i = 1; i = b < a < c; cout << i;...
Has i been implicitly changed to a boolean? No. Rather, a boolean expression has been implicitly converted to int, then stored in i, as commented by @WhozCraig. How can an integer value be set to an expression like this? Because it follows the C++ Standard. When you do: i = b < a < c; since the first < and the se...
63,866,152
63,866,399
Why the algorithm gives different answers for C++ and Python?
I do an algorithm exercise today. This question's tutorial gives an example answer written in C++: int dp[21][200]; int i, j, k; void main() { int bucketN, fishN; scanf("%d %d", &bucketN, &fishN); dp[0][0] = 1; for(int i = 1; i <= bucketN; ++i) { for(int j = 0; j <= fishN; ++j) ...
In the C++ code, the data type for dp array is int, which can hold upto the number 2147483647. The true non-overflown answer you are looking for is returned by your python code 68785126410. Change the first line in your C++ code from: int dp[21][200]; to long long int dp[21][200]; and the printf format specifier from "...
63,866,346
63,866,402
segment fault when passing right reference for literal in labmda with varidic template function
the code is as follows #include <functional> #include <iostream> using namespace std; int foo(int a){ cout<<a; return a; } template<typename R, typename ...Args> function<void()> wrapper( R f, Args&& ... args) { function<void()> fun([&] { f(forward<Args...>(args...)); });//crash //function<void()> fun...
function<void()> fun([&] { f(forward<Args...>(args...)); });//crash All of these captured objects, f and all args, are captured by reference. All of them are parameters to wrapper. But as soon as wrapper returns, all parameters to wrapper go out of scope and get destroyed. And your lambda's captured references, all of...
63,866,395
63,866,448
Why am i getting this warning C26495 in visual studio?
I have a code that seems to be error free but I am getting this warning C26495: Variable '_date::year' is uninitialized. Always initialize a member variable (type.6). It also says +3 overloads for the constructor in the same warning. Why am i getting this warning. I have looked online but cannot figure out what is the ...
Your particular issue is that, in the day/month constructor, the year member variable is not being initialised so may be set to some arbitrary value. You have a constructor like (and note the changes to the default values, there's no such thing as the zeroth day of the month or month of the year so, unless you're usin...
63,866,913
63,867,115
How to forge my OS fit screen in Console/Video(protected) mode in kernel C?
First of all, sorry for my English. I'm creating my own operating system but I have some screen size issues. How can I make my OS fit screen and get screen size? Thank you all.
An OS is a huge thing with many pieces (boot loader, kernel, drivers, GUI, applications, ...). All of the pieces depend on lower level things causing "layers", where pieces at one layer (e.g. applications) depend on pieces in lower layers (GUI, VFS, network stack) which depend on pieces in a lower layer (drivers) which...
63,867,210
63,867,602
Why am i getting error when i try to assign string to istringstream object in visual studio in c++?
The following class takes a string line as input from the user. My aim is to store it in the istringstream iss and then to extract various data from the istringstream iss into various variables. But, when I try to initialize iss with string user_input, I am getting this error when I compile the file: error C2064: term...
The short version is you cannot initialize an object twice. iss is declared and constructed as a private member of your class. It already exists when you attempt iss{user_input} -- that's not allowed. You don't want Initialization, instead you simply want to replace the content of iss with what is in user_input. For th...
63,867,232
63,867,271
simple question about standard c++ multithreading
hi i am newbie learning c++ multithreading this ques may look stupid but just curious why it's happening would be amazing if somebody points out what is going on underhood so, class background_task { public: void operator()() const { for (int i = 0; i < 1000; ++i) std::cout << "Hello world ...
You need to either detach or join std::thread objects before they get destroyed. This is part of the API and documented in the destructor: std::thread::~thread Destroys the thread object. If *this has an associated thread (joinable() == true), std::terminate() is called. What you usually want is to join the thread, w...
63,867,584
63,872,602
Error in detecting cycle in undirected graph code
#include<bits/stdc++.h> using namespace std; bool iscycle(list<int> *adj,bool *visited,int i,int parent){ visited[i] = true; for(auto j : adj[i]){ if(!visited[j]) if(iscycle(adj,visited,j,i)) return true; else if(j != parent) return true; } return ...
The else in iscycle goes with the second, innermost if, not the first, misleading indentation notwithstanding. Add braces as needed.
63,867,637
63,867,672
C++ deleting children basing on parent's pointer
Let's say that I have class A: class A { A(); }; and class B being a child of A: class B : public A { B() : A(); ~B(); }; and a vector of A pointers: std::vector<A*> a_pointers; Now, I initialize everything with: B* b_obj = new B(); a_pointers.push_back(b_obj); How do I delete b_obj object? Should it b...
You'll want to give A a virtual destructor (see here for why): class A { A(); public: virtual ~A() = default; }; At which point calling delete a_pointers[0] will fully destruct b_obj.
63,867,758
63,868,252
C++ inline or not inline declarations of template class specializations
I am a little confused when one should inline specializations. From this question it gets clear that every specialization must be inlined to avoid duplicate symbol errors. But what if I want to have a declaration of the specialization first, how would that change things? If we consider this example: template<typename T...
Like the other Q&A mentions, the specialization is its own entity. If you do as you did, declare the specialization in a header, and then define them in another (single) TU, that is well-formed. Any TU that includes that header will see that the specialization for int and float are only declarations. As such, their def...
63,867,796
63,871,484
Difference between Ranges algorithms and std algorithms
Many standard library algorithms have two versions in C++20: one in the std namespace and another one in the std::ranges namespace with the same name. For example, std::ranges::count and std::count are both are used to count the number of elements that satisfy a predicate. Why are there two versions of these algorithms...
The Ranges functionality adds C++20 concepts to iterators and ranges, and it constrains the definition of its algorithms and the like to those concepts. However, the C++20 concepts have different requirements from the C++17 named requirements. Usually, types which fulfilled the C++17 requirements will fulfill the C++20...
63,867,830
63,949,866
How can I use compile & use multiple similar c++ library together?
I want to use 5 complex c++ libraries in Rust written by other open-sources projects at once. Those libraries have a similar structure: utils, parser, ast, simple interface. Those interfaces can be altered easily, however, those utils, parsers and asts share the same function name but have different implementations. e....
I solved this problem using the following procedure: calm down and believe you are a robot. give every .cpp & .h a unique namespace when it can be easily done. (e.g: namespace_a{}) For that hard-to-add-namespace source files, in this project, they usually generated by flex + bison. use %option prefix="any_name_I_like...
63,868,250
63,868,320
Showing Runtime ErrorAbort signal from abort(3) (SIGABRT)
// Sum of Sub-Array #include<iostream> #include<vector> using namespace std; void firstSubArray(vector<int> arr, int size, int sum) { int newSum = 0; int beginPos=0; for(int i = 0; i<size; i++) { newSum += arr.at(i); if(newSum > sum) { newSum = newSum - arr.fro...
You are trying to access a position in the vector that does not exist. The executor on the server detects this condition and aborts. As a first step, change the arr to vector < int > const &arr.
63,868,310
63,896,861
Real input to FFT then iFFT back to real data in 1-D Array
I'm trying to implement FFT and iFFT using Intel MKL. The FFT on the real input works fine and the output array I get back is correct. On using the same output array for an iFFT the values that are returned are all multiplied by the size of the array and this holds true for all sizes. I'm unable to understand why this ...
There exist different conventions for definition of FFT/IFFT, with different normalisation factors: 1/N normalisation at FFT side, or 1/N normalisation at IFFT side, or 1/sqrt(N) normalisation at both sides, or no normalisation at all. With no normalisation factor, after FFT/IFFT, you get a multiplication by the FFT si...
63,868,340
63,869,313
How to design class that I need use derived class member in base class?
Generally, we use virtual-function or composition to design class.As I know, use virtual-function will make class more structured; use composition will be easy to impl, but maybe write more duplicate code. In this situation: I need a parser, it will use for different protocol.Now, I suppose that it will use in A-Protoc...
If the two parsers don't return the same data, they do not have a related interface and probably shouldn't have a common base class. If they do return the same data, put the GetData function in the base class. Or better yet, return the data directly from Parse.
63,868,405
63,868,845
How to fix the problem in the program for decrypting the Caesar cipher?
#include <iostream> using namespace std; int main() { setlocale(LC_ALL, "Ukrainian"); string text = "ІЇЬЩЙКХЧКЬСИЛЧХЙЮІЙБНИКЇИЗБДШЬЗЬЇХКИЇАХЩИІИЖИШИУФЕИШИЄУЩФЖЖИЯЗХЧ"; char arr[32] = { 'А','Б','В', 'Г', 'Д', 'Е', 'Є', 'Ж', 'З', 'И', 'І', 'Ї', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц',...
When a == plus, you access arr [32].
63,868,422
63,868,568
C++ How to find min and max values in a one-dimensional array of n elements?
Write a program that asks a user to input an integer n. The program should prompt the user to input n integers and store them in a one-dimensional array. Then the program should output the minimum and maximum elements in the array. int main() { int n,a,b; cin>>n; int ma=0,mi=0; int num[n]; cin>>nu...
You missed that the first value in your algo will never be set as a min or as a max value. Let's assume all the numbers are positive ones int main() { int n; cin>>n; int ma=0,mi=2147483647; int num[n]; for(int i=0;i<n;i++) { cin>>num[i]; if(num[i] > ma) ...
63,868,693
63,868,743
Can't change data members' values of member object
In this sample program: I created a class A with a object member of class B Class B contains data member x with a setter and a getter Constructor of Class B initialize data member x with the value 5 Class A contains member function func () to set the value of data member x of class B to value: 7 Now the value of x be...
This is returning by value (a copy of obj and not obj itself): B getB() { return obj; } To return the variable itself, you should return a reference to it: B& getB() { return obj; }
63,868,835
63,869,135
Why does my object get overwritten in C++?
Im trying to create a grid of pointers to objects. To do so, I made two classes, the first one is called Pixel, stores the pixel's info, and the second one is the Grid class, which constructor creates a matrix of pointers directed to a Pixel object. The problem comes when I instantiate a Pixel object and a Grid object,...
In the Grid constructor, p0 is a local variable. It disappears when the constructor ends. &p0 is the address of a local variable. It points to random rubbish when the constructor ends. So whatever you stored into p is rubbish pointers. But it's worse. You declared g and p to be arrays of size 0. (Why the heck is your c...
63,868,836
63,868,885
How to concatenate strings in an output function?
Some languages have easy ways of doing this, but my question revolves in C and C++. I wanna do something like this in Java: public class sandbox { public static void main(String[] args) { System.out.println("Thank" + " you!"); } } And transfer it in C: #include <stdio.h> int main() { /* The easies...
You use just nothing: puts ("Thank" " you.");
63,869,137
63,869,297
In C++, what is the best way to dynamically allocate a single class?
SomeClass* a = new SomeClass; Is straightforward, but I have heard that std::vector is preferable to new. But, std::vector<SomeClass> a(1); also feels weird, because when I use a[0], it's not clear that I'm using it as a variable and not an array. Is there nothing wrong with that, or is there a better way to do this?...
If you want to dynamically allocate an instance of a class then use a smart pointer: std::unique_ptr or std::shared_ptr which are constructible via make_unique and make_shared respectively. There are also libraries with other smart pointers you could use. Incase of allocating an int... I mean there could be reasons but...
63,869,292
63,869,315
How does glm::mat4 constructor works?
How does this line of code work? glm::mat4 trans = glm::mat4(1.0f); Why do i have to pass only one float and how does the matrix look like?
The OpenGL Mathematics (GLM) API documentation is based on OpenGL Shading Language (GLSL) and refers to The OpenGL Shading Language specification. 5.4.2 Vector and Matrix Constructors [...] If there is a single scalar parameter to a matrix constructor, it is used to initialize all the components on the matrix's diagon...
63,869,650
63,869,950
C onnx header can't find OrtEnv definition
I am trying to wrap the ONNX header for use in another language. To be clear it uses the C dll and requires the C header however I'm having issues compiling using the C header due to the ONNX header seemingly missing the definition of the OrtEnv struct that is used in the current ONNX samples. https://github.com/micros...
If a header does not contain a definition, it means that the author did not want to give it to you. That can happen for various legitimate reasons, one of them is that you should not be able to tamper with the content.
63,869,981
63,870,198
C++ Class pointer dynamic array deallocate problem
#include <stdio.h> #include <stdlib.h> #include <windows.h> #define ROW 1 class Foo { public: Foo() { this->dummy = new unsigned int[100]; } ~Foo() { delete[] this->dummy; this->dummy = NULL; } unsigned int* dummy; }; Foo** allocate() { Foo** foo_array = NULL;...
I don't see any reason to declare foo_array as pointer to pointer. In your code you are passing pointers by value. That means you can change what the pointers are pointing at but you can't change the values of the pointers. You can solve the problem using references. #include <cstdio> #define ROW 1 class Foo { public...
63,870,119
63,870,320
Console wont stop asking for input
I am new in C++. And for my first ever problem about Quick Sort algorithm, when I run the code, it wont stop asking for input. Even though i have been running the code from a different IDE the problem persists. #include <bits/stdc++.h> #include <iostream> using namespace std; void swap(int &x, int &y){ int temp; temp=...
The code is not stuck at the input rather it encounters an infinite loop, to check the same you can print a cout and check if the statement is printed or not. cout<<" Read the array elements"<<endl; part(arr, 0, n-1); One case in which infinite loop occurs is in lines while(a[s]<=a[p]){ if(s!=hi+1){ ...
63,870,345
63,870,478
Unhandled exception at 0x00007FF982801B5F (ntdll.dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF
I get this error "Unhandled exception at 0x00007FF982801B5F (ntdll.dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF" while trying to initialize a dynamic 2D array inside a class. Here is my class class Board { private: int boardSize; char** board = new char*[...
char** board = new char*[boardSize]; The line above is setting you array to the size of what ever boardSize is initialized by the compiler (most likely 0). It doesn't get set it in the constructor. If you can use a debugger and see what it is set to in the board constructor. If you want a dynamic 2D array you need to ...
63,870,356
63,870,369
Proper way to fill a struct with 0 using std::fill?
Does std::fill designed for fill struct as well? For example I got a struct: struct Foo { int i = 1; float f = 0.2; }; for some reason I want to fill the Foo with 0: int main() { Foo foo; // memset(&foo, 0, sizeof(Foo)); std::fill(&foo, &foo + 1, 0); std::cout << foo.i << std::endl; std::cout << foo.f << ...
As the compiler told you, std::fill uses operator= internally. If you define it in your class, you can use std::fill with it. From the reference: Assigns the given value to the elements in the range [first, last). Assignement means the operator=.
63,870,442
63,893,416
Sorting the Addressess of the pointers in a dynamically allocated array of class
I've created a dynamically allocated array of a class. class AlienShip { public: int DAMAGE; .......... }; AlienShip * ships = new AlienShip[N]; Where N is between 2 and 50 inclusively. After initialization of each element, I want to sort the array in the decreasing value of DAMAGE in each of ships. I im...
Since you have an array of AlienShips, and you want to sort on the DAMAGE variable of each, then use std::sort with a custom comparison function. You don't need to sort pointers. You have one pointer (to the start of your array). Using that pointers, you get each AlienShip. If you want to swap a pair of AlienShips, you...
63,870,599
63,870,621
Is it safe to call c_str() directly on returned std::string from a function?
int main () { char dest[BIG_ENOUGH]; memset(dest, '\0', sizeof(dest)); strcpy(dest, func1().c_str()); return(0); } std::string func1 () { std::string s("test"); return s; } one of my workmates told me that the string on which c_str() is invoked may already be destroyed before strcpy being executed. is ...
It is safe in the given example as the lifetime of the returned string ends at the end of the statement containing the function call. In general I recommend reading https://en.cppreference.com/w/cpp/language/lifetime
63,871,388
63,871,570
Is it possible to use an indexed iterator to access the index of another array?
I'm trying to use an iterator constructed as a std::vector<std::array<int,3>>::iterator data type in a loop to access the index of a std::array, but whenever I dereference and index the iterator I'm getting the error "no operator "*" matches these operands". What can I do to fix this? std::vector<std::array<int,3>> x =...
The precedence of [] is higher than that of * (https://en.cppreference.com/w/cpp/language/operator_precedence) You need to write (*it)[0]. As a side note, using a range-for loop or <algorithm> (std::for_each(), std::transform(), std::find_if()...) is less error-prone than dealing explicitly with the iterators (or indic...
63,871,802
63,871,966
Why did C++17 introduce std::aligned_alloc?
Aim: To understand the motivation why C++17 introduced std::aligned_alloc for dynamic memory management. Problem: For the memory allocation in C++, using std::malloc is virtually always discouraged due to various reasons exemplified under In what cases do I use malloc and/or new?. Instead, using new expression is almos...
C++17 bumped up its support for plain C from C99 to C11. It inherited aligned_alloc along with other stuff from C11. paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0063r3.html So the motivation is to make C features available in C++ for those who want them.
63,872,160
63,872,267
Unexpected behavior return a value from a std::bitset inside a lambda function
I am trying to use the value from a std::bitset inside of a lambda function but I am experiencing unexpected behavior: int main() { auto lambda = [](unsigned int param) { std::bitset<10> bits(param); std::cout << "inside lambda bits[8] = " << bits[8] << std::endl; return bits[8]; ...
The operator[] for std::bitset returns a std::bitset::reference when called on a non-const std::bitset. This means the lambda (which deduces the return type), returns a reference to a local variable. This obviously dangles, and invokes undefined behavior when used at the call site. You can fix this in several ways: Ex...
63,872,318
63,872,576
Templated typedef structs with constructor in C++
I have this code right now, which seems to work so far but I was wondering if there was a way to get the exact same struct in a more elegant way since my method so far needs a duplicate everytime for each struct... The end goal would be to have a typedefed struct which would swap the bytes according to the endianness a...
There is no need for a typedef struct declaration in C++. This is a relic of C. In C++, after declaring a struct ResourceHeader_s, or struct ResourceHeader_t, or just a plain struct ResourceHeader, the same symbol can be used directly by itself, without an explicit struct.
63,872,689
63,925,407
Can't cross compile c++ class with sqlite included (undefined reference) on linux (i686-w64-mingw32-g++)
I tried to compile my c++ class with sqltie3 include. I run Ubuntu 20.04. For this I use the i686-w64-mingw32-g++ cross compiler, I also tested it with g++ and it works perfectly but not with the i686-w64-mingw32-g++ compiler. I always get the same error: /usr/bin/i686-w64-mingw32-ld: DBWrapper.o:DBWrapper.cpp:(.text+0...
I figured it out I just needed sqlite3 as a compiled object file (sqlite3.o) for the compiler.
63,872,806
63,872,857
How to use std::find algorithm on a vector of boolean elements
I'm getting this std::_Bit_const_iterator error when trying to find an element in a std::vector<bool> using std::find. Can somebody explain what is it that I'm doing wrong. #include <iostream> #include <vector> #include <iterator> #include <algorithm> int32_t main(int32_t argc, char* argv[]) { std::vector<std::ve...
Since row is a const std::vector<bool>, the return value of std::find is of type std::vector<bool>::const_iterator, and is not convertible to std::vector<bool>::iterator. Note that const iterator is not at all the same thing as const_iterator - the former means the iterator itself cannot change (e.g. can't be pointed t...
63,872,817
63,954,267
Close main window ffrom messagebox using gtkmm / c++
From a message box i'd like to close the main window if i click on Ok button. class usb_boot : public Gtk::Window{ public: usb_boot(); and from message box i tried this void usb_boot::creation(){ //Gtk::MessageDialog dialog(*this, dropdownList.get_active_text()); std::string message("Format : " + type); Gtk::Mess...
You should avoid using raw new/delete whenever you can (like here, for instance). For message dialogs, you can use simple scopes: #include <iostream> #include <gtkmm.h> class MainWindow : public Gtk::ApplicationWindow { public: MainWindow() = default; }; int main(int argc, char **argv) { auto app = Gtk::App...
63,873,049
63,873,186
std::function as a friend of the class
Consider this code : #include <functional> class A{ public: std::function<void(A* obj)> todo; void doWork(){ if(todo) todo(this); } private: void dummy(){} friend void todo(); // not working }; int main(int argc, char *argv[]) { A tmp; tmp.todo = [](A *obj){ ob...
friend void todo(); // not working Yes, it's not working. This declares that the friend function is some function called "todo". This is not the same thing as a class member of the same name. Friends are functions (or classes), and not class members. The fundamental issue you are facing here is a combination of two fu...
63,873,137
63,873,346
Sfml how to make a shape move to a certain point
I am having a trouble implementing an interpolation to move an object to a point in my screen. Here is the code: factor += timer.getElapsedTime().asSeconds() * speed; for(int i = 0; i < 50; i++) { circleObjectArray[i].setPosition(Interpolate(movePositionsX[rand() % 5], movePositionsY[rand() % 5], factor)); window....
You need to give your shapes time to move. For each shape you should store the three inputs of your interpolate function. Then, update the factor a little bit every frame and render it by calling Interpolate with the stored arguments. For example, adding 1/60 every frame will make the shape do the complete move in one...
63,873,362
63,873,446
How do I remove space at the end of an output in C++?
#include <iostream> using namespace std; int main() { int n, i; cin >> n; for (int i = 1; i <= n; i++) { if (i == 6 || i == 9) continue; cout << i << " "; } return 0; } Question- write 1 to n integer numbers but she do not write 6 and 9. you required to write a cpp pro...
Use the method @ user4581301 has mentioned if (n > 0) std::cout << 1; for(int i=2;i<n;i++) { if( i == 6 || i == 9 ) continue; cout<<" " << i; }
63,873,475
63,874,032
Wrap with a function to return a different type
I have a struct x which needs to be converted to something else before it is given to a function as an argument. For example, static struct ss x = {{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}}; int out1 = function1( std::span<const a>(x)) int out2 = function2( std::span<const a>(x)) int out3 = function3( std::span<const ...
I think this is what you want: span funx () { return span (x); }.
63,874,190
63,881,349
How to set a mesh with a material to actor in C++?
How to set a mesh with a material to actor AMySphere? void AMyActor::DrawSpheresAtLevel(int level_) { // 1. Generate parameters... if (0 != level_) { spheres_count += spheres_count / 100 * factor; radius += radius / 100 * rad_factor; // radius of a circle with a player placed at the center ...
If you need just a sphere you can add a component like this in AMySphere::AMySphere and add whatever material you want to this component. USphereComponent* SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("RootComponent")); RootComponent = SphereComponent; SphereComponent->InitSphereRadius(40.0f); If yo...
63,874,324
63,874,388
static_cast<unsigned> vs static_cast<unsigned int>
I'm new to C++, so please take this lightly. I was using resharper to convert some code from c-style casts to c++ style casts. This code here: (unsigned int)(ch - start) <= (unsigned int)(end - start); Was changed to static_cast<unsigned>(ch - start) <= static_cast<unsigned>(end - start); instead of: static_cast<unsi...
Is there ANY difference? unsigned int has 4 more characters than unsigned. There are no other differences. And also, is there any peformance differences? No.
63,874,607
63,874,674
Supported Operations for Implicitly Defined User Conversion Operators
I'm currently learning how implicitly defined conversion operators (also known as user-defined conversions) work for a given class. In my particular case, I wanted to test out my class to be implicitly converted to the default integer type. Found below is my code snippet. #include <iostream> using std::cout; using std...
These operators: cin >> foo; // >> endl is a bug foo *= 2; foo++; can only be called on an l-value. Your conversion operator returns a temporary int, which is not an l-value. Also, your operator is const qualified, which means it can only be called on const A instances. You need to provide a con...
63,874,789
63,922,767
Get HID report Descriptor from .pcap file
I am building a C++ app on windows that should reinterpret USB data stream captured by Wireshark and USBPCap stored into a .pcap file. I am currently having trouble to get HID Report descriptor, so then i would be able to interpret data that mouse sends to the host. The site USB Made Simple has been a great source of i...
Is there any way to get HID REPORT DESCRIPTOR from this or am I missing something out ? Don't know about you but for me that looks like Wireshark/USBPCap is missing something. If you compare it with mine example it looks like entries with USBHID protocol are missing in your part. Please check your Wireshark version ...
63,874,868
63,874,929
Compare strings character by character using iterators in C++
I have to create a compering function using string iterators and recursion. This is what I have enum class Order { LT, GT, EQ }; Order compare(std::string::iterator a, std::string::iterator b) { if (*a < *b) return Order::LT; else if (*a > *b) return Order::GT; else compare(a + ...
You need to return the value of the recursive call. Order compare(std::string::iterator a, std::string::iterator b) { if (*a < *b) return Order::LT; else if (*a > *b) return Order::GT; else return compare(a + 1, b + 1); }
63,875,203
63,875,268
Why does push_back() create two zeros at the start of the vector
Considering the following code and input #include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> v(n); while(n--) { int a, b; cin >> a >> b; v.push_back(a); v.push_back(b); } for(auto item : v) cou...
What behaviour of vector.push_back() I'm I not understanding? push_back does what you expect; the problem is vector<int> v(n); where in your example create the vector with 2 elements. Simplest fix is vector<int> v;
63,875,413
63,875,510
Grokking the comma operator
I am trying to grok the comma operator. The reference says: In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (...), and its side effects are completed before evaluation of the expression E2 begins (...). I am unable to grok the clause - "... the expression E1 is evaluated, its re...
In C++ an expression can result in a value and can cause side effects. In the expression ++x, --y you have two sub expressions forming the whole expression. The left, ++x returns x after increment, and the right returns y after decrement. The expression will return the right side of the comma (y) rather than the left s...
63,875,579
63,875,622
Undefined reference to, problem with inheritance - C++
I'm getting both of following errors: "undefined reference to `Vessel::Vessel()' " and: "Id returned 1 exit status" but nothing shows up. How do I fix it? I tried everything but I can't come up with a solution. It can be seen that the problem is in merging in classes or references but I can't figure out what exactly He...
The problem is here: class Vessel{ ... public: Vessel(); You'll need to provide a definition for the default ctor, for example Vessel() = default; Note, you have a parameterized ctor for Vessel that's not utilized, at least not in your code snippet. Did you mean for that to be there? If so, did you mean to...
63,875,627
63,875,723
How to pass non-static member function as template argument to another member function?
I want to do something like this: struct S { void mf() {}; template <auto f> void func() { f(); } }; int main() { S x; x.func<x.mf>(); } However, these are the errors: error: no matching function for call to 'S::func<x.S::mf>()'` note: candidate: 'template<auto f> void S::func()' note: t...
Calling member functions through a pointer can be so tricky. You want to pass a member function pointer to S::mf like so: struct S { void mf () {std::cout << "called mf\n";}; template <auto f> void func () { (this->*f)(); } }; int main() { S x; x.func<&S::mf>(); }
63,875,650
63,875,664
how can I create a bitmaped data in c?
I am trying to create a bitmaped data in , here is the code I used but I am not able to figure the right logic. Here's my code bool a=1; bool b=0; bool c=1; bool d=0; uint8_t output = a|b|c|d; printf("outupt = %X", output); I want my output to be "1010" which is equivalent to hex "0x0A". How do I do it ??
The bitwise or operator ors the bits in each position. The result of a|b|c|d will be 1 because you're bitwise oring 0 and 1 in the least significant position. You can shift (<<) the bits to the correct positions like this: uint8_t output = a << 3 | b << 2 | c << 1 | d; This will result in 00001000 (a << 3) 000...
63,875,697
64,020,521
WinAPI What happens if I don't Translate and Dispatch unhandled message
On GetMessage reference from microsoft we have the next example: BOOL bRet; while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0) { if (bRet == -1) { // handle the error and possibly exit } else { TranslateMessage(&msg); DispatchMessage(&msg); } } What if I just ignor...
According The Message Loop, The TranslateMessage function is related to keyboard input. It translates keystrokes (key down, key up) into characters. You do not really have to know how this function works; just remember to call it before DispatchMessage. The link to the MSDN documentation will give you more information...
63,875,748
63,875,890
How to do variadic template for even position in c++?
I have to write a variadic template function that returns true if the value of every even position is lower than the value of the parameter on the next position. Example: f(4, 5, 7, 9, 2, 4) -> true (4 < 5, 7 < 9, 2 < 4) i tried this : template<typename T> T check() { auto even_number = [](T x) { return (x % 2...
#include <iostream> template <typename ... Ints> constexpr bool check( Ints... args) requires(std::is_same_v<std::common_type_t<Ints...>, int> && sizeof... (Ints) %2 == 0) { int arr[] {args...}; for(size_t i{}; i < sizeof... (args)/2; ++i){ if (!(arr[2*i] < arr[2*i + 1])) return false; } retur...
63,876,280
63,876,320
Passing lamda to std::find
Probably its a late night struggle, but I am stuck with a simple thing here guys: int main() { std::vector<int> v{1,2,3,4,5 }; int N; std::cin>>N; auto it = std::find(v.begin(), v.end(), [=](auto it) { return it*it == N; }); } I just want the first value whose square is N, a...
You need find_if instead of find.
63,876,596
64,190,694
Is it possible to make mods in C++ for the bedrock edition on a Windows 10 PC?
(thread title) bedrock minecraft more recognizable as "Windows 10 Edition" Minecraft, is it possible to create a sub category UI menu similar to that in Java minecraft where it says "mods" but in bedrock? and to add mods you make a mods folder that adds the mods coded in C++ (which the language bedrock/windows 10 MC is...
although this has been answered by @Kosaro, I just wanna add that you can create plugins to use on a PocketMine server. this is mainly written in YAML and PHP, so its not really what your looking for exactly but it a bit more open than just the addons that Minecraft allows you to create. plugins like this are what make...
63,876,782
63,876,808
Error while implementing a C-API text block class in C++
class Text { public : char& operator[](int pos) const {return text[pos];} char* get() const {return text;} private: char* text = "hello"; }; int main() { Text a; char * x = &a[0]; *x = 's'; cout << a.get() << endl; } I was following Scott Meyers Effecti...
This line: char* text = "hello"; is not valid C++, since string literals decay to a const char *. With the correct command line flags, your compiler should have warned you about this. Following on from there, *x = 's'; results in undefined behaviour, because x is pointing into said string literal. In practise, you g...
63,876,787
63,878,103
Is replacing a simple method (e.g vector::size()) by a const reference field a good idea?
For example, this is my implementation of vector: template<typename T, /*...*/> class List { private: /*...*/ int count; int capacity; public: /*constexpr int Count() noexcept { return count; }*/ /*constexpr int Capacity() noexcept { return capacity; }*/ const int& Coun...
There is no benefit to adding reference-members to your class -- the public methods that you have commented out are more efficient, since the compiler will not be constrained by aliasing issues when optimizing them. Also there are several drawbacks to using reference-members: They increase the size of your class-obj...
63,877,573
63,877,638
To many char read by fread
Im am trying to open a file in binary mode and write the content to a buffer in C++. I am using fread for this. However something goes wrong. My code is: FILE * in = fopen("in", "rb"); _in = new unsigned char [length_in]; fread(_in, sizeof(char), length_in, in); When debugging i can see that _in = unsigned char * "As...
Your array is created uninitialized, so those are garbage values from whatever was in memory beforehand. Initialize it to zeros like this: _in = new unsigned char [length_in](); Also fread returns the number of bytes read. If you’re treating it like a string, make sure the result is null-terminated.
63,877,668
63,877,702
How to check if std::max_element returned an element?
I'm learning about std::max_element. I wrote the following code: auto e = std::max_element( std::begin(rtspUrls), std::end(rtspUrls), [](const RTSPUrl &p1, const RTSPUrl &p2) { unsigned int area1 = p1.resolution().width() * p1.resolution().height(); ...
From cplusplus.com: Return value An iterator to largest value in the range, or last if the range is empty. So to check if it actually returned something, you compare it against std::end(rtspUrls). If it's equal, then it didn't. If it's not equal to that, then it returned something, and you can access it via dereferen...
63,877,879
63,882,233
Could it be problematic to point to a character array in a member function?
int setString(char *pcString) { if( NULL == pcString ) { pcString = ""; } if( NULL == m_pcData ) { m_pcData = new char[m_nBufferLength]; memset(m_pcData, '\0', m_nBufferLength); } int nCurrentBuffer = 0; int nLength = 0; int nInputS...
The pcString is declared as pointer to character(s), so it is implicitly assumed that these characters can be changed. The literal "" is a string of constants characters, so it can not be changed. For backward compatibility reasons, C++ allows you to make the assignment: pcString = ""; but the following code will not ...
63,878,026
63,880,198
Changing Background color of QCheckBox
I want to have a checkbox with the following style: For that purpose I have created the follow stylesheet: QCheckBox { background-color : cyan; } QCheckBox::indicator { width : 20px; height : 20px; } sadly the result was not was I expected, here is what I get: But I want to have all background with the color cyan. I...
I did not solve my problem using the stylesheet commands, I actually think that it is not possible SOURCE. Anyway, I was I able to achieve my goals using one image for the checked state and another one for the unchecked state as follow. QWidget* w = new QWidget(); QCheckBox* cb = new QCheckBox(w); cb->set...
63,878,357
63,878,394
Why getting a runtime error while using string in struct
Details- I am taking input of n students Their number- rollno./mobile/UID in union, their full name, their course name, their age, their branch name. I am using a linked list to store the data in a sorted manner. As soon as I insert a node, the list becomes sorted simultaneously. In the end, I print the whole list. The...
The first thing you should do is replace node *temp=(node*)(malloc(sizeof(node))); with node *temp=new node; Don't use malloc in a C++ program. The reason is that malloc does not call the constructors for the objects it allocates. std::string has a constructor and this must be called or you will get errors. The...
63,878,619
63,879,136
How to find median of `std::set`
I'm trying to find the median of a std::set. Since std::set already sorts everything, I just have to pick the middle element. My idea is to advance to the half: std::advance(e, rtspUrls.size() / 2);, but I'm not sure how it'll behave. What about numbers like 1.5? Will it advance to something? I'm using a try catch to t...
With std::set you are limited to using iterators to iterate to the middle element (in case of an odd number of entries in your set) or iterating to middle-1 and middle and taking the average (int the case of a even number of entries) to determine the median. A simple loop and a counter is about as straight-forward as i...
63,879,108
63,879,146
What is the right way to use access a value in an enumeration in C++
I have come across this while coding and I am not sure about why its the way It is. Consider this code Case 1 #include<iostream> enum test{ a,b,c,d,e,f }; int main(){ std::cout << a; return 0x1; } Case 2 #include<iostream> enum test{ a,b,c,d,e,f }; int main(){ std::cout << test::a; return 0x1; } W...
No, test:: is not neccessary, because enum test declares an unscoped enum. test:: would become neccessary when you define a scoped enum like this: enum class test {...}; See also https://en.cppreference.com/w/cpp/language/enum for more detailed information.
63,879,132
63,879,167
How to initialize anonymous structures in class constructor?
How could i initialize anonymous structures ? class A { public: A() : m_var.var_1(1) { } private: struct { int var_1; int var_2; }m_var; }; The above code give me this error when i try to compile it: main.cpp: In constructor ‘A::A()’: main.cpp:6:16: error: expected ‘(’ be...
You have to initialize the whole object, not the subobjects of the data member. This is not just special for anonymous struct. E.g. A() : m_var{1, 0} // m_var.var_1 and m_var.var_2 are initialized as 1 and 0 { } And since C++20 we can use designated initializers to specify data member of the struct in initialization. ...
63,879,483
63,879,572
Does the order of arguments while returning a pair/struct/tuple matter in following code?
In the following code, is the return value correctly created. I have some doubt as both the arguments to the pair constructor are related. Does the use of move for second argument corrupts the first argument. Or if the first argument is always created before the second argument: class A { private: struct B ...
From this evaluation order reference: In list-initialization, every value computation and side effect of a given initializer clause is sequenced before every value computation and side effect associated with any initializer clause that follows it in the brace-enclosed comma-separated list of initalizers. What it is...
63,879,541
63,913,994
Redirecting output to file then back to console in C++
The task is to read input from input.txt and write the output to output.txt. However on completion of the above tasks, further instructions/output should now be displayed to the console. Came to know about freopen() in c++ which works fine for the first half of the given task. But unfortunately, I have no idea how to r...
Probably what you are looking for is rdbuf() as mentioned by doomista in the comments. Here is a way to redirect Output. #include <iostream> #include <fstream> int main() { /** backup cout buffer and redirect to out.txt **/ std::ofstream out("out.txt"); auto *coutbuf = std::cout.rdbuf(); std::cout.rdb...
63,879,792
63,881,376
Call function on one of many vectors without enum and switch
I have a class that contains several vectors of unrelated classes. class Class0 {}; class Class1 {}; class Class2 {}; enum class RemoveFromVector : uint8_t { CLASS0 = 0, CLASS1 = 1, CLASS2 = 2 }; class C { public: std::vector<Class0> c0s; std::vector<Class1> c1s; std::vector<Class2> c2s; void RemoveFromV...
I think std::variant and std::visit are the way you can go. You also can use a new helper function make_variant_array to make the code even shorter: #include <cstdint> #include <vector> #include <variant> #include <array> #include <functional> class Class0 {}; class Class1 {}; class Class2 {}; enum class RemoveFromV...
63,879,948
63,880,288
Correct way of freeing memory of a vector of structs
What is the correct way of freeing the memory of an std::vector of struct? Consider the following pseudo-code: typedef struct { unsigned int packageLen; unsigned char* package; } PACKAGE; std::vector<PACKAGE*>* packages = new std::vector<PACKAGE*>; for (...) { PACKAGE *tempPackage = new PACKAGE; // Set da...
No, you are leaking memory. Here's a the right wayTM struct Package { // ... }; int main() { std::vector<Package> packages; // no pointers involved // Can use vector::reserve at this point if you know how many // elements you are going to need for (...) { packages.push_back({ /*...*/ }); // may a...
63,880,219
63,886,648
Qt C++ class data json serialization
I have custom class Person. It looks like below. class Person : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(int phoneNumber READ phoneNumber WRITE setPhoneNumber) Q_PROPERTY(ChildPerson* childData MEMBER m_childData ) public: Person(){ m_name = "Fl...
First add functions to translate your objects into JSON objects. QJsonObject Person::toJson() const { QJsonObject obj; obj["name"] = m_name; obj["phone"] = m_phoneNumber; if (m_childData) obj["child"] = m_childData.toJson(); return obj; } QJsonObject ChildPerson::toJson() const { QJsonO...
63,881,316
63,882,257
Why is Switch Statement skipped?
I want to learn why the switch statement is skipped in my code? The Compiler just not read the data in the switch statement and returning 0. I must be doing something wrong but can't point the mistake if it is a reason! Code: #include <iostream> using namespace std; void mainMenu(); void ResultUsr(int); int main() ...
In the main Function you must send and bind the user input by using the variable which you are already using to take user input. EX: In the main Function You are taking user input by variable userChoice and Binding ResultUsrInput in the switch statement which is empty and return 0 or default case. Bind userChoice or ta...
63,881,320
63,881,699
How to conditionally write code that's dependent on lambda's return type in C++?
I have function that invokes callback for every element it iterates: #include <type_traits> #include <iostream> using namespace std; void iterate( const auto & on_element ) { for ( int i = 0; i < 10; ++ i ) { //here I want to stop iteration if function returns bool true: if constexpr ( is_same< res...
on_node is not a name in your example, and std::result_of doesn't have that syntax (and is deprecated in favor of std::invoke_result). I think you mean std::is_same_v<std::invoke_result_t<decltype(on_element), int>, bool>
63,881,528
63,882,111
A question about atomic operation and its c++ exposition
I have a question about atomic operation, and its exposition in c++: std::atomic<int> my_value{0}; //... // executed on thread 1 int a = my_value++; //... //executed on thread 2 int b= my_value++; To me, std::atomic::operator++ ensure that my_value == 2 , but does it also ensure{a=0, b=1} or {a=1, b=0} ? From wha...
From what I understand only the increment operation is atomic... That's wrong. Both reading the actual value and (post-)increment is a single atomic operation. It's the same as fetch_add(1);. Note that "fetch" in the operation name.
63,881,752
63,885,171
got receive_from: Bad file descriptor while using boost::asio
#include "string" #include <boost/asio.hpp> #include <boost/asio/io_context.hpp> using namespace boost::asio::ip; class A { public: std::string address; std::string port; boost::asio::io_context io_context; udp::socket socketInstance = udp::socket(io_context); udp::endpoint endpointSetup; ...
The problem is with your declaration of the aClass member in B: class B { public: A aClass; explicit B(const A& a) : aClass(a) {} ... The aClass member is of type A, so when you do aClass(a), a copy is performed. You have defined a copy constructor for A, but it does not copy the already opened socket, l...
63,881,766
63,930,387
Does mutex have scope?
Does std::mutex have scope? I know in JAVA we can use {} to limit the lock in scope to release the lock as soon as possible. If we can do the same thing in c++ ? void func() { // some code { std::lock_guard<std::mutex> lock(mutex_); } // some code } additional, when did the mutex work? Does the lock work a...
With help, I finally found the answer. Read the source code, then no magic. Below is lock_guard's source code. template<typename _Mutex> class lock_guard { public: typedef _Mutex mutex_type; explicit lock_guard(mutex_type& __m) : _M_device(__m) { _M_device.lock(); } loc...
63,882,085
63,882,472
Template overload based on condition
With type traits I can do the following: template<typename Rect> Rect& move(Rect& rc, size_type<Rect> delta) { rc.left += delta.width; rc.right += delta.width; rc.top += delta.height; rc.bottom += delta.height; return rc; } template<typename Rect> Rect& move(Rect& rc, point_type<Rect> to) { int ...
What I want to do is template<typename Rect, typename Size /*if Size::width, use this*/> Rect& move(Rect& rc, Size size); template<typename Rect, typename Point /*if Point::x, use this*/> Rect& move(Rect& rc, Point to); I.e. choosing an overload depends on whether a template argument has a particular member. ...