question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
66,814,399
66,815,035
Convert void* to const void**
In CPP I use a C library, one of the method needs a const void ** as parameter. In my class I have a property whose type is void *. I tried to call the function by doing function(&my_property) but the compiler complained that it could not convert a void ** to a const void **. To fix this issue I used a const cast and d...
Proper solution would be to turn my_property into const void*. Otherwise you might break a contract of function.
66,814,870
66,815,016
How to get element from const map?
I have some struct like bellow to get static const map: struct SupportedPorts{ static std::map<std::string, std::string> init() { std::map<std::string, std::string> port; port["COM1"] = "ttySO1"; port["COM2"] = "ttySO2"; port["USB"] = "ttyUSB0"; return port...
The operator [] is declared for the class template std::map the following way T& operator[](const key_type& x); T& operator[](key_type&& x); That is the the operator returns a non-constant reference that may not be done for a constant object. And the operator may be called only for a non-constant object because it is...
66,815,095
66,815,198
change pointer type from malloc type and free it. Does it lead to memory leak?
I use malloc to allocate memory which is used by a pointer type. And then I forcefully modify pointer type. use free func to release the memory block. I am curious to know whether memory leak happens? I thought memroy was free by pointer type. "int *b" has wider range memory block than "char *a". I compile the followin...
The routines in the malloc family keep track of all the memory they reserve, including the sizes. When you pass an address to free, the routines look up the address in their records and release the amount of space that was allocated for it. free is only passed an address. It has no information about the type of the poi...
66,815,102
66,817,121
Directly send signals to USB using Python
How can I set HIGH or LOW to a usb port connections using Python. This could be used in come custom usb device. For Example, Consider I have a LED connected to the usb port(DATA Line) . Now through the code I want to blink it or control it. Now this can be easily achieved by using any micro controller, Arduino, Raspbe...
Controlling components like LEDs from devices like Arduino and Raspberry Pi are done using GPIO pins. In contrast, USB is designed for data transfer and not for maintaining more constant high or low signals like GPIO. It also consumes different voltage and current levels than GPIO pins and could potentially damage comp...
66,815,512
66,816,127
Including files correctly , but still getting linker error
hope you guys are doing well. I am just getting linker error in C++ , I don't know why? Everything is correct.... Check below testing.h file #ifndef __MYClass__ #define __MYClass__ #include<iostream> using namespace std; class Abc { private: int a; public: void input(); void display(); }; #endif and h...
There are multiple ways you can fix this but before that please read up on Translation Unit. Coming to your problem. When you write g++ -Wall -o main main.cpp The compiler will pick up main.cpp for compilation and expand testing.h that includes the declaration for class ABC and with this header file it can determine w...
66,815,590
66,815,881
C++ using string_view in constexpr if
I want to compare string views at compile time like this: constexpr bool isMatch(const string_view str) { if constexpr (str == "firstMatch"sv) { return true; } else if constexpr (str == "secondMatch"sv) { return true; } // .... } And the function is called like this: isMatch("something"sv); Which i...
how can I have a constexpr function that checks for these kind of matches Just remove the constexpr from ifs. constexpr bool isMatch(const string_view str) { if (str == "firstMatch"sv) { return true; } else if (str == "secondMatch"sv) { return true; } return false; } std::string_view::operator== i...
66,815,743
66,816,131
Wrapper for a callback from a weak poitner
Quite often I use the following approach for a callback: scheduleCallback(std::function<void()> callback); class MyClass { void test() { ... scheduleCallback([weakPtr{weak_from_this()}](){ if (auto sharedPtr = weakPtr.lock()) sharedPtr->someFunction(); }); } void someFunction(); } to ...
Maybe you want something like: template<typename C, typename... Args, typename... ExtraArgs> constexpr auto weak_function(std::weak_ptr<C> weakPtr, void (C::*mf)(Args...), ExtraArgs&&... extraArgs) { return [weakPtr, mf, extraArgs...](auto&&... args) { ...
66,816,301
66,816,831
Is there a safe version of C++ without undefined behaviour?
Undefined behaviour in C++ can be really hard to debug. Is there a version of C++ and standard library which does not contain any undefined behaviour but rather throws exceptions? I understand that this will be a performance killer, but I only intend to use this version when I am programming, debugging and compiling in...
Undefined behavior Undefined behavior means that your program has ended up in a state the behavior of which is not defined by the standard. So what you're really asking is if there's a language the standard of which defines every possible scenario. And I can't think of one language like this, for the simple reason that...
66,816,335
66,816,484
When a fixed-length char array is initialized with a short string, how is the remaining space initialized?
char s[10] = "Test"; How are the remaining chars (after "Test" and terminating null) initialized? (Is it defined?) Background I'm doing this to write a custom fixed-width (and ignored) header into an STL file. But I wouldn't like to have random/uninitialized bytes in the remaining space.
The general rule for any array (or struct) where not all members are initialized explicitly, is that the remaining ones are initialized "as if they had static storage duration". Which means that they are set to zero. So it will actually work just fine to write something weird like this: char s[10] = {'T','e','s','t'};....
66,817,173
66,825,908
Shared library problems between C++11 and C++14
I have had to switch from C++11 to C++14 in my project to use the Catch testing framework, written for C++14 (it doesn't compile with anything less). Everything compiles fine. However, while running the program, the following function causes a series of errors which seem linked to a mismatch between C++11 and C++14 sha...
The error is inside malloc, after it has printed some error message (usually double-free or something similar) indicating heap corruption. While it is possible that you have some kind of library mismatch, it is much more likely that you have a plain heap corruption bug in your own code (overflowing heap buffer, double ...
66,817,211
66,817,283
C++ header file: error: expected unqualified-id before ')' token
Sorry for asking such a beginner question, but I'm stuck writing header files. For information, there aren't StackOverflow articles relating to the problem I have -- it seems like I've got a very simple setting wrong but couldn't find it on the internet. Error message: insertion/insertion.h:16:24: error: expected unqua...
#define insertion colides with void insertion();. Change #ifndef insertion #define insertion to #ifndef _insertion_h_inc_ #define _insertion_h_inc_ Or better: change #include <iostream> // exactly the same imports as the file above but didn't import itself #ifndef insertion #define insertion class Insertion { p...
66,817,513
66,817,697
GMP stuck generating same random integers
I would like to generate a random integer z of n bytes such that 2^(n-1) <= z <= 2^n - 1 Whenever I run the following code gmp spits out the same exact integer, what am I doing wrong? // Random int of n bits. const auto n_bits = 1024; mpz_t mpz_int; gmp_randstate_t state; mpz_init(mpz_int); gmp_randinit_default(state);...
gmp_randinit_default apparently sets the seed to some fixed value. You are supposed to call gmp_randseed or gmp_randseed_ui afterwards to set the seed to your own value which will not be the same on every run. For an initial test, you could try gmp_randseed_ui(state, getpid()). On Linux you can get a much more random...
66,818,089
66,824,700
c++: Efficient way to passing shared_ptr to a lambda
I've created a small program years ago, and I've recently stared to use smart pointers. So for practice reasons I refactored some part of the code based on Scott Meyers - Effective Modern C++ book. Imagine a class, that holds a member shared_ptr of another class, that manages the life cycle of some other unnecessary ob...
For situations like this one, I always recommend to be clear about this question first: Can my lambda legally be called after the lifetime of this? If so, capturing this would not be the way to go here. A similar question is then: Is my lambda allowed to extend the lifetime of this? If so, capturing this and the accord...
66,818,233
66,818,282
C++ Segmentation fault core dumped for simple vector operation
I have the following code c++ code #include <vector> #include <iostream> using namespace std; #define for_loop(upper_bound) for (int i=0;i<upper_bound; ++i) // #define SHOW_VECTOR(vec_in) for(int j=0;j<vec_in.size();j++){ cout << vec_in[j] << " " << endl;}; int main(){ int dim_1=10; int dim_2=3; int o...
You need to size both your outer and inner vectors vector<vector<int>> vec_var(dim_1, vector<int>(dim_2)); // ^ inner vector default size Otherwise as written, you have an outer vector if size dim_1 but all of the inner vectors are empty. As an aside, since I notice you then filling the...
66,818,658
66,819,060
Using std::iota to fill an alphabet vector
In this code I'm filling the vector alpha with letters from 'a' to 'z': std::vector<char> alpha(26); std::iota(alpha.begin(), alpha.end(), 'a'); I'm assuming this will not work with all character encodings, can anyone confirm? Or deny? And if the former is true, is there any solid alternative?
The behavior of std::iota is very simple: Fills the range [first, last) with sequentially increasing values, starting with value and repetitively evaluating ++value. This means your code will only work when the encoding represents the characters 'a', 'b' ... 'z' in increasing order. This is the case with ASCII encodi...
66,819,320
66,819,454
Having a problem calculating the compounded Interest
I tried as I/P: 100, 10, 1 and it works fine so CI = 10 and total = 110 But with other example I can't get right answer can you please tell me what to do. I tried to look at other questions here but I can't understand what the wrong I did. #include<iostream> #include<math.h> using namespace std; int main() { fl...
Code: #include<iostream> #include<math.h> using namespace std; int main() { float amount,rate,time_,total,compoundedInterest; cout<<"Amount: ";cin>>amount; cout<<"Rate of Interest: ";cin>>rate; cout<<"Time: ";cin>>time_; compoundedInterest=amount*pow((1+rate/100),time_)-amount; total=am...
66,819,838
66,820,010
CMake not finding headers from library in subproject
Update: Fixed I've corrected the CMakeLists.txt file below: I had left out a slash. So the solution was adding ${CMAKE_CURRENT_LIST_DIR} to the path for target_include_directories. I'm trying to use libharu as a subproject. I've set it up as a git submodule in my project in the libharu directory and made edits to the C...
I fixed up the code real quick based on my guesses. add_executable(gftodvi) # This part is probably fine add_subdirectory(libharu) target_link_libraries(gftodvi PRIVATE libharu) # This line is the probably the cause of your problems # If libharu was written using modern cmake this wouldn't have been an issue. # Beca...
66,820,605
66,824,950
Initialize multi-level pointer to pointer and compile error occurs
I have multi-level pointer to pointer code like this: int main(int argc, char **argv) { int a = 1; int *pa = &a; //int **ppa = &pa; // [Right Code] int **ppa = &&a; // [Wrong Code] int ***pppa = &ppa; *ppa = pa; **pppa = pa; *pppa = &pa; } When using gcc...
No, that's incorrect syntax in both C and C++. Step back a bit and think what would an address of address mean. @sweenish has provided an excellent example of that in real life. I'll resort to a bit of assembly. int a = 1; int *pa = &a; This translates to assembly something on the lines of mov DWORD PTR [rbp-1...
66,820,681
66,821,371
c++ multiple template template parameter
I'm reading some references online and I'm confused about template template argument. In particular I do not understand how the inner template parameter are passed according to their position. Perhaps an example will help to understand what is my confusion What I was trying to do is the following. I have template <type...
template <typename A, typename B, typename DepA, typename DepB> class aClass; template <class A, class...As, class B, class...Bs, template<class...>class DA, template<class...>class DB> class aClass<A, B, DA<A, As...>, DB<B, Bs...>> { // ... }; is one approach; this enforces that the DepA/DepB take A/B as the firs...
66,821,409
66,821,452
Generating binary number using bitset causing segmentation fault in c++
Generating binary representation of numbers from 0 to 255. This is causing segmentation fault. Kindly enlighten. vector<bitset<7>> vb; for (i = 0; i < 256; i++) { bitset<7> b(i); vb[i] = b; } //print for(i=0;i<256;i++){ cout<<vb[i]<<"\n";
Your vector is of size 0. Either use vb.push_back(b); or initialize a size like: vector<bitset<7>> vb(256);
66,821,417
66,902,770
Capturing a video from multiple thread Opencv in Cpp
I am learner in Cpp and opencv,I am trying to access the same video from multiple thread and while doing it I am getting deadlock which is pretty expected I am creating n threads and trying to process the video by dividing it in n part and simultaneously process it in different threads.this is my void function.I found ...
So as the task was just a course assignment what I did is loaded the whole video frames in memory(which is not a good practice) and than used mutex lock to access the frames from every thread the video size was small (174MB) but I was able to store video at 5FPS in my memory and then completed the task. But if there is...
66,821,476
66,822,435
How do the AVX(2) gather instructions actually compute the fetch address?
The current Intel intrinsics guide for _mm_i32gather_epi32() describes the computed address for each subword as: addr := base_addr + SignExtend64(vindex[m+31:m]) * ZeroExtend64(scale) * 8 That last 8 puzzles me. Assuming addr and base_addr are in bytes and scale takes a value of 1, 2, 4 or 8, then you can only ever in...
Note the next line in the pseudo-code: dst[i+31:i] := MEM[addr+31:addr] Apparently someone decided it would be a good idea to describe the memory address as a bit-address, not a byte-address. /facepalm. Which doesn't really make sense, is not what anyone would expect, and isn't even done right because they failed to s...
66,821,478
66,821,581
What Happens in Scanf When We Using & Operator?
When we using '&' operator in scanf, do we scan address or exact value in that adress? For instance i don't understand how this 2 code give to us same result. CODE 1 #include <stdio.h> int main(){ int arr[6], i, sum=0; for(i=0;i<6;i++){ scanf("%d", &arr[i]); sum+=arr[i]; } printf("%d",...
scanf() requires you to pass it the address of each variable that you want it to write parsed values to. The & operator returns those addresses. In your examples, &arr[i] and (arr+i) both represent the same address of the i'th array element, and also arr[i] and *(arr+i) both represent accesses to that same element's st...
66,821,952
67,000,791
Clang error "implicit instantiation of undefined template std::tuple_size<auto>"
Is there a (clean) work-around to Clang's behavior "undefined template smthg<auto>" ? Code example : https://godbolt.org/z/GGs7ndKE4 (see below for copy/paste) Additional insight : This issue is not reproductible with GCC nor MSVC/CL, thus only affect clang and clang-cl Clang-cl add the following error message : e...
Thanks to @Yakk - Adam Nevraumont, and as conclusion, here is the way I fixed it : using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>; constexpr static inline auto as_array_v = as_array_t{trait<Ts>::value...}; This avoid another #if __clang__ /* workaround ...
66,822,017
66,822,395
C++ Return const reference from function with temporary parameter of custom non-duplicable object
I am struggling with miniproject, where I have to do this const Foo &f = func(arr(1.3, 2.4, 3.8, 4.3)); Foo is non-duplicable class containing single float value as memeber, arr is simple function that returns std::vector of Foo objects initialized with values passed as parameter into arr. Finally func is defined as f...
If func were to return by value, it would return a temporary object whose lifetime would be extended to that of f. However, the object needs to be moved from the input array since it cannot be copied. This is a problem because the input parameter is a const reference. So provide an overload that takes a movable paramet...
66,822,702
66,823,075
C++ optimization - stack allocated array type with externally linked dimension?
I'm new to optimization in C++. I have read that stack allocated memory can be much faster than heap allocated memory. I also have read that std::array is stack allocated, but most other containers, like std::vector or dynamic arrays are heap allocated. I'd like to define a class which essentially just stores an array ...
You are asking for a template: template<int dimension> struct Coordinates { std::array<double, dimension> q{}; }; Usage: int main() { constexpr auto dimension = 2*3*100; Coordinates<dimension> c; c.q[0] = 1; c.q[1] = 2; // ... } Demo
66,822,748
66,822,833
Adding the values of two pointers and saving the addition into another pointer
I'm a beginner but what I'm trying to do is getting the value of two pointers and saving the 'action' of their addition. I thought pointer to function would work but can't find how to initialize a pointer to a function with it's parameters. Something like this. int foo(int *a, int *b){return *a + *b;} //main int *a =...
You can't have a pointer depend on the values of multiple other pointers the way you want. But you could write a lambda that captures the dependent variables by reference, and returns the value returned by the call to foo. Any changes to the values pointed at by the pointers will be reflected in what the lambda returns...
66,822,756
66,822,881
How the compiler infer types using strategy pattern (with overloaded() in struct or class)?
I am struggling to understand how this code even compile when passing a "callable" struct/class. Referring to the main function below, I would expect the compiler to tell me that there is no matching constructor for Point3D (CallableI is not an instance of FuncType). What I would be tempting to do is to create an algo ...
std::function is a type erasure template. std::function<R(Arg0, Arg1)> is a type erasure type. It can be constructed with any value that you can: Invoke with () with Arg0, Arg1 and the return type can be converted to R Can be copied, moved, and destroyed. It is a kind of polymorphism that does not require inheritance...
66,822,885
66,822,987
C++ Override Destructor and ownership transfer of a member variable
I am not very proficient in C++. So I'll explain my problem as clearly as possible and when you are answering,please do some explanation. So my problem involves 2 classes(A and B) with another class in a framework which I don't have access to. A has a pointer to B and B has a pointer to the A (raw pointers). The follow...
As soon as the call to SomeServiceClass::doSomething(std::unique_ptr<B>(this->b_)); ends, the destructor of the unique_ptr has destroyed what it points to, potentially* making b_ a useless dangling pointer. Do not try to read b_ anywhere else, which includes not deleting it in A's destructor. If a function takes a uni...
66,823,146
66,835,485
boost::split to split only if delimiter is present in c++
I am using boost::split but if the string has no delimiter then it returns the string in the vector. I want it to not return anything if delimiter is not there in the string. #include <iostream> #include <string> #include <bits/stdc++.h> #include <boost/algorithm/string.hpp> using namespace std; int main() { str...
It looks a bit like you might need a validating parser. Regex could be a good starting stone, but I'd suggest a parser generator, as in all likelihood you require more My crystal ball whispers that you might be parsing command line output or CSV/TSV files This is what you could do with Boost Spirit X3: template <type...
66,823,207
66,854,246
SSL_set_tlsext_host_name crashes
I'm trying to use scio_beast in a project. I understand its rather unfinished, but that should not matter much. I've managed to get it working pretty well. I'm trying to connect to a server behind CloudFlare now, an I understand I need SNI for that to work. Given the following: using tcp = boost::asio::ip::tc...
Turns out this was a linking problem: The app uses another library (WebRTC) that uses boringssl. Somehow the linker didn't complain about duplicate symbols when linking OpenSSL after WebRTC and silently used boringssl's functions. Both MSVC and gcc do it. I solved it by moving the websocket/OpenSSL code into a dll, whi...
66,823,260
66,823,431
Why is the memoized solution slower than the normal recursive solution?
I was implementing a function to compute the nth Catalan number. The formula for the sequence is the following: I noticed that the memoized solution was slower than the normal recursive solution. This is my code: #include <bits/stdc++.h> using namespace std; int catalan_number_recursive(int n){ if (n == 0) retur...
#include <bits/stdc++.h> using namespace std; int catalan_number_recursive(int n){ if (n == 0) return 1; else{ int ans = 0; for (int i = 0; i < n; i++){ ans += catalan_number_recursive(i)*catalan_number_recursive(n - 1 - i); } return ans; } } int catalan_number_...
66,823,562
66,823,765
How does cpprestsdk use MARCO to define constants
For example in include/cpprest/http_msg.h the header_names is defined as: class header_names { public: #define _HEADER_NAMES #define DAT(a, b) _ASYNCRTIMP const static utility::string_t a; #include "cpprest/details/http_constants.dat" #undef _HEADER_NAMES #undef DAT }; and in cpprest/details/http_constants.dat there's...
The header file contains the class declaration of the static variables. The corresponding definitions, including the initializations, are in release/src/http/common/http_msg.cpp. #define _HEADER_NAMES #define DAT(a, b) const utility::string_t header_names::a = _XPLATSTR(b); #include "cpprest/details/http_constants.dat"...
66,823,900
66,831,833
Writing to hdf5-file in C++ results in data being truncated at some point
Consider the following code: #include <H5Cpp.h> #include <vector> #include <eigen3/Eigen/Dense> #include <iostream> double* matrix_to_array(Eigen::MatrixXd const &input){ int const NX = input.rows(); int const NY = input.cols(); double *data = new double[NX*NY]; for(std::size_t i=0; i<NX; i++){ ...
After some trying out and consulting the examples of the H5 group, I got it to work. #include <iostream> #include <string> #include "H5Cpp.h" #include <eigen3/Eigen/Dense> using namespace H5; int main (void){ const H5std_string FILE_NAME( "data.h5" ); const H5std_string DATASET_NAME( "DOUBLEArray" ); const ...
66,824,023
66,824,186
C++ How to inherit from interface with a method of other interface type?
I have this structure: class IA { virtual void foo() = 0; }; class IB { virtual IA bar() = 0; }; So far I made the inherited versions of these two interfaces but I have difficulties with how to make concrete overriding of the IA IB::bar() method? I mean if I have a class A inheriting from IA then how to decla...
Welcome to the wonderful world of subtle differences between Java and C++. If you come from a Java background, a value of type IA is of type IA or any subclass thereof. But in C++, a value of type IA is a concrete instance of IA, nothing more and nothing less. And your IA is abstract, hence there are no concrete instan...
66,824,357
66,824,576
Allow only certain threads to execute in parallel
I got two member functions for a class, say foo1 and foo2. foo1 receives a string label and a data as inputs and calls foo2. class MyClass { public: void foo1(int data, std::string label) { // do stuff foo2(); } void foo2(void) {} }; Now, I want to be able to create threads for parallel executions of foo1, but ...
A mutex is exactly what you want. You just need 1 mutex per label, for instance in a std::map keyed by label. Then, foo1() can lock the std::mutex of the specified label, and unlock it when finished, eg: std::map<std::string, std::mutex> locks; class MyClass { public: void foo1(int data, std::string label) ...
66,824,671
66,824,706
Why can I use the constructor without an object declaration?
Why can I use the constructor without a previous object declaration? And, if the previous works, why do I get an error when using k()? Here is my code: #include <iostream> using namespace std; class Test { int i, x; public: Test(int ii = 0) { cout<<"WOW!"; cout<<i<<" "; i=ii; } void k() { cout<<i<<" "...
Why can I use the constructor without a previous object declaration? A constructor is used to create a new object. So it can't be called on a previous object. And, if the previous works, why do I get an error when using k()? Because k() is a non-static method of Test, so it needs a Test object to call it on. You ...
66,825,122
66,866,580
Reusing Nodes in implementation of a Decision Tree
I saw this Decision Tree implementation in this stream (is in spanish). #include <iostream> #include <ctime> #include <vector> #include <memory> struct Node { virtual void run() noexcept = 0; virtual ~Node() noexcept = default; }; struct ActionSay_t : Node { explicit ActionSay_t(std::string&& w) : ...
Because of that, we can't reuse the nodes. You cannot use the unique pointers to the nodes for another tree or in general after they are moved, that's clear. But you can still refer to the underlying allocated memory that is not(!) affected by the move operation on the unique pointers. So for instance, this is totall...
66,825,286
66,825,395
Compiling error | cannot compile cpp program due to compiler parser
Short Description I am trying to compile a short lambda to convert a giving input to string format. My overall class uses a template, i.e template <typename T>. I want to overload << to print-out an object which can be of any type; i.e, int, string, etc. For example, let's say that my object is {int age: 12, int* left...
You need at least C++17 to use if constexpr. With if constexpr you can write something as if constexpr ( std::is_same_v<T, std::string> ) return value else { // something else that return a std::string } Only this way you can exclude from the compilation return value, when T isn't std::string, and the ...
66,825,494
66,825,731
How do I retreive the first bit of a number (or specific bits) without a mask?
Assuming we're working in 16bits Lets say I have an algorithm that retrieves the signs from a very large list of numbers. I could do something like sign=(number>0)-(number<0) but I want to be more efficient than this. The very first bit of the integer(or float) should store its sign value. How could i tell the compute...
As has been said in the comments, you really should just let the compiler to its job and use the mask. And still, you will have to move the bits manually if you want to remove gaps like in your last example. If you do still want to access individual bits, you can use a bitfield structure: struct S { unsigned int b : ...
66,825,528
66,833,332
A way to distinguish `\e` from escaped keys like `\e[A` in C++
I'm writing a readline replacement in C++, and I want to process terminal input in raw mode, including special/escaped keys like "up arrow" \e[A. However, I also want to be able to distinguish between a single press of the escape key \e followed by a press of [ and a press of A vs a press of the up arrow. I assume that...
Seems like the key is to put the termios in nonblocking mode and then poll with usleep. Mixing std::cin with read also seems to break this; stick to read. termios enter_raw() { /* ... */ } int main() { termios orig = enter_raw(); while(true) { termios block; tcgetattr(STDOUT_FILENO, &block); te...
66,825,798
66,825,874
How do you initialise a std::unique_ptr to a reference
With raw pointers I can do: int x = 10; int* y = &x; x = 20; std::cout << *y; //prints 20 However, Im struggling to emulate the same behaviour with std::unique_ptr. Ive tried: int x = 10; std::unique_ptr<int> y = std::make_unique(&x); //doesnt compile std::unique_ptr<int> y = std::make_unique<int>(&x); //doesnt com...
unique_ptr is about managing the lifetime of dynamically allocated memory. That is to say std::unique_ptr<int> y = std::make_unique<int>(x); says allocate memory for an integer, copy the value of x into it and when y goes out of scope please release that memory. In your example, you are not interested in managing the ...
66,827,584
66,828,354
Why does push_back fail for unique_ptr of string vectors?
The code below has a segmentation fault. When there is not a unique_ptr involved everything works fine. #include <iostream> int main() { auto vect = std::unique_ptr<std::vector<std::string>>(); vect->push_back("abc"); // Segmentation Fault. vect->emplace_back("abc"); // Segmentation Fault. return 0; } In ...
You have declared a std::unique_ptr using its default constructor, so it is holding a nullptr pointer. You are not creating a std::vector object for it to point at. Use new to create the std::vector: int main() { auto vect = std::unique<std::vector<std::string>>(new std::vector<std::string>); // or: // std:...
66,827,666
66,830,904
C++ template function call seems to prefer the less specialized one
I'm trying to simplify some of my earlier JSON serialization by using C++ templates to somewhat reduce boilerplate code. All went fine, until I wanted to serialize types such as lists, since these are templates themselves as well and seem to require partial template specialization, which does not seem to exist for temp...
I have no idea why on earth this is happening, as I would expect that it would take the function template specialised for the QList. Does anyone have an idea why this is happening? When you call Support::toJsonValue<QList<int>>(foo); the following "convenience function" matches template<typename T> QJsonValue toJs...
66,828,295
66,828,570
Why " throw" will display a warning?
#include <iostream> #include <sstream> using std::string; using std::cout; using std::endl; using std::ostringstream; class illegalParameterValue { private: string message; public: illegalParameterValue() : message("Illegal parameter value") {} explicit illegalParameterValue(const char* theMessage) {mess...
consider the following code: try { // do something that might throw an exception } catch (const std::exception &ex) { // handle the exception } If you derive your illegalParameterValue class from std::exception, then the catch clause above will catch it (along with other kinds of exceptions derived from std::excep...
66,828,648
66,829,278
Mimic `super` keyword: Set `base` class and `derived` class field during instantiation
Consider the following code: #include <iostream> struct Parent { int baseA_ = 0; double baseB_ = 0.0; Parent() = default; virtual ~Parent() = default; Parent(int a) : baseA_{a} {} Parent(int a, double b) : baseA_{a}, baseB_{b} {} auto set(int a) -> void { baseA_ = a; } auto set(int a, double b) ->...
You could replace your super method with a template constructor that forwards to the base class. template <typename T> struct Child : public T { int derivedA_ = 0; Child() = default; ~Child() = default; Child(int a) : derivedA_{a} {} template <typename... Args> Child(int a, Args&&... args) : T{std::forwa...
66,828,892
66,828,984
C++: get error: std::bad_alloc when using vector and iterator
I am using mailio library and I get into trouble when I want to get all elements in a vector. string msg = "Subject: " + mail -> subject() + "\nFrom: "; for(auto address = ( mail -> from() ).addresses.begin(); address != ( mail -> from() ).addresses.end(); ++address ){ //address is not empty msg.append( address -> ...
If the from() doesn’t return a reference then it makes a copy of the struct, including copying the std::vector. This means in your loop you get two different vectors of which you take begin() and end() respectively. You’re not allowed to loop between these since the begin iterator will most likely never match the end, ...
66,828,930
66,829,951
I think this open gl code is causing a memory leak, What mistake am I making?
In this code I attempt to draw two lines, initially it's basically a short setup of a VBO and a VAO and then I draw the line, it seems to work, but when I copy and paste the code a few times to get more lines I seem to be creating a memory leak, and therefore must be doing it wrong. I have a feeling there's a better wa...
You are doing glGenBuffers and glBufferData inside a render function, which will allocate GPU memory and loads it every frame. Instead, use glGenBuffers in the setup part of your program. Most likely you are only changing the transformation which is supplied to the shader for most rendering (meshes, terrain, etc), so y...
66,829,019
66,829,494
String being empty still gives True value
The code is used to implement Max-Heaps using Binary Heaps, and the output is instead 1000 unwanted lines. auto input = ifstream(filename); string line; getline(input,line); while(!line.empty()) { int option; int in; stringstream l(line); l >> in; option = in; switch (option) { case ...
In response to "they do the same thing" comment. Not quite. If getline fails the string is left untouched (in this case). #include <string> #include <fstream> #include <iostream> int main(int, char**) { std::ifstream is("some invalid file name"); // nonsense std::string s = "Hello World"; // any ...
66,829,704
66,830,247
Traversing a binary tree to get from one number to another using only two operations
I'm doing a problem that says that we have to get from one number, n, to another, m, in as few steps as possible, where each "step" can be 1) doubling, or 2) subtracting one. The natural approach is two construct a binary tree and run BFS since we are given that n, m are bounded by 0 ≤ n, m ≤ 104 and so the tree doesn'...
You only have 2 available operations: double n subtract 1 from n That means the only way to go up is to double and the only way to go down is to subtract 1. If m is an even number, then you can land on it by doubling n when 2*n = m. Otherwise, you will have to subtract 1 as well (if 2*n = m + 1 then you will have to ...
66,830,406
66,830,611
(Linux, C/C++) Segmentation fault caused when manually assigning an address to a pointer
I would like to make a memory reader for my school project for Linux OS but I've encountered an error. I've made this simple test code just to find out what causes it. And it turns out, that when I cast user's input (which is a hex value) to the pointer and then try to access it, segmentation fault happens. It worked w...
int address = -1; An int may not be able to hold an entire address. In <stdint.h> there is a type called intptr_t that is guaranteed to be able to hold any pointer address. You should preferably use that. printf("Address of some value: %X\n",&value); The complete address of value isn't printed. printf has a specific ...
66,830,497
66,830,498
Why the generated assembler of certain boolean expressions contains a conditional jump?
Consider this code: bool res_true(); bool res_false(); bool test1(const bool cond) { return (cond && res_true()) || (!cond && res_false()); } bool test2(const bool cond) { return cond ? res_true() : res_false(); } Both test1() and test2() select a certain boolean result between res_true(),res_false() basing ...
That's because the default c++ boolean operators || and && are short-circuited (with guaranteed left-to-right evaluation), so a logical expression may or may not be fully evaluated depending on the results of his sub-expressions. for example in: f() || g() f() will be called first and g() won't be called if f() was tr...
66,830,971
66,833,273
Why is this combination of move and value constructor ambigous for MSVC but not for Clang and GCC in C++17 and above
I have the following code struct R { int i_ = 8; R() = default; R(R const& o) = default; R(R&& o) = default; R(int i) : i_(i) {} operator int() const { return i_; } }; struct S { R i_; operator R() const { return i_; } operator int() const { return static_cast<int>(i_); } }; int main...
This is CWG 2327, which doesn't currently have a resolution but gcc and clang seem to do "the right thing." The issue reads: Consider an example like: struct Cat {}; struct Dog { operator Cat(); }; Dog d; Cat c(d); This goes to 9.4 [dcl.init] bullet 17.6.2: Otherwise, if the initialization is direct-initializat...
66,830,976
66,831,922
pass a value of a derived type as template NTTP parameter
Should it be possible to pass a value of a derived type as NTTP? struct base { }; struct derived : base { }; template< base name > struct component { }; struct test1 : component< ( base() ) > { }; // OK struct test2 : component< ( derived() ) > { }; // error C++20 (GCC 10.2) complains error: conversion from 'derived...
The definition of "converted constant expression" (which NTTP arguments must be) specifically excludes the possibility of derived-to-base conversions in the set of allowed standard conversions. This appears to be an oversight, as there's a defect report on it. So the C++20 standard at present doesn't allow them, though...
66,831,932
66,833,080
I need a regular expression in order to tokenize multiple words inside quotes in c++
I have an input file that I want to tokenize. the text is like this: MATERIAL "A992Fy50" TYPE "Steel" GRADE "Grade 50" WEIGHTPERVOLUME 0.007849048 The tricky part is to get the "Grade 50" as a single word. could any one suggest a regular expression in c++. I know how to do it without the white space inside t...
Regex is also a text parser that is ready for use straight away, with an efficient expression that is as simple as "([^"]*)"|(\S+) See regex proof. EXPLANATION -------------------------------------------------------------------------------- " '"' -----------------------------------------------...
66,832,762
66,832,932
right-shifting unsigned char is filling with ones?
On my system, (unsigned char) -1 is (expectedly for chars of 8 bits) 1111 1111 in binary (255 decimal). Similarly, (unsigned char) -1 >> 1 is as expected 0111 1111. The left was filled with a zero. ~((unsigned char) -1 >> 1) is 1000 0000 as expected. Now I want to generate the unsigned char 0010 0000 for example. I tri...
Another way to set the nth bit (from the left): 1 << (CHAR_BIT - n - 1)
66,833,334
66,833,516
The validity of lambda expression with omitted parameter list in C++23
According to cppreference, both gcc and clang have completed the implementation of P1102R2 ("Down with ()!") recently, which means we can define lambda expressions more concisely in C++23. But I found that they are inconsistent with a certain form: auto l = []<auto> noexcept requires true {}; clang accepts this form, ...
Thanks for reminding me of how pointless this feature is. The correct answer is: no, that's not a well-formed lambda. The grammar is defined in [expr.prim.lambda.general]: In our case, to start with we have: []<auto> noexcept requires true {}; [] is the lambda-introducer <auto> matches <template-parameter-list> and ...
66,833,541
66,834,661
How to set format of std::scientific
I want to print 12345.0 as 0.1235e+05. But the below code gives 1.23450e+04. Is there a way to control the format of std::scientific? #include <iostream> #include <string> #include <sstream> int main() { double a = 12345.0; std::stringstream s; s.precision(3); s << std::scientific; s << a; ...
I corrected the error in the solution given in the link Print exponential notation with one leading zero with C++ by adding two lines of code. I also repeated the process for correct formatting: int p = stream.precision(); base = round(base * pow(10, p)) / pow(10, p); It now makes correct rounding and gives 0.1235E5....
66,833,617
66,833,692
Read len bytes of a file at offset and write it to FILETIME
Is there any possibility to read sth from a binary file when knowing only the size of the element that should be red and the offset (in hexa)? For example, if I want to read a FILETIME variable of 8 bytes, that has offset 0x001C, how do I approach this is C or C++? I tried fseek(pFile, 0x001C, SEEK_SET); FILETIME* temp...
You can set your offset with fseek, and then read len of bytes with fread: #include <stdio.h> #include <stdlib.h> int main(void) { FILE *file = fopen("read_bytes.c", "rb"); size_t offset = 0x001C; size_t len = 8; fseek(file, offset, SEEK_SET); FILETIME* temp = malloc(sizeof(FILETIME)); fread(t...
66,833,629
66,833,659
Do all functions in a c++ program's main function get called regardless of error?
Let's say i have a program that executes void foo() from main(). What happens if foo has lets say a vector out of range exception. Then after foo() inside the main() there is a function called bar() will bar be executed? void main() { foo() //exception in this function bar() //will bar be called? } Assuming that foo()...
An uncaught C++ exception will terminate the program. Often with a stack trace but that is up to the implementation. So no, in your example bar() will never be called. Update: In some situations the optimizer could inline both functions and move some code from bar to the top of main. You would only see this in a debugg...
66,833,773
66,833,900
Why converting constructor needs copy constructor to be declared when explicit cast performed?
From what I learned, I thought Foo a = 1 is equivalent to Foo a = (Foo)1. With copy constructor declared, yes, they both result in calling Converting constructor. class Foo { public: // Converting constructor Foo(int n) : value_(n) { std::cout << "Converting constructor." << std::endl; } // Copy constructo...
Foo a = 1; calls Foo(int n). (Foo)1 also calls Foo(int n). Foo b = (Foo)1; calls copy constructor Foo(const Foo&). Until C++17 the last call can be elided but the copy constructor must be available. Since C++17 copy elision is mandatory and the copy constructor isn't necessary: https://en.cppreference.com/w/cpp/languag...
66,834,322
66,834,691
C++ code runs sometimes but other times it either hangs or throws exceptions
I wrote a C++ program that merges sorted sub-arrays, but my issue is that when I run the code using Visual Studio it runs perfectly fine sometimes, but other times it doesn't (I'd say it runs without issues ~40% of the time), when it doesn't run as intended it either hangs at a certain point or it throws exceptions, so...
Often when it may run sometimes and not other can be attributed to a memory leak. Sometimes you may get lucky and the leak wont corrupt other data but often it does curropt other data. Try using a prebuilt list class from the std library with error catching and see what error it throughs and then fix it. One last thing...
66,834,335
66,837,137
Game does not launch from Menu
I am new to Game Development. I managed to create a simple game (like Space Invaders) as well as a simple start Menu using C++ and SFML. However, upon pressing "Enter" on the main menu, the game is not being launched. How do I link it properly? I appreciate your help. This is not homework. main.cpp codes #include <SFML...
"window redefinition" error occurs because both your RenderWindow objects have the same identifiers (i.e. window). You might want to change the name of the second window or better yet use the same window. The second error, sf::Text::setColor() is deprecated means that it is no longer "useable" or "is not suggested to b...
66,834,502
66,836,898
finding the maximum subsequence of string?
I am new to programming. I have been struggling with this programme for a long time. Question: what logic error am I having with my code? Problem: need to find the maximum subsequence of a string. The length of the required subsequence, and the content of the string are from input. for example, maximum subsequence with...
Your current code has a big problem since you erase characters from I and therefore can't calculate the pos in the original string properly. I suggest that you use std::max_element to get an iterator to the char with the largest value instead of doing the search manually. Here's how to fix it using AbCd687fs 4 as an ex...
66,835,050
66,835,242
Pass vector of memeber functions to Base class function
How can one do this? I need inheritance because there will be a lots of Child classes (and they will differ in "printers" function) but "creator_function" will be same for all of them and Child function inherit more features than this problematic one. I do not know parts in ?? Header of creator_function Calling passed...
It's going to get messy trying to do a method invocation of a child class from a base class. Remember, pointer to member functions can only be invoked with an instance ("this") of that class. The classic solution would be to have a separate printer base class with a virtual print method on it. Then have a printer1 an...
66,835,155
66,835,180
C++ : Program fails during vector filling and searching
I'm practicing C++ vector and as an exercise I want to fill a vector with 16 million random numbers and then find the position of the first occurrence of a number. The code which I implemented so far is this: int getIndexOf(std::vector<int>& v, int num) { for(std::size_t i=0; i < v.size(); i++) { if(v.at(i)...
int vectorSize = 16000000; std::vector<int> v(vectorSize); for(std::size_t i=0; i < v.size(); i++) { v.push_back(rand() % 10000000); } This part is bad. push_back() adds an element to the vector, so it increases size(). Therefore, this loop won't terminate until something bad happens. You shoul...
66,835,829
67,274,659
libbfd: Write COFF object with AMD64 machine type
Im using libbfd to write out the contents of a coff object file for windows that contains x86-64 code. Writing symbols, sections and relocations works, but the resulting file does not have the machine type set in the coff header. I manually write 0x8664 at the beginning of the file to fix this issue. Is there a way to ...
The answer is quite simple, but cannot be found that easily in the documentation... when opening the bfd object, bfd_set_arch_info must be used to set the architecture. bfd_init(); auto bfd = bfd_openw("test.obj", "pe-x86-64"); if (!bfd) { bfd_perror("bfd_openw failed"); return -1; } if (!bfd_set_format(bfd, bf...
66,835,850
66,835,930
C++: expected ';' at end of member declaration
sorry for the French-English mix... I'm getting [Error] expected ';' at end of member declaration for this line public: monthly(string n,string s,int t,int b,double sl,int nc,double tc)::employee(n,s,t,b) found in #include <iostream> #include <string> using namespace std; class employee {protected: string name; ...
Here is how your code should look. clang-format fixed it up. #include <iostream> #include <string> using namespace std; class employee { protected: string name; string surname; int tel; int nbureau; public: employee(string n, string s, int t, int b) { name = n; surname = s; tel = t; nbureau ...
66,835,866
66,836,002
C++ inheritance constructor problems
I have created 2 classes (Entity and Player). So basically the Player class inherits from the Entity class, so a Player instance is in itself an Entity object. Here is the first class: #include <iostream> #define print(obj) std::cout << obj << std::endl class Entity { public: int xPos, yPos; Entity(i...
Because you don't have a default constructor for Entity that takes no arguments, you have to initialize it too: Player(int _level, int _healt) : Entity(0 , 0) { level = _level; healt = _healt; } Or more idiomatically: Player(int _level, int _healt) : Entity(0 , 0), healt(_healt), level(_level) {} In the above...
66,835,988
66,836,341
Why doesn't switching on a char value reach case 0xC2?
Found a bug the code below, it parses C-string and is supposed to detect UTF8 characters: char* pTmp = ...; ... switch (*pTmp) { case 'o': { ... // works fine break; } case 0xC2: { ... // never gets triggered break; } } However case 0xC2: is never trig...
Is char signed? It is implementation specific if char has the same range as signed char or unsinged char. In OP's case, char has the range [-128 ... 127], thus case 0xC2: is never matched. But I would like to clarify what is really going on here and what rules are applied. The C standard library string functions ...
66,836,542
66,836,921
deleting values less than a given value in a doubly linked list
I'm writing a code that simulates a music playlist. One of my functions should delete all the songs that are before a given year. But I'm having some issues getting my code to work. The function wont delete the nodes, when I use a function to print the list after running this function, it's completely unchanged. Can an...
You are not traversing the list correctly when looking for nodes to remove. If the list is empty, the code will crash. If the loop encounters a node that is not older than the specified year, the loop ends prematurely. When removing a node, the code does not correctly account for the possibility of that node being at ...
66,836,993
66,837,270
Using std::cin in a while loop to read multiple numbers while they're being added (Loop won't terminate)
I'm doing exercise 1.16 (p. 17) in C++ primer. The exercise is to get a set of numbers from user input (std::cin) and add them and output (std::cout). My loop won't terminate with std::cin >> input as the condition. Once it runs out of numbers to add it reads from the keyboard again. I'm a little familiar with C and in...
I would like it to terminate on reading the newline from the input buffer In that case, I'd use std::getline to read the line as a std::string and then convert that string to an integer using one of the conversion functions, like std::stoi: #include <string> // ... // exit the for loop if an empty li...
66,837,232
66,837,424
translating a string of words to another string of words
I want a program that gets a char[] as input and outputs a char[] of the same length but that its first character is a w , the last one is a f and all the characters in between are os. If the input has size one, the output shoul be de 'w' and if it has 2 characters it should be wf. Example: "stackOverflow" => "wooooooo...
Maybe this: for (int i = 0; i < strlen(human); i++) { if(i == 0) { dog[i] = 'w'; } else if(i == (strlen(human)-1)) { dog[i] = 'f'; } else { dog[i] = 'o'; } }
66,837,376
66,837,387
Validating a number using c++
I am trying to validate an integer entered by the user (getUserInteger). When the value of the input is not an integer, the while loop is supposed to clear the buffer, reset the error status of the buffer, print "bad entry, try again: " and then ask for a new number. It looks like everything is working well up until a ...
cin.ignore should come after cin.clear. Wrong: cin.ignore(numeric_limits<streamsize>::max(), '\n'); //clear buffer through 'enter' cin.clear(); // reset error buffer Fixed: cin.clear(); // reset error buffer cin.ignore(numeric_limits<streamsize>::max(), '\n'); //clear buffer t...
66,838,104
66,838,114
Int* outputting incorrect length c++
I've been really troubled by this problem. It may sound ridiculous, but this is exactly what happened in my terminal. int* nums = new int[100]; cout << sizeof(nums); but the block above outputs 8 instead of 100; can anyone please help? Full program (readfile.cpp): // imports pair<int, int*> Readfile::readfile (strin...
The reason you are getting 8 is because that is the size of the pointer nums.
66,838,140
66,838,153
C++ Avoid typing out constructor
I have a struct with e.g. 16 fields and want to later initialize the struct with a initalizer list. Is there a way to avoid retyping all of them in the constructor (given I want to initialize all of them and in the exact order)? Even if they're all plain old data? Besides being tedious, it seems to me there is simply s...
Since your data members are public, you can in fact do this by reducing the amount of code you have. Simply don't provide a constructor: struct Foo { int A; int B; Bar* C; // ... }; and then you can construct a Foo like this: Foo foo{1, 2, new Bar{}, /* ... */ }; or Foo foo = {1, 2, new Bar{}, /* ... */ }; ...
66,838,529
66,838,594
Why #include<bits/stdc++.h> does not work by default on windows?
I have installed the mingw-w64 compiler on windows. But using #include<bits/stdc++.h> in the c++ program preprocessor directive always gives an error. How can this be fixed?
bits/stdc++.h is not a standard header file. Thus, it is not guaranteed to work except with certain specific compilers. Even different versions of the same compiler might or might not provide it. When it is available, bits/stdc++.h just #includes every standard C++ header file. This might make sense for someone just st...
66,839,468
66,839,687
Staircase Pattern Printing in c++
void staircase(int n) { for(int i = 1 ; i <= n ; i++) { string h(i,'#'); string s(n-i,' '); cout<<s<<h<<endl; }} Please explain the first two lines in the for loop. Can we declare like string h(i,'#'); in strings? Does it means filling the ith position in the string with "#"?
Can we declare like string h(i,'#'); in strings? Yes. Actually, that's defining the string, not declaring. Does it means filling the ith position in the string with "#"? No. Please use the reference pages. They are and will be your friend in the C++ journey. For your particular use case, refer to the constructor of...
66,840,161
66,842,761
output 10 with memory_order_seq_cst
When i run this program i get output as 10 which seems to be impossible for me. I'm running this on x86_64 core i3 ubuntu. If the output is 10, then 1 must have come from either c or d. Also in thread t[0], we assign c as 1. Now a is 1 since it occurs before c=1. c is equal to b which was set to 1 by thread 1. So when ...
10 (c=1, d=0) is easily explained: bar happened to run first, and finished before foo read b. Quirks of inter-core communication to get threads started on different cores means it's easily possible for this to happen even though thread(foo) ran first in the main thread. e.g. maybe an interrupt arrived at the core the ...
66,840,466
66,840,579
When is a child class too different to be inherited?
I have a set of closely linked data structures that feel like they ought to be inherited. However, they are different in that children have some extra variables. I can achieve this via: struct A { int a; int b; virtual int kind()=0; A(int a_, int b_) : a{a_}, b{b_} {}; } struct B: A { int c; int kind() {return 1;}; B(...
You've already done the work of creating the virtual base class. Instead of returning the kind as a value you can just overload the functions where you want to do separate things. struct A { virtual ~A() = default; int a; int b; virtual int get_value() const = 0; A(int a_, int b_) : a{a_}, b{b_} {}; } struct...
66,840,757
66,842,789
How to instantiate a list of types for compile-time/static polymorphism
I'm implementing a compile time dispatcher which makes use of static polymorphism and metaprogramming. I have a list of types which I would like to instantiate into a runtime std::array. struct Test { typedef std::integral_constant<int,0> nop; typedef std::integral_constant<int,1> A; typedef std::integra...
I would suggest changing the typedefs for A, B and C to struct so you can define the string inside them. struct A { static constexpr int value = 1; static constexpr char name[] = "A"; }; // Same for B and C using list = mp_list<A, B, C>; Then you can create a make_thing_list template <typename... T> static s...
66,841,735
66,841,818
std::this_thread::sleep_until timing is completely off by about a factor of 2, inexplicably
Ok, I really have no idea why this is happening. I'm currently implementing a thread container which runs an infinite loop in a detached manner, limited to a certain speed between each iteration. Header: class timeloop { public: std::thread thread = { }; bool state = true; void (*function_pointer)() = null...
There are no guarantees on resolution of sleep_until, you are only guaranteed the thread will not be woken before the timepoint. If you are implementing the main game loop, read Fix your timestep. Using sleep to guarantee timing is a terrible way to do it. You are at mercy of OS scheduler and e.g. Windows has a minimal...
66,841,870
66,841,907
Vector push back function in structure not working
I want to store a vector in a structure and then append to the vector from a function. Does this even make sense or can I only create elements in my vector when creating it? If no, where is the error in the code below, because if I execute it, it simply prints nothing. I want it to store the numbers 0-4 as components o...
You have to pass the layer parameter by reference, not by value. Instead of void range(layers layer), do void range(layers &layer). If you pass by value, you are making a copy of the vector and then modify this copy inside the function, so your original vector remains untouched. If you pass by reference, the original v...
66,841,930
66,842,362
Qt decided to ignore functions?
So i have this project with Frameless windows and in order to move them around the screen made such functions for every window: window.h private: Ui::MainWindow *ui; void main_mousePressEvent(QMouseEvent *event); void main_mouseMoveEvent(QMouseEvent *event); int m_nMouseClick_X_Coordinate; int m_nMo...
Maybe a stupid question, but have you enabled mouse tracking? eg. setMouseTracking(true); in the window constructor. Also, with your implementation, the window will move constantly even when you are not pressing the mouse. The way I would do it is to override two functions: onMousePressEvent() and onMouseReleaseEvent()...
66,842,001
66,842,050
What caused the following aggregate initialization problem?
I am trying to reproduce the code explained in a textbook about learning c++. The simplest one is given as follows. But it does not compile as expected. #include<vector> using namespace std; struct Storage { vector<int> data; }; Storage GetStorage(vector<int> params) { return Storage{ .data=params}; } Intellis...
You must set your language version to C++20 for designated initializers to work. On visual studio you must enable the flag /std:c++latest and -std=c++20 on other compilers
66,842,289
66,842,520
Unknown error in inserting values in multimap
I have the following code, where I try to insert values into a multimap of 2 strings, but I keep getting an error that I cannot understand. I've been trying to solve this for hours. The whole point of the program is to sort the lines of a dictionary based on the automatic sorting of the multimap insertion. // sort_entr...
as @Evg said, it accepts a std::pair dict.insert(std::make_pair(currentWord, value)); if I understand your intention correctly, you don't want to save the \t into your result, so add 1 after delimiterPos to get the correct value: auto value = currentDictEntry.substr(delimiterPos + 1, std::string::npos); test run. o...
66,843,045
66,843,179
how does the std::sort() function in C++ work?
I'm using Programming Principles and Practice Using C++ as my guide and reference to learn programming and c++. In chapter 4.6.4 the book showed this snippet of code. int main() { vector<string> words; for (string temp; cin >> temp; ) // read whitespace-separated words words.push_back(temp); // put into...
The first example is working in C++20, if sort is from the ranges namespace. Is it mentioned in the book/tutorial your are reading? sort(arr, arr[5]); in your terms, arr[5] is not "where", it's an array element, i.e. "what". "Where" is the address &arr[5] or &arr[n]. You could use std::begin(arr) and std::end(arr) inst...
66,843,240
66,845,297
Code gets stuck when not using cout and doesnt work with some numbers
What the code does: What this code does is given that number of primes that are wanted, startin from 2 ,it makes an array with those prime numbers. to find the prime numbers what it does is to divide a number that could be a prime by every number on that array, if the remainder in every division isn't 0, that means tha...
There is a problem in your code, which when fixed, makes your code run perfectly! An array MUST have a const value, which means it can't depend on input in any way. It must always be the same. Change: int primes[primesWanted]; To: int* primes = new int[primesWanted]; After all, an array is basically a pointer, so ...
66,843,886
66,857,075
How to create a generic function with write_json and read_josn using C++ boost library
I am using different functions and when executing each function, I would like to create Json message for communication like as shown below: TestFunction1(string id) { "message" : "MSG_TestFunction1", "id" : "1212" } TestFunction2(string id) { "message" : "MSG_TestFunction2", "id" : "1213" } In...
Please, do not use Property Tree as a JSON library. Boost 1.75.0 added a JSON library though! As the other commenter said, it's not very clear what exactly you require, so let me just sketch a few similar use-cases: #include <boost/json.hpp> #include <boost/json/src.hpp> // for compiler explorer #include <string> #incl...
66,843,924
66,844,387
What does the return code of the Wifi Libary in an ESP8266 mean?
#include <ESP8266WiFi.h> #include <WiFiClientSecure.h> #ifndef STASSID #define STASSID "wlanName" #define STAPSK "wlanPassword" #endif const char* ssid = STASSID; const char* password = STAPSK; const char* host = "api.github.com"; const int httpsPort = 443; const char fingerprint[] PROGMEM = "5F F1 60 31 09 04 3E ...
There is publicly available documentation https://www.arduino.cc/en/Reference/WiFiStatus Arduino sources are open source. You can browse the sources. Type in google "Arduino esp8266 source github" and you may find https://github.com/esp8266/Arduino . From there you can ex. type WL_CONNECTED in search bar above and find...
66,844,014
66,844,974
How can I speed up the program execution?
I have a program that reads data from a file (a matrix of 400,000 * 3 elements) and writes it to a two-dimensional array and write this array. However, there is a problem: it all takes a long time (6 seconds). According to the conditions of correct tests, this should take no more than 2 seconds. int main() { ifstr...
S.M.'s advice is promising - just short* matrix = new short [edge * 3]; then for (int i = 0; i < edge * 3; i++) file_for_reading >> matrix[i]; to read the file. Crucially, this puts all the file content into contiguous memory, which is more CPU cache friendly. Using the following code I generated test input and measur...
66,844,424
66,845,234
How to add newly created object into array
I want to add an object to an array. I'm trying to do it in the constructor within this. I'm starting to learn c++ and I'm not sure why it doesn't work in this way. Can someone explain why it won't work and how to do it properly? #include <iostream> using namespace std; const int CAPACITY = 50; class Photo { pri...
Your constructor is trying to store a Photo* pointer into an array of Photo objects. You would have to either dereference the this pointer to assign the Photo object being pointed at. collection[collection_size++] = *this; change the array to store Photo* pointers. static Photo* collection[CAPACITY];
66,844,724
66,844,776
Declaring and Initializing C++ Static variables
Note: This is coming from a beginner. Why does the first one outputs 333 and the second one 345 ? In the second code does it skips over the declaration? I mean it should initialise the "j" variable again like in the first one. int main() { static int j =12; for(int i=0; i<=2; i++) { j = 2; j += ...
static variables are only initialized once (when first used). After that, it behaves as if it is declared somewhere else (I mean, the initialization is ignored). In the second main, the initialization static int j = 2; is executed only the first time, after that, you are incrementing it sequentially (i.e. 2,3,4...) In ...
66,844,835
66,844,938
Reading a file stops at the first null character
my C++ knowledge is very limited so my apologies beforehand as it may be a very simple question but I haven't been able to find a solution. I have a binary file that I'm trying to read. The code attempting to read the binary file is shown below: string readFile2(const string &fileName) { cout << "B1 \n"; ifstre...
The problem is not with how you are reading the file, but with how you are outputting its data. You are treating the data as if it were a null-terminated char* string, which will break on the first nul character encountered. Non-textual binary files tend to have a lot of 0x00 bytes in them. Replace this: cout << bytes...
66,844,969
66,861,410
How to avoid cached data in multithread application C++
Can someone clarify the next moment. I saw some implementations of std::queue for multithreading purposes, where all operations of pushing/poping/erasing elements where protected with mutex, but when I see that I imagine next scenario: we have two threads (thread1 and thread2) and they are running on different cores of...
It's not your problem. You're writing C++ code. It's the compiler's job to ensure your code makes the CPU and its caches do the right thing, not yours. You just have to comply with the rules for whatever threading standard you are using. But if i lock some mutex, how can i be shure, that this memory isn't cached, or m...
66,845,099
66,846,227
cpp to delphi "byte [enum]"
I have a problem with struct translation from C++ to Delphi. In a C++ header, three fields of a struct have a byte array to a enum value. I'm supposing its the order value since the enum has no values. //Part of struct declaring a byte array of NET_COLOR_TYPE_MAX BYTE byColorSimilar[NET_COLOR_TYPE_M...
You can use the NET_COLOR_TYPE_MAX enum value to declare the arrays, just as the C++ code does. Remember that the upper bound of a 0-indexed array is -1 of the element count, eg: type EM_COLOR_TYPE = ( NET_COLOR_TYPE_RED, // red NET_COLOR_TYPE_YELLOW, ...
66,845,203
66,846,123
Is there a hidden rabbit hole in returning in try block?
So to be more specific, here is the example I got: Example 1. std::vector<std::string> f() { try { return someOtherFunction(); } catch (...) { std::vector<std::string> res; ///... return res; } } Example 2. std::vector<std::string> f() { try { ...
When you return expression and that expression is an rvalue, in c++17 the elision of that expression into the return value is required. When you return local_variable, the elision is not guaranteed, and the local variable and the return value can have separate identities, depending on optimization levels and compiler f...
66,845,340
66,845,530
How do save the entire content of a binary file into postgres database?
I'm trying to save binary data into postgres. Parts of the code is shown below: string readFile2(const string &fileName) { ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate); ifs.seekg(0, ios::end); ifstream::pos_type fileSize = ifs.tellg(); ifs.seekg(0, ios::beg); vector<char> bytes...
Use bytea instead of BLOB, and then escape the binary data when inserting it, eg: w.exec("CREATE TABLE IF NOT EXISTS binary (id INT PRIMARY KEY, meta bytea)"); w.exec("INSERT INTO binary (id,meta) VALUES (18, '"+w.esc_raw(content)+"')"); Alternatively, put the binary data into a pqxx::binarystring instead: pqxx::binar...
66,846,114
67,283,819
Is it possible to get cc1plus.exe compiliing details on windows?
My app is tracing compiling process on windows via g++ or clang++. To compile a make project which trigger g++. myapp make then the process tree looks: ├── make.exe ├── g++.exe └── cc1plus.exe Currently, I can get pid, parentid and sort of information about make unfortunately not make c...
I find the solution via windows debug api. WinBase.h and if you change DEBUG_PROCESS to following options #define DEBUG_PROCESS 0x00000001 #define DEBUG_ONLY_THIS_PROCESS 0x00000002 #define CREATE_SUSPENDED 0x00000004 #define DETACHED_PROCESS 0x00000008 u...
66,846,253
66,846,515
stopping a while / for loop when an user says so
i'm new to c++ so I only kind of know iostream and the syntax of the language. I am writing a program that creates an infinite amount of .txt files using fstream but i'm kind of stuck, I want it to have a menu in the program so the user could interfere with the process with the help of commands I will code in void func...
My advise, Adam, is to change your problem description so you ask user how many files they want to create, and then run the loop that many times: for(;;) { unsigned n; cout << "How many files do you want to create (0 to stop)? "; cin >> n; if(!n) break; for(unsigned i = 0; i < n; i++) { CreateNewFile(); ...