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
73,635,160
73,635,667
How to solve Boost Error: terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'
I am trying to use Boost for creating a shared memory. This is my code: #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <iostream> #define BUF_SIZE 1*1024*1024 int main() { shared_memory_object tx_data_buffer(create_only ,"tx_data_memory",...
You're specifically asking the shared_memory_object to open in create_only mode. Of course, when it exists, it cannot be created, so it fails. The error message is very clear: "File exists". One way to resolve your problem is to use open_or_create instead: namespace bip = boost::interprocess; bip::shared_memory_object...
73,635,173
73,635,476
C++ template runtime choices
I would like to improve the following runtime template selection code: We have 4 functors for p-norm calculation (1 general case, 3 specialized cases). During runtime, we can select the best one. template <typename T> struct p_norm { // contains functors to calculate p-norm struct general { ... }; // general case ...
std::variant with tag (std::type_identity here) might help: template <typename T> std::variant<std::type_identity<p_norm <T>::general>, std::type_identity<p_norm <T>::one>, std::type_identity<p_norm <T>::two>, std::type_identity<p_norm <T>::inf>> get_method_var(double d) { if ...
73,635,636
73,644,207
No .lib file generated after building tiny C++ static library project
I decided on adding a tiny extra project to my visual studio solution which includes only a single header file(for now) with a mutex which allows only 1 thread to output to the console at a time. Since this is a functionality which all of my projects in my solution will need so I thought it will be best to add a separa...
Add one empty .cpp file in your lib project and a lib will be generated. But as far as I am concerned, it will be better to #include the logger_mutex.h to other project's pch.h instead of as a library.
73,638,117
73,638,246
What precision is used by std::chrono::system_clock?
Here's some code that I found: std::cout << std::chrono::system_clock::now().time_since_epoch().count() << std::endl; This prints 1662563612364838407 for me; so it looks like this prints the number of nanoseconds since the UNIX epoch (1970-01-01). But is this precision guaranteed? I didn't find any indication at https...
No it is not guaranteed. You can use the clocks period member alias to get tick period in seconds: #include <chrono> #include <iostream> int main() { std::cout << std::chrono::system_clock::period::num << " / " << std::chrono::system_clock::period::den; } Possible output: 1 / 1000000000
73,638,202
73,639,359
How to implement copyable and movable wrapper around reference counted type?
Suppose a C API provides an opaque struct with internal reference counting: struct Opaque { int data; int refcount; }; struct Opaque* opaque_new(int data) { return new Opaque { .data = data, .refcount = 1 }; } int opaque_data(struct Opaque* opaque) { return opaque->data; } struct ...
Boost's intrusive_ptr was made for "internal reference counts": #include <boost/intrusive_ptr.hpp> // intrusive_ptr API functions inline void intrusive_ptr_add_ref(Opaque* opaque) noexcept { ::opaque_ref(opaque); } inline void intrusive_ptr_release(Opaque* opaque) noexcept { ::opaque_unref(opaque); } struct W...
73,638,331
73,640,445
boost::asio SerialPort unable to receive data
I am unable to receive data over serial port in boost::asio while using asynchronous. When I use synchronous routines I am able to receive data. Code : SerialPort.cpp bool SerialPort::read_async(std::uint32_t read_timeout) { try { if (read_timeout not_eq SerialPort::ignore_timeout) this->rea...
You're supposedly trying to do some operations asynchronously. Firstly, mixing synchronous and asynchronous operations is not always advisable. Some services/IO objects might hold inner state that assumes one or the other. Secondly, the asynchronous operation requires the io_service to be run. That doesn't happen. You ...
73,639,728
73,641,444
How to use `--start-group` and `--end-group` in CMake
Is it possible to use CMake to enclose a target's libraries in --start-group/--end-group without manually writing the argument string into target_link_options? Background: I'm having library ordering issues when linking a C++ executable to a list of libraries (using g++ 7.5.0). I recently learned about the --start-grou...
CMake 3.24 introduces LINK_GROUP generator expression, which allows to group libraries in target_link_libraries command for adding some feature on that group. One of the group features is RESCAN, which effectively adds --start-group/--end-group for a GNU compiler: target_link_libraries(myTarget PRIVATE # or any other...
73,640,094
73,640,733
Why are two destructors created for googletest test fixture when not placed in unnamed namespace?
When I analyze gcov results for the following code (after using c++filt to demangle), I see two FooTest::~FooTest() in the coverage information file, both mapped to the same line number. One is marked as called and the other is not. Note: No compiler optimizations are used (i.e. -O0). #include "gtest/gtest.h" struct ...
The link posted by Eljay, https://stackoverflow.com/a/6614369/4641116, contains an explanation as to why multiple dtors are created. In the code snippit above, the base object destructor (D2) is called by the derived test class defined via the TEST_F macro. The deleting destructor (D0) is not called by the program and...
73,640,182
73,640,837
Return an array from a function in c++
I'm trying to implement a function that returns an array, I came to this solution, but I don't know if it is a good practice, that's how I did it: #include <iostream> using namespace std; int* returnNewArray(int n) { int* arr = new int[n]; for (int i=0;i<n;i++) arr[i] = i; return arr; } int ...
I don't know if it is a good practice It's not. Nowadays, cases where using new/new[] and delete/delete[] are necessary are very few. I wonder if it is necessary to deallocate the memory that I allocated in the function It is necessary if you want to avoid memory leaks and since you used a raw owning pointer, you n...
73,640,419
73,640,576
Template argument deduction, Qualified-Id and performance
Suppose I have a lambda function: std::function<void (int&& y)> lambda = [](int&& y) { std::cout << std::forward<int>(y) << std::endl; }; Having another function named gate which takes the lambda function as arg: template<typename T> void gate(T&& x, std::function<void (T&&)> f) { f(std::move(x)); }; as the template ...
What I am wondering is, are there some lost in performance given the usage of the 'identity' struct? Certainly no runtime performance because the structure is never instantiated or used. Compilation speed could be affected since the compiler has to instantiate that type but it "amortizes" together with the instantiat...
73,640,973
73,641,200
Question about Nt and Zw functions API from User Mode
Im not working for any specific project, i just would like to know more about Nt and Zw functions, so here are my questions: NOTE: Im always referring to User-Mode space, and not Kernel-Mode. Whats the difference between Nt and Zw functions ? (so like, for example NtTerminateProcess and ZwTerminateProcess) Is the same...
Whats the difference between Nt and Zw functions ? in user mode both 2 names point to the same address (function). so no difference which name use. and in user mode this functions is stub, which call to kernel. the ntdll.dll export all names - all Nt and all Zw. however if use definitions from ntifs/ntddk/wdm - not a...
73,640,974
73,640,984
What is the difference between "using std::string" and "#include <string>"
I am newly learning C++, I do not really understand the difference between putting using std::string vs #include <string> at the top of my main file. I seem to be able to define strings without having #include <string> here: #include <iostream> using std::cout; using std::cin; using std::endl; using std::string; int m...
You need to include the <string> header to use std::string. Adding using std::string; allows you to use it without the std:: namespace qualifier. If you include a header that includes <string> you may not have to do so explicitly. However, it is bad practice to count on this, and well-written headers include guards aga...
73,641,004
73,641,435
Defining declared member function inside struct
struct a_t { struct not_yet_known_t; struct b_t { void f(not_yet_known_t* m); }; struct c_t { b_t b; //... }; struct not_yet_known_t { c_t c; //... }; // ERROR HERE void b_t::f(not_yet_known_t* m) { // code comes here } }; int main() { a_t::not_yet_known_t m; a_t::b_t b...
struct a_t { struct not_yet_known_t; struct b_t { void f(not_yet_known_t* m){ _b_t_f(this, m); } }; struct c_t { b_t b; //... }; struct not_yet_known_t { c_t c; //... }; static void _b_t_f(b_t* b, not_yet_known_t* m) { // code comes here } }; Instead of declaring a_t::b_t::f ...
73,641,174
73,666,658
using std::filesystem::recursive_directory_iterator; (Console App works, VCL App Doesn't)
I'm wanting to use std::filesystem::recursive_directory_iterator to list files in a folder and subfolder. This code works fine in a Console Application: #include <iostream> #include <vector> #include <string> #include <filesystem> using std::cout; using std::cin; using std::endl; using std::string; using std::filesyst...
Your Console project is configured to use a Clang-based C++ compiler, but your GUI project is configured to use the "classic" Borland C++ compiler instead. The classic compiler does not support C++11, and thus cannot use the <filesystem> library. You will have to go into your Project Options and disable the "Use 'cla...
73,641,731
73,641,802
Unique pointer to a pointer memory management
Function f allocates a few bytes that are returned in the form of a unique_ptr<char*>. How "smart" is this smart pointer ? When the returned unique_ptr goes out of scope, are those allocated bytes returned to the system ? The managed object here is a pointer (char*), not the bytes it points to ! (hence the specializati...
std::unique_ptr is a very simple class template. All it does is store a pointer and delete (or delete[], in the case of an array) the object pointed to by that pointer in its destructor. That is, it looks something like this (slightly simplified): template <typename T> class unique_ptr { private: T* ptr_; public:...
73,641,893
73,642,837
Operator overload taking void
I have a case in my code where I want to call a class-defined binary operator overload through a template, but the second argument might be type void. Is it possible to write that specialisation? The why: So I have a piece of existing macroisation/template wrapping which helps me log return values from functions. It go...
I have a case in my code where I want to call a class-defined binary operator overload through a template, but the second argument might be type void. Is it possible to write that specialisation? You can handle void return type using built-in binary comma operator: In a comma expression E1, E2, the expression E1 is ...
73,642,159
73,642,429
How to find the smiley symbols( :) and :-] ) starting positions in a text using c++
Trying to find the starting positions of the smiley in c++. But once it found the first smiley, it stops finding the next smiley. Code I was trying with regex (":\)|:\-\]") #include <iostream> #include <string> #include <regex> int main () { std::string s ("Best :) bookseller :) today. :-]"); std::smatch m; std:...
A regex_search only returns a single match. As the documentation notes: In order to examine all matches within the target sequence, std::regex_search may be called in a loop, restarting each time from m[0].second of the previous call. std::regex_iterator offers an easy interface to this iteration. Simple loop constru...
73,642,889
73,642,919
C++ union of derived classes with pure virtual base - what happens?
I stumbled across this pattern today. It compiles fine but does not work correctly at runtime. ("Der1" is printed twice) I can sort of see why, given that the address dereferenced is always the same, but I don't fully understand. I am not looking for a solution or workaround, I have already restructured this code. J...
What's happening is undefined behavior. What happens "under the hood" is immaterial. A different C++ compiler might produce completely different results (called a "crash"). You can observe undefined behavior in action by adding a constructor to both classes: struct Der1 : public Base { Der1() { std::cou...
73,642,903
73,647,684
Sending an array of ints with boost::asio
I want to send raw ints with boost.asio compatibly with any CPU architecture. Usually, I would convert ints to strings, but I may be able to get better performance by skipping the int/ascii conversion. I don't know what boost.asio already does under the hood such as using htonl. The documentation doesn't say and there ...
The other answer by @bazza has good professional advice. I won't repeat that. I get the impression you're more focusing on understanding the implementation specifics here, so I'll dive into the details of that for you here: Yeah, option 1 seems okay for the simple use case you describe. I don't know what boost.asio a...
73,643,874
73,675,695
C++ Simple Window Creation is executing java code for some reason?
I'm following the walkthrough of how to create a simple c++ application window here, and as far as I can tell my code is exactly the same as on the website. However whenever I try to execute the code it throws up this console where it seems to execute some java code and infinitely try to connect to a server. The proble...
The cause of this was from a library by the name of Tesseract, I'm unsure why it was compiling with the code at all, but I can be sure that it was causing this, and a quick uninstall of the library fixed everything.
73,644,157
73,724,541
Get raw buffer for in-memory dataset in GDAL C++ API
I have generated a GeoTiff dataset in-memory using GDALTranslate() with a /vsimem/ filepath. I need access to the buffer for the actual GeoTiff file to put it in a stream for an external API. My understanding is that this should be possible with VSIGetMemFileBuffer(), however I can't seem to get this to return anything...
I came back to this after putting in a workaround, and upon swapping things back over it seems to work fine. @mmomtchev suggested looking at the CPL_DEBUG output, which showed nothing unusual (and was silent during the actual VSIGetMemFileBuffer call). In particular, for other reasons I had to put a GDALWarp call in be...
73,644,823
73,644,993
What does `template<>` mean in front of a variable definition in C++98
I'm recently working on some legacy codes written in C++98. I am trying to get them compiled by C++17 compiler. A whole lot of warnings popped out as I was doing that. However, almost all the warnings were easily resolved. Except for this one: struct Counter { Counter(int v) : m_val(v) {} int m_val; }; struct ...
It seems like gcc 4.7.4 is unable to give a diagnostic. Note that from gcc 5.1 onwards, we get a diagnostic from gcc. Demo. The given program is ill-formed in both C++17 as well as C++98 as you're trying to provide an explicit specialization when there is nothing to specialize(as there is no templated entity anywhere ...
73,645,060
73,645,467
Created a program for binary tree traversal, inorder and postorder print wrong sequences
I made a program that takes user input to create a binary tree, with options to traverse said tree based on user input. Inserting and Preorder traversal work fine, but for some reason Inorder traversal prints the same output as Preorder, and Postorder traversal prints the input backwards. I've checked my insert and tra...
You did not make a mistake at all. But you have now first-hand encountered the raison d'être for tree balancing. (eg red-black trees or AVL trees) Inserting "1 2 3 4 5" in that order, with your code, gives the following tree (also known as a linked list): 1 2 3 4 5 If you change your input to "3 1 ...
73,645,987
73,646,492
Execute lambda with CreateThread
Is there a better way to use CreateThread than creating a free function each time for the sole purpose of casting lpParameter? Are there any modern alternatives to CreateThread for creating persistent threads? Edit: Perhaps you should just use std::async(lambda). I imagine that it's just implemented with CreateThread....
There are several mechanisms for achieving parallelism (std::async etc. as mentioned above). But the modern one which is most similar to your original code with CreateThread is std::thread. It can be constructed with a global function, a lambda, or a class method (which seems the best fit for you): m_thread = std::thre...
73,646,519
73,646,587
while(decision1 != 1 || decision1 != 2) why does this keep repeating even though decision is already 1 or 2
This is the code. Why does it keep repeating even though decision is already 1 or 2? std::cout << "How many toppings do you want? (1/2): "; std::cin >> decision1; while(decision1 != 1 || decision1 != 2) { std::cout << "Please enter either 1 or 2\n"; std::cout << "How many toppin...
When decision1 == 1, the condition decision1 != 2 is true, and vice-versa. Since decision1 cannot be both 1 and 2, decision1 != 1 || decision1 != 2 is always true.
73,646,581
73,647,040
How to get a user's input into a class's member variable and dereference it
class cookie{ public: cookie() = default; int*p_member{}; int case{}; private: }; #include <iostream> using namespace std; int main(){ cookie cold; cout << "Type what you want into the cookie p_member variable " << endl; std::cin >> cold.*p_member; // this doesn't work } I wanna know how to g...
First things first, make sure that you're not dereferencing a null or uninitialized pointer. Otherwise you'll have undefined behavior. it's about a member that is a pointer.I would like to assign a value to the member, and then dereference the member so i could print it out. You can use a pointer to member syntax fo...
73,646,712
73,647,244
I am trying to solve this question. But condition is dont touch listPrime function. Is it possible
**Dont touch listPrime function just modify the main function.Also Must use listPrime to get return value ; Question from one of my senior classmate ** #include <iostream> const int nmax = 100001; bool isPrime[nmax]; int listPrime(int num){ for(int i = 2; i<=num;i++){ isPrime[i] = true; } for(int i = 2; i<=num/2;i...
You don't need to use the function's return value at all. I'm sure that final loop and return in the function is there to throw you off. It's completely pointless. The function computes a prime sieve. If you just call it once, it'll generate the entire table for values up to whatever value you passed. So you may as wel...
73,647,216
73,648,873
Compiling opencv on ubuntu with C++ version 17
I'm trying to add a pnp solver to opencv I'm working on ubuntu OS. first I followed a tutorial on how to install opencv from source by cloning the repositories, then I tested the example and it worked so it compiled and installed succesfully. I began adding my files and I made sure that no names are duplicated and all ...
You can install OpenCV from ubuntu's opencv package via the following: for python: sudo apt-get install python3-opencv for libopencv-dev: sudo apt-get install libopencv-dev If you want to compile it and not use ubuntu's OpenCV package, do the following: # dependencies sudo apt-get install cmake sudo apt-get install g...
73,647,249
73,647,425
class initalizer list using a templated constructor of baseclass
I like to create a registry of templated classes adressed through their polymorphic anonymous base-class. In order to construct these classes I need to store the type of the used template class in the base-class. I woulod like to make the design slim and pass the template class in the constructor of the baseclass throu...
This Store(const Tstored stored) : Store_Base<Tstored>() is wrong, because it attempts to initialize the base class Store_Base<Tstored>, but Store_Base is not a template. The base class to be initialized is Store_Base not Store_Base<Tstored>. The way to call a templated constructor is to have the template argu...
73,648,806
73,648,843
How to read data from a binary file and write to a shared memory region?
I have created a shared memory region using boost. My next step is to read data from a binary file and write it to the shared memory region. I am using the following code to do this: #include <fstream> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> using namespac...
This can be solved by casting the pointer from unsigned char* to char*; this is one of the rare cases where just changing the type of a pointer is OK. So, use file.read(reinterpret_cast<char*>(mem), region.get_size());
73,649,066
73,650,407
Adjacency List in graph
Hi I am try to implement a graph using adjacency list using following code. #include<iostream> #include<list> #include<vector> #include<unordered_map> using namespace std; class graph{ public: vector<int> adj[10000]; void insert(int u,int v, bool direction) { adj[u].push_back(v); if(direction==1) { ...
The edges you are adding aren't the same as the graph i picture, you are inputting edge 1, 3 instead of edge 1, 5.
73,649,475
73,681,699
Serving static files in uWebSockets HTTP server (C++)
I am setting up an HTTP server in C++ using the uWebSockets library and I would like to add a middleware to serve static files, similar to what app.use(express.static(path.join(__dirname, 'public'))); does in Express.js. The static files reside in the public folder. The middleware should make the server load files unde...
There is an example with this exactly I eventually ended up adding a directory watch and updating the html files if saved (a few changes in codebase) but i guess thats a different thing #include "helpers/AsyncFileReader.h" #include "helpers/AsyncFileStreamer.h" #include "helpers/Middleware.h" AsyncFileStreamer asyncFi...
73,649,751
73,662,809
Nested lambda capture of variable gives incorrect warning
I'm using a nested lambda to walk through some data. The outer lambda does some processing and then calls the inner lambda. I get the following warning: x86-64 clang 13.0.1 - 2629ms (104630B) ~1800 lines filtered Output of x86-64 clang 13.0.1 (Compiler #1) <source>:9:34: warning: class '' does not declare any con...
It's a compiler bug that was fixed in this commit: https://github.com/llvm/llvm-project/commit/f7007c570a216c0fa87b863733a1011bdb2ff9ca. As you can see, the commit is in clang 14, specifically between the tags llvmorg-14.0.0-rc2 and llvmorg-14.0.0-rc3. So it makes sense that the warning does not appear on godbolt with ...
73,649,793
73,649,903
How make a vector2 relative to other vector2 properly?
Im making a 2D game with box2D physics, and i want to implement a parent-child system between the objects. The child's position will be relative to it parent. For example, father object position is (10, 0), the relative child's position is (0, 1) and the result child's position is (10, 1). I was thinking about how to i...
What you're describing is known in the physics simulation world as a constraint. It simply means that the constrained object isn't free to move like it wants to, but instead there are some restrictions. A special case of a constraint is a joint that links two bodies together - and Box2D supports them. In your specific ...
73,649,917
73,650,474
construction with an allocator must be possible if uses_allocator is true
I'm trying to create a pmr-allocated datastructure (compare code below). This however fails with an awful long error message and I can't quite track the root of it. At the end is a static_assert which says construction with an allocator must be possible if uses_allocator is true. As far as I can tell, std::pmr::vector ...
update(allocator_type allocator = {}) : profiles_{ allocator } Converts allocator to profile and initializes profiles_ with an initializer_list containing single element, which is getting copied. Either change {} to () or make profile constructor explicit (you might want to provide separate non-explicit default ...
73,650,604
73,650,875
Is there a way to create a new tuple from an already exisiting tuple?
I need a way to generate a new tuple from another tuple. std::string f1(int a) { std::string b = "hello"; return b; } float f2(std::string a) { float b = 2.5f; return b; } int f3(float a) { int b = 4; return b; } int main() { auto t1 = std::make_tuple(1, "a", 1.5f); //New tuple ---> s...
You can use std::apply to do this: template<class Tuple, class... Fns> auto tuple_transform(const Tuple& t, Fns... fns) { return std::apply([&](const auto&... args) { return std::tuple(fns(args)...); }, t); } auto t1 = std::make_tuple(1, "a", 1.5f); auto t2 = tuple_transform(t1, f1, f2, f3); Demo
73,650,921
73,651,642
Why do 'for' and 'for_each' result in different functions being generated by iterating through array elements using lambdas?
I'm trying to better understand the interactions of lambda expressions and iterators. What is the difference between these three snippets of code? onSelect is an std::function that is called when a component is selected. Example 1 and 3 seem to work quite nicely. Example 2 returns the same index value, regardless of th...
What is the difference between these three snippets of code? Well, only the first one is legal. My intuition is that Example 2 only results in one symbol being generated Each lambda expression generates a unique unnamed class type in the smallest enclosing scope. You have one block scope (inside the for loop) and o...
73,651,580
73,651,858
c++ vector with two parameters
I don't quite understand what the following does: std::vector<const char*> getRequiredExtensions() { uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); std::vector<const char*> extensions(glfwExtensions, glfwExtensions...
Let's concentrate on the following line of code: std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); This declares extensions as a variable of the templated std::vector<typename T> type, where the T type resolves to const char* (that is, it declares a vector whose elements are eac...
73,651,991
73,652,598
Is there anything from the standard library or boost that facilitates conditionally executing a function?
I am refactoring a function with too many if-else's, something like the following but more complicated. Some major characteristics of this function are: It bails out early for many pre-conditions (e.g., condition1() and condition2()). It only does some meaningful stuff on very specific scenarios (e.g., doA() and doB()...
Edit: conclusion at the top, frame challenge below. Back to the original question, is there anything existing in std or boost to do what ConditionalCommand does? OK, if you're really not worried about the fact that this design violates your own stated requirements, the answer is: NO. Nothing does exactly this. Howeve...
73,652,195
73,652,327
in C++, is std::move still preferred when calling a function that takes in a const reference?
Of the two versions of function calls below, is the one with std::move still preferred? void myFunc(const std::string& myStr){ // } std::string MyStr = "my string"; //For these 2 versions, should I still prefer std::move here to save a value copy, even when the function itself takes in a reference? myFunc(std::move(...
When passing a value by reference std::move doesn't make any sense, because no instantiation is happening here, and there would be no side effects (provided you don't want to alter overload function candidate) Thus for this particular case there is no any difference and you don't need std::move
73,652,567
73,652,755
How to match callable objects out of parameter pack to corresponding element in an array as argument?
For example, say I have the following: template<typename ...FunctionTypes> static void MainFunction(FunctionTypes... functions) { constexpr Uint32_t NumFunctions= sizeof...(FunctionTypes); std::array<double, NumFunctions> myArray; double arg1 = 4.2; int arg2= 9; for_each_tuple(myArray, FigureOutTh...
I think something like this could work: #include <array> #include <functional> template<typename ...FunctionTypes> constexpr void MainFunction(FunctionTypes... functions) { constexpr auto NumFunctions= sizeof...(FunctionTypes); std::array<double, NumFunctions> myArray{};//Zero-init for now. double arg1 =...
73,653,604
73,653,802
How to use unique_ptr fo automatic memory management?
I want a memory block that I can resize, so using the C library functions: { char *buf = reinterpret_cast<char*>(std::malloc(n)); ⋮ std::realloc(buf,N); ⋮ std::free(buf); } How can I go about using smart pointer protection (against leaking buf) in the above snippet? If I replace the first instruction with th...
would "free" me from worrying about the final free() ? Yes, it will correctly call delete[] for you. Would the unique_ptr tolerate resizing its *raw protégé (no longer n bytes) and do the delete[] expected from it when leaving the scope ? Calling realloc on the raw pointer causes undefined behavior, because it was ...
73,653,615
73,653,857
Reference to child class lost after assigning to a base instance
I'm trying to implement a Runner class that handles different types of objects dynamically, this Runner should be agnostic of what type of object is handling and use abstract class methods to execute functions which the child classes will be in charge of executing their own implementation. All properties in the Runner ...
The problem comes from the generic list. Here you declare a vector of generic items: // Inside GenericList std::vector<GenericItem*> list; But then, you also declare another vector in its child class: // inside AppleList std::vector<Apple*> list; This will shadow the parent's list. You can't override members like fun...
73,653,939
73,653,960
sizeof instance of std::vector returns wrong number of elements in the vector
I have a cycle, that defines a vector of GLfloat vertices coordinates. (three 1.0f floats describe the color, it doesn't matter) std::vector<GLfloat> verticesUnitPoints; float xCurrent = -1.0f; for (int i = 0; i <= 8; i++) { float yOffset = 0.01f; //first vertex verticesUnitPoints.push_back(xCurr...
sizeof(verticesUnitPoints) returns size of std::vector class (not instance), which is fixed for any number of elements. In order to obtain this number use member function std::vector::size (verticesUnitPoints.size())
73,654,812
73,655,310
How to represent a floating point number in binary from 32-bit hex value in C++ without using bitset or float variable?
Given a 32-bit hex like 0x7f000002, how do I get the full value of this number printed in binary without using bitset or defining any float variables to use union? I know that it is supposed to display +100000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000...
You can appeal directly to what the bits in a floating point number mean: https://en.wikipedia.org/wiki/Single-precision_floating-point_format The last 23 bits store the mantissa, and the eight bits before store the biased exponent (with the one bit before that being the signbit). The number is essentially "1.<mantissa...
73,654,820
73,655,088
Convert int to an int array C++
Given an input from the user (ex. 123456) you must convert the input int to an int array (ex. {1, 2, 3, 4, 5, 6}. I was wondering, how can this be done? I have started out with a function that counts the digits the were inputted, and initializes an array with the amount of digits. Is there another way to go about doi...
Let me solve this in what is a bit overkill for the problem, but will actually teach you various C++ constructs instead of the "C plus a bit syntactic sugar" you are doing right now. #include <iostream> #include <vector> #include <string> #include <algorithm> int main( int argc, char * argv[] ) { if ( argc != 2 ) ...
73,655,413
73,657,241
How to get Linux based system in QT5?
I am developing an application on qt5 using C++ which will support all popular distros, for this currently I am using QSysInfo qDebug() << "currentCpuArchitecture():" << QSysInfo::currentCpuArchitecture(); qDebug() << "productType():" << QSysInfo::productType(); qDebug() << "productVersion():" << QSysInfo::pro...
All Linux distros are just Linux so you need to read distro-specific values: $ cat /etc/*-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=22.04 DISTRIB_CODENAME=jammy DISTRIB_DESCRIPTION="Ubuntu 22.04.1 LTS" PRETTY_NAME="Ubuntu 22.04.1 LTS" NAME="Ubuntu" VERSION_ID="22.04" VERSION="22.04.1 LTS (Jammy Jellyfish)" VERSION_CODE...
73,656,117
73,656,566
Is equivalent destruction undefined behavior?
Will running a 'equivalent' procedure to an objects destructor result in undefined behavior under the standard? Example: Assume we wish to represent a directed acyclic tree, with homogeneous nodes, with root ownership. A problem with deep-structures is recursive operations. Almost all operations can be implemented, of ...
However, can the nodes remain homogeneous, and automatically destroyed, without undefined behavior? Sure. First of all let's use proper data type for pointers, as you assume unique ownership we should use std::unique_ptr: class Node { using NodePtr = std::unique_ptr<Node>; // ... // Assuming unique ownership ...
73,656,671
73,656,986
std::filesystem::path obtain relative path given a base path without temporary std::string conversion?
I am trying to find the relative path of something not from root but from a given path instead, like find the difference of 2 paths using std::filesystem::path objects, for example: std::filesystem::path path = "/var/log", file = "/var/log/folder1/folder2/log.log"; I was expecting that operator- was implemented for th...
std::filesystem::relative has an overload that accepts a base path and returns the first argument relative to the second, so all you need is: auto relative_path = std::filesystem::relative(file, path); Demo
73,657,141
73,657,175
Incompatible pointer types assigning to 'int (*)(int, int, int, int, int)' from 'int *'
I have this pointer to an orgFunction takes 5 int as input and returns int, and orgfunctionhook takes the same args and return: int (*orgFunction)(int a1, int a2 , int a3 , int a4, int a5); int orgFunctionHook(int a1, int a2 , int a3 , int a4, int a5) { // do something.. return orgFunction(a1,a2,a3,a4,a5); } void...
You're casting to the wrong type. As mentioned in the error message, the function pointer has type int (*)(int,int,int,int,int) but you're attempting to assign an expression of type int * to it. These types are incompatible. The proper way to do this would be to create a typedef for the function pointer type: typedef...
73,657,183
73,657,527
Passing the template variable to the Observers from the Subject - Observe design pattern
I am utilizing an observer design pattern for this simple use case whereupon a change in a Subject concrete class, the template value _x is passed to the observers via notify() however that will require Subject to be a template class which I don't want. Instead of making Subject a template class, I made notify a templa...
If you really promise that for notify<T>, there are only Observer<T>, then you could use a dynamic_cast safely: class Subject; class ObsBase{ virtual ~ObsBase()=default; }; template<typename T> class Observer:public ObsBase { public: virtual void update(T value, Subject *) = 0; }; class Subject { //If ...
73,658,473
73,665,788
How to customize a QScopedPointerDeleter to avoid calling destructor of parent class
I have 2 classes A and B, which looks like this class A{ public: ~A(){/* do something */}; }; class B : public A{ public: ~B(){/* do something */}; }; I want to avoid calling ~A() when ~B() is called. I found this post said that std::shared_ptr can customize deleter to control destructor. But I'm working ...
The good guy Don't do it. Solve the actual problem in a clean way. The bad guy - I really want to do it WARNING Keep in mind that you may get in trouble using this approach, f.ex. by creating memory leaks or undefined behavior. Note that calling the child destructor ~B, without executing the parent/base destructor ~A i...
73,659,169
73,659,233
Why is this C++ program outputting this with a input of 5?
this is the code: #include <iomanip> #include <iostream> using namespace std; int main() { const double PERC19 = 0.2; const double PERC49 = 0.3; const double PERC99 = 0.4; const double PERC100 = 0.5; const double Price = 99.00; double totalCost, originalAmount, discountAmount, dRate; int numberofSold; ...
You have not initialized the variable totalCost to anything. Reading an uninitialized variable is undefined behavior (anything can happen). In your case it so happens to return the value 3.95253e-323 which you then output in the last line. The fix is to initialize it with: double totalCost = 0; You can also ensure ...
73,660,023
73,660,905
How condition_variable comes to deadlock
I write a demo about condition_variable. I need the correct order to be first-second-third, but there comes to the deadlock.Program infinite loop and there is no output. class Foo { public: void printfirst() { printf("first"); } void printsecond() { printf("second"); } void printthird() { printf("third"); } Foo...
The first code may deadlock because, for example, cv2 might be notified before third starts running. The condition variable doesn't remember that you notified it. If nobody is waiting when you notify it, nothing happens. The second code remembers that the notification was sent. It only waits if secondready is false, ot...
73,660,415
73,660,742
How to print 12 12 12..... using two threads in C++11
How can I print 12 12 12....continuously using two threads in C++11. can someone please suggest. I have used two functions. One function will print "1" and the second function will print "2" with a condition variable. I don't know whether this is a correct approach or not #include <iostream> #include <thread> #include ...
You have to make the flag to be toggled by each thread, then each one should wait for the flag to have the correct value. The code below should make the job #include <iostream> #include <thread> #include <condition_variable> #include <mutex> #include <chrono> using namespace std; mutex m; condition_variable cv; bool ...
73,660,529
73,660,920
How to get the index of function argument in C/C++ with or without a macro?
We are trying to find a way to get the index of a function argument in C. More specifically, we have a function prototype we want to follow, for example, void f(int a, int b, int *c). Unfortunately, this prototype cannot change for compatibility issues. What we want is to allow the user of the function to explicitly st...
If I understand correctly, you have functions that you cannot change and you want to enable calling the function with "missing" parameters in any position. You can use overloading by a wrapper with std::optional arguments. The caller can then either pass parameters or std::nullopt where the wrapper then uses the defaul...
73,660,847
73,661,431
What does time complexity actually mean?
I got the task of showing the time taken by the merge sort algorithm theoretically ( n log(n) ) and practically (by program) on a graph by using different values of n and time taken. In the program, I'm printing the time difference between before calling the function and after the end of the function in microseconds I ...
What time complexity actually means? I interpret your question in the following way: Why is the actual time needed by the program not K*n*log(n) microseconds? The answer is: Because on modern computers, the same step (such as comparing two numbers) does not need the same time if it is executed multiple times. If yo...
73,661,722
73,668,899
What is an std::uniform_real_distribution<>::param_type?
When calling an std::uniform_read_distribution<>, there is an option to specify the range by passing a param_type. dist(generator, decltype(dist)::param_type{1, 2}) seems to work, but I can't find where param_type is defined. Can someone explain what it is or provide a link to its definition in cppreference or the stan...
I looked through the docs more carefully and it turns out I missed it earlier. cppreference P, the type named by D::param_type, which satisfies CopyConstructible satisfies CopyAssignable satisfies EqualityComparable has a constructor taking identical arguments as each of the constructors of D that - take arguments co...
73,661,732
73,661,889
Can't access the file(Internal File Buffer NULL)
I have this strange bug. I have a program which writes text to the file using the fstream, but the file is not being created and therefore no text is appended. When I debug my code, it shows me this: create_new_file = {_Filebuffer={_Pcvt=0x0000000000000000 <NULL> _Mychar=0 '\0' _Wrotesome=false ...} }. But whenever I u...
The problem is that for bidirectional file streams the trunc flag must always be explicitly specified, i.e., if you want the file content to be discarded then you must write in | out | trunc as the second argument as shown below. Thus, to solve the problem change std::fstream create_new_file{ fileName.str()}; to : //--...
73,661,830
73,662,182
How get google.com web page using C socket
I wrote code that should query the google.com web page and display its contents, but it doesn't work as intended. #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <stdlib.h> #include <stdio.h> int main() { int sockfd; struct sockaddr_in destAddr; if((sock...
It should be Host: www.google.com and not Host: http://www.google.com/ However, it might not give you the home page. Google wants you to use HTTPS, so it'll probably redirect you to https://www.google.com/ and you won't be able to implement HTTPS fully yourself (you'll have to use a library like OpenSSL)
73,661,933
73,662,002
C++, conflicting between library function and inhertited class function
#include <iostream> #include <unistd.h> using namespace std; class A{ public: bool close(){ return true; } }; class B: public A{ public: void fun(){ (void) close(1); } }; int main() { B b; b.fun(); return 0; } In class B I want to call the function close(1) whic...
In the scope of the member function fun the name close as an unqualified name is searched in the scope of the class void fun(){ (void) close(1); } And indeed there is another member function close in the base class with such a name. So the compiler selects this function. If you want to use a function f...
73,662,472
73,662,672
Can const-default-constructible objects be of non-class types?
Per my understanding, for class type T to be const-default-constructible type, the default-initialization of T shall invoke a user-provided constructor, or T shall provide a default member initializer for each non-variant non-static data member: ([dcl.init]/7) A class type T is const-default-constructible if default-i...
Is the type of S::I said to be non-const-default-constructible? Yes. Like you've quoted in [dcl.init]/7 only class types can be const-default-constructible. The reason for this is non-class types do not have a default constructor, meaning they have no default value that can be used if they are declared like const T...
73,662,903
73,663,350
Is move elision guaranteed in this case?
Consider the following C++20 code; assume T to be non-movable and non-copyable: struct Cell { Cell(T&& instance) : obj(std::move(instance)) {} private: T obj; }; Cell cell(T{/* arguments */}); Is move elision guaranteed in the constructor of Cell? If T were movable, would it be guaranteed that only the regul...
Is move elision guaranteed in the constructor of Cell? No, the parameter instance of Cell::Cell(T&& instance) is of rvalue reference type T&&, so there can be no move elision here. The parameter instance must bind to the materialized temporary T{/* arguments */}. Then, std::move(instance) will be used to direct init...
73,664,004
73,709,422
How to import classes from C++ to Cython that uses function overloading
I have classes nested in classes and inside of a namespace in c++ in the following format: namespace my_Namespace{ class MyFirstClass{ class NestedClass{ public: NestedClass(int arg){}; NestedClass(double arg{}; NestedClass(std::string arg){}; }; }; };...
The upshot as I explained in the comments is that you can declare the overloads for your C++ methods and Cython understands them. You can't declare overloads for methods of cdef classes, and therefore need to pick some other way of switching based on type. I suggested either using different factory functions (classmeth...
73,665,940
73,666,029
How do I convert this C++ 2D array code into Python?
I am currently trying to improve my Python coding skills, but am stuck on something. I am attempting to convert some C++ 2D array code that ignores spaces into Python. What I am trying to do is allow a user to input a number for a 2D array size of their liking and input what they want inside it. For example, 3 would cr...
nHood[i] is an empty list, so you should append new element to it. D = 0 R = 0 noChange = 0 houseAmt = 0 size = int(input("Please enter the grid size: ")) print("Please enter either 'D' or 'R' using spaces to separate each one:") nHood = [[] for _ in range(size)] #second array for changed votes nHood2 = [[] for _ in ...
73,665,963
73,670,349
Non uniform pixel painting in low Frame rate
I am making an image editing program and when making the brush tool I have encountered a problem. The problem is when the frame rate is very low, since the program reads the mouse at that moment and paints the pixel below it. What solution could I use to fix this? I am using IMGUI and OpenGL. Comparision. Also Im usin...
sample your mouse without redrawing in its event ... redraw on mouse change when you can (depends on fps or architecture of your app) instead of using mouse points directly use them as piecewise cubic curve control points see: How can i produce multi point linear interpolation? Catmull-Rom interpolation on SVG Path...
73,666,163
73,666,210
WINAPI in function signature causes errors
Though I have spent some years in other languages, my ability in C++ is somewhat limited. I currently have a broad goal to figure out how to use a C++ dll as a function in Excel. This question though is focused on a more narrow area of difficulty in trying to achieve this goal. I am following a tutorial found here. ...
Coming from other languages, double WINAPI in the SquareLib.cpp source file looks like it might be a return type Only the double is the return value. WINAPI is a preprocessor macro that resolves to __stdcall, ie it is the calling convention of the function, not part of the return type. and at the very least part of ...
73,666,291
73,666,465
How do I clear a struct if I can't use memset?
I'm working with a piece of C++ code previously compiled (for x86) with clang++. In converting to gcc, I'm seeing an error on the following line: memset(tracking, 0, sizeof(dbg_log_tracking_t)); I understand that I can't memset a 'non-trivial' (compiler's words) class, or something with a vtable, but this is a str...
if you are using C++ 11 or superior tracking = {}; should work
73,666,728
73,666,981
Implications of Derived class having a different ABI, than Base class?
While debugging with gdb, printing the vtable yields something like the following: (gdb) info vtbl *object vtable for 'my_namespace_B::MyDerivedObject' @ 0x555555690bf0 (subobject @ 0x5555556ab710): [0]: 0x55555559ff42 <my_namespace_A::MyBaseObject::function1[abi:cxx11]() const> [1]: 0x5555555a016c <my_namespace_A::MyB...
This is the abi_tag attribute, either applied directly to your function or the return type is tagged. Most likely your functions just return std::string, which libstdc++ tags with abi_tag("cxx11") so that code compiled with the old C++03 copy-on-write strings doesn't link to modern code and silently break. There are no...
73,667,322
73,698,368
Best way to convert a std::vector< std::array<double, 3> > to Python object using Cython
I'm using Cython to wrap a C++ library. In the C++ code there is some data that represents a list of 3D vectors. It is stored in the object std::vector< std::array<double, 3> >. My current method to convert this into a python object is to loop over the vector and use the method arrayd3ToNumpy in the answer to my previo...
This this case the data is a simple C type, continguous in memory. I'd therefore expose it to Python via a wrapper cdef class that has the buffer protocol. There's a guide (with an example) in the Cython documentation. In your case you don't need to store ncols - it's just 3 defined by the array type. The key advantage...
73,667,429
73,675,079
If you std::move an object can you delete the original safely? Should you?
I have difficulty understanding std::move behavior and would like to know whether it is necessary to manually call delete for newStudentDan after "addStudent" in an example like below, or it will be a memory leak. #include <iostream> #include <vector> #include <memory> using namespace std; class Student { public: ...
I think your confusion stems from two related, but separate concepts: storage duration and object lifetime. Moving an object, just like copying, causes a new object to be created, without ending the lifetime of the original. On the other hand, a memory leak is a failure to deallocate memory that is no longer needed, wh...
73,668,294
73,668,300
C++ is saying that -1 < 13 (in programming) is false
I have a string called in, a string that has the value of Hello, world!. I also have a integer called i that has the value -1. When I ask C++ to print out if i is less than the length of in (in.length()), it says false but when I try -1 < 15, it says true. Why does it say false? I feel like this is extremely basic math...
string::length() returns an unsigned integer. You can't compare that to a negative signed value, so the -1 gets converted to an unsigned value, which wraps it to a very large number, which is not less than the string's length, hence the result is false. -1 < 15, on the other hand, is comparing two signed integers, so ...
73,668,821
73,668,851
what does it mean when we create instance of type, created using enum (and not enum class) in c++
I recently got a comment from a SO user (on another account) that Enums are are used to create type and not instances! I wanted to cross-check with the community whether it's right. As far as I understand there is a plain enum (Enum-Type) and Enum Class in C++. My que dealt with just enum and had not written enum clas...
Yes, both enum and enum class define new types (just like struct and class are used to define new types). And yes, enum is not type safe - you can compare two unrelated enums directly for example and enums implicitly convert to int. enum class on the other hand is type safe - you cannot compare unrelated types (unrelat...
73,668,869
73,677,567
Map values to values
I have a problem, let's assume I have a string std::string str = "some_characters_here"; and I have a vector with numbers from 0 to 255 std::vector<int> v; How can I map each number to closest char in string? like this function map (number) -> char in string perfect if we can do str[n] so I have a string len, and I ...
Although the question is not very clear, as I understand it, you want to divide an array with a size of 255 into ranges according to the length of a string and assign the string's characters to those ranges. std::vector<char> __map(const std::string &str) { std::vector<char> result(256); float n = (float)256 /...
73,669,128
73,669,153
Why can we push function object to std::thread directly?
I'm a little bit confuse about why we can do something like this: std::vector<std::thread> vec; vec.reserve(2); vec.emplace_back(std::bind(silly, 1)); vec.emplace_back(std::bind(silly, 2)); for (auto i = 0; i < vec.size(); i++) { vec[i].join(); } // for folks who see this post after // you can use push_back() like...
Edit: I missread code sample, as stated in comments, in this particular case of emplace_back, the constructor is called without going through the implicit conversion chain, as is the purpose of emplace_back. Leaving the rest nonetheless since question was about pushing. C++ offers implicit conversions, which is what en...
73,669,245
73,670,331
Do I need to call glewInit() for every GLFW window I create?
This is my first big OpenGL project and am confused about a new feature I want to implement. I am working on a game engine. In my engine I have two classes: Renderer and CustomWindow. GLFW needs to be initialized, then an OpenGL context needs to be created, then glew can be initialized. There is no problem with this, u...
After some research, i would say that it depends, therefore it's always best to have a look at the base to form an opinion. The OpenGL wiki has some useful information to offer. Loading OpenGL Functions is an important task for initializing OpenGL after creating an OpenGL context. You are strongly advised to use an Op...
73,669,279
73,669,542
Spacing is incrementing for no reason when printing
I'm trying to print a Christmas tree which would look like. There is an only issue with spacing in front of the leaves if I input 1 it looks fine but for anything above that the spaces increase by 1. #include <iostream> #include <iomanip> using namespace std; void pineT (int rows , int finish , int spaces) { ...
The first thing to do to find the problem is to determine whether the problem is in the function main or in the function pineT. When running your program line by line in a debugger, you will determine that when rows == 1, then main will call the function pineT once, like this: pineT( 1, 3, 3 ); When rows == 2, then ma...
73,670,155
73,670,307
How to prevent the compiler from checking the syntactic correctness of a certain branch
I basically want to select one of the branches at compile-time but can't figure out how to address the error that shows up. Here is the code (link): #include <iostream> #include <vector> #include <type_traits> template <typename charT> struct Foo { using value_type = charT; std::vector<value_type> vec; ...
Lift your if constexpr logic into a template function: template <typename charT> void printIt( Foo<charT>& foo ) { if constexpr ( std::is_same_v<charT, char> ) foo.printVec( std::cout ); else if constexpr ( std::is_same_v<charT, wchar_t> ) foo.printVec( std::wcout ); else static_asse...
73,670,564
73,671,127
Is there a way to make function not type-checked in C++?
I am currently implementing a class that is a three-way map, meaning each "index" has three keys and one can retrieve each. The function get is defined as: template<typename returnType, typename getType> returnType get(getType getVal) { if (typeid(returnType) == typeid(getType)) { return getVal; } ...
typeid is not meant to be used this way at compile-time. If you want to operate on types at compile-time, use the tools from #include<type_traits>. typeid is meant to be used if you need to operate on types at runtime (e.g. store ids for types in a container or obtain a printable name for a type) or you need to determi...
73,670,650
73,671,155
find the total number of subarrays with the ratio of 0's and 1's equal to x:y
question given an array of elements 0, 1, 2 with find the total number of subarrays with the ratio of 0's and 1's equal to x:y. input 5 1 1 0 1 2 0 1 output 6 \\5 is the size of array 0 1 2 0 1 are elements of the array 1 1 is x and y and now we have to find the subarrays whose counts of 0's and 1's ratio is equa...
First, the order you read your inputs is different than what you describe, then your transform of the input values make no sense. //... cin >> n; cin >> x >> y; // program expects x then y, then contents of array. a.resize(n); for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i]==0) a[i] = y; else if( a[...
73,670,908
73,670,969
operator<< with cout and precedence
The accepted answers to the questions here and here say that it's all about operator precedence and thus, cout << i && j ; is evaluated as (cout << i) &&j ; since the precedence of Bitwise-Operators is greater than that of Logical-Operators. (It's not the bitwise operator here, but it is the symbol itself which is s...
someone tell what is the precedence of overloaded operator << in comparison to all other existing operators? The inserter << has higher precedence than the relational operator<, operator> etc. Refer to operator precedence. This means that cout << x>y is grouped as(and not evaluated as): (cout << x)>y; Now, cout << x...
73,671,556
73,673,073
qt create button when right click
I am new in qt I want to create a button when I right click There is my code: void MainWindow::right_clicked(QMouseEvent *event) { if(event->button() == Qt::RightButton) { QPushButton *item = new QPushButton(); item->setIcon(QIcon(":/images/7928748-removebg-preview(1).ico")); ...
To capture any mouse event in a QWidget you must override the mousePressEvent method. class MainWindow : public QMainWindow { Q_OBJECT protected: void mousePressEvent(QMouseEvent *event); }; And in the mainwindow.cpp, implement it as follows: void MainWindow::mousePressEvent(QMouseEvent *event) { if(event...
73,671,717
73,671,765
Template paramter pack with different types
Can the following function template be made to actually act based on argument type : #include <iostream> #include <memory> #include <tuple> #include <typeinfo> using namespace std; using UPSTR = unique_ptr<char[]>; template<typename... Ts> void uprint(Ts const&... strs){ auto tp = std::tie(strs...); auto& x = s...
The compiler always instantiates the whole body of a function template, no matter whether some if statements can be proven at compile-time to be false. So any syntax/type errors, even in false branches are reported. But exactly for this use case, there is if constexpr: if constexpr (std::is_same_v<std::decay_t<decltype...
73,672,006
73,672,074
C++, Find out if a string contains a substring?
I don't know how to use the find() function to check if a string contains a substring, then the program should print out all Words, and "Contains" if Sentence contains at least one of them. Can anyone help me out? My usage of find() sets A always to true. Thanks for help #include <iostream> #include <string> using name...
There are a few bugs and issues in this code I think, but the biggest is the for loops all go too far by one. for (i = 0; i <= Words.length(); i++) and for (j = 0; j <= n; j++) should be for (i = 0; i < Words.length(); i++) and for (j = 0; j < n; j++) The valid indexes for a string, vector or array are zero upto bu...
73,672,049
73,672,166
How to make copies of the executable itself in C++?
I want to make copies of the exe file itself multiple times. I tried the following code: #include <fstream> #include <string> int main() { std::ifstream from("main.exe", std::ios::binary); auto buf { from.rdbuf() }; for(int x { 0 }; x <= 10; ++x) { std::string name { "main" + std::to_string(x) + "...
Reading from the input file stream buffer consumes the data. You need to reset the stream to the start after copying the file: ... for (int x{ 0 }; x <= 10; ++x) { std::string name{ "main" + std::to_string(x) + ".exe" }; std::ofstream out(name, std::ios::binary); out << buf; out.close(); from.seek...
73,672,132
73,673,078
The proper way to initialize array of char with constant string
I use a struct to transfer data over TCP-IP and I have to stick with certain packet size, so I use char array of fixed size for text data. Due to the fact that I can't initialize it otherwise, I forced to copy string to that array in constructor using simple function (based on strcpy). The problem is: analyzer (clang-t...
The warning is a false positive. The clang-tidy docs for the warning you got say: The check takes assignment of fields in the constructor body into account but generates false positives for fields initialized in methods invoked in the constructor body. https://releases.llvm.org/10.0.0/tools/clang/tools/extra/docs/cl...
73,672,215
73,692,450
Get user input with multple values formated with comma
I want to achive someting like this: User input values here for example 1,2,3 Your values: 1,2,3 [1,2,3 is inputed by user in one line] and this values are pushed to array.I need check here if number is not bigger than max number for example 4 and isnt below 1. I came up with this code. It takes msg to show for user a...
How can I get integer array inputted by user with commas? #include <iostream> #include <sstream> #include <string> #include <vector> std::vector< int > getMultipleIntAboveZero(std::string msg, int maxNum) { std::istringstream iss (msg); std::string unit; std::vector<int> nums; int num; while(std::...
73,673,455
73,673,506
Put an array in the end of another array C++
Normally it's a question about a buffer with a null-terminated string, but we can extrapolate it to a general case. I have a big array of a fixed length, let's say 10: char outputArray[10] = {'-','-','-','-','-','-','-','-','-','-'}; And I have some other (Edited: smaller) array (in my case it's a char buffer with nul...
It can be done with a single for loop and a single variable: for (char i=0; i<arrLength; i++) { outputArray[10-arrLength+i] = inputArray[i]; } If you make arrLength a char instead of an int, this will even save you 2 bytes of memory ;-) Use memset() to set all memory to an initial value and then memcpy() the...
73,674,436
73,700,701
EspHome custom component
i have a probleme with custom code in esphome.. There is the error : src/screen.h:23:59: error: cannot convert 'MyCustomComponent::MyCustomComponent(esphome::template_::TemplateNumber*&, esphome::template_::TemplateNumber*&, esphome::template_::TemplateNumber*&, esphome::homeassistant::HomeassistantTextSensor*&)::<lamb...
As shown here void esphome::text_sensor::TextSensor::add_on_state_callback(std::function< void(std::string)>callback) You should use std::string instead of String (Arduino string), those are incompatible. I'm not sure what you're going to do with String str = "ff"; but In case you still want to use Arduino String, you...
73,674,935
73,675,091
Can I add main function in C++ header file?
Hi guys I have a vehicule.h header file like this #include <iostream> using namespace std; class Vehicule{ private: string type; //etc... }; //can this function be there or do i need to add it on .cpp file? int main(){ return 0; }
Technically yes, you can. However, if you do put a non-inline function definition such as main into a header, then you may only include the header into one translation unit. This makes the header rather pointless. In conclusion, don't do it because it isn't useful.
73,675,285
73,675,448
Active Qt - add member to Outlook distribution list
I'm trying to use Active Qt to modify a distribution list in Outlook. I'm able to access it and list all of its members with the following code: QAxObject* outlook = new QAxObject("Outlook.Application"); QAxObject* session = outlook->querySubObject("Session"); QAxObject* contactsFolder = session->querySubObject("GetDef...
Use the Resolve method right after a new recipient is created. The method attempts to resolve a Recipient object against the Address Book. And if the recipient is resolved (see the corresponding property) you may call the DistListItem.AddMember method to add a new member to the distribution list in Outlook. Here is how...
73,675,349
73,675,371
C++. What's the best way to initialize multiple static variables in a templated class?
There are class with multiple static variables, e.g. template<class T> struct A { // some code... static int i; static short s; static float f; static double d; // other static variables }; The main way is to use the full template name template<typename T> int A...
Make them inline to be able to give them initializers: template<class T> struct A { // some code... inline static int i = 0; inline static short s = 0; inline static float f = 0.f; inline static double d = 0.; // other static variables };
73,675,368
73,675,380
Calling overrided method on Derived class casted from void ptr causes segmentation fault
Calling overrided method on Derived class casted from void ptr causes segmentation fault. It doesn't if derive from concrete (non abstract) class. #include <cstdio> struct Base{ virtual void base_method() = 0; }; struct Derived : Base{ int x; void own_method(){ printf("own %d", x); } void ...
You didn't run the constructor of Derived, so your code has UB. In case of ItaniumABI, your virtual table is not populated and thus you're likely jumping to an undefined address. If you'd like to use the char array / void* as the memory for Derived, you can do placement new: #include <new> auto derived_ptr = new(void_...
73,675,476
73,677,441
Window background visible through textures
What can I try to solve this problem? In this example (see a screenshot below) I am using OpenGL 1.1 with deprecated functions like: glEnableClientState, glMatrixMode, glTexCoordPointer, and so on. Thanks in advance. You can see the whole example code in this thread: https://community.khronos.org/t/window-background-vi...
Transparency is achieved with the alpha channel and Blending only works when the textures have an alpha channel. When the alpha channel of the transparent background is 0.0 and the alpha channel of the object is 1.0 then you can use the following blending function: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_M...
73,675,612
73,676,371
Why I got syntax error, when trying to use concept?
I am using Visual Studio 2022, with the latest compiler. I have a problem, when I am trying to create concept definition. I got many syntax error, for example syntax error: identifier 'has_type_member' syntax error: missing ';' before '{' template<typename T> concept has_type_member = requires { typename T::typ...
In Visual Studio 2022, ISO C++ 14 Standard in enabled by default. Concept feature is available since C++20. To enable ISO C++20 standard for your project, right click on the project name and select Properties, under Configuration Properties -> General -> C++ Language Standard select ISO C++20 Standard (/stdc++20).
73,675,691
73,675,716
Change Include Path of Interface library
I have just created an interface library called "foo". Now I would like to include each of the modules of foo like this: #include "foo/module.h" Right now, I always have to write the include path as following #include "foo/include/module.h" Is it somehow possible to tell Cmake to ignore the "include" within the path?...
Is it somehow possible to tell Cmake to ignore the "include" within the path? That's not CMake's job. CMake is a build system that hands off the work of actually compiling the C++ text to the compiler and linker. CMake provides command line parameters and tracks which files need to be compiled, but it doesn't deal in...
73,675,909
73,675,916
Bottom coordinates of CListBox is not set correctly
MFC beginner question. I created a listbox and a button using CListBox::Create and CButton::Create respectively, using CRect for their size and location. The two CRect has the same height, but when they are shown in the screen, the height of the listbox is shorter than that of the button. I checked the pixel coordinate...
Add the LBS_NOINTEGRALHEIGHT style: Specifies that the size of the list box is exactly the size specified by the application when it created the list box. Normally, the system sizes a list box so that the list box does not display partial items.
73,677,437
73,677,487
How to use SFML without errors?
My code for Text_Box.cpp is: #include <SFML/Graphics.hpp> int main1() { sf::RenderWindow window(sf::VideoMode(800, 600), "Window", sf::Style::Titlebar | sf::Style::Close); sf::Font arial; arial.loadFromFile("arial.ttf"); sf::Text t; t.setFillColor(sf::Color::White); t.setFont(arial); ...
The compiler needs to specify (in the project settings) /Zc:__cplusplus Never do it bellow. Remove main.c and rename main1 to main. main.c #include <stdio.h> #include "Text_Box.cpp" int main() { main1(); return 0; }
73,677,576
73,677,707
Visual Studio: two little projects with identical "Command Lines" but one cannot find the headers?
I have a solution with two one-source-file projects in it. Each file is: #include <mosquitto.h> The first compiles fine. The second says it cannot find a header. The source code in the second is identical to the first, so it is a mystery why it cannot compile. Pre-compiled headers are not being used in either, so i...
I turned on Tools->Options->Projects and Solutions->Build and Run->verbosity=Detailed, and compared the CL.exe commands issued. To my surprise, the /I include option was NOT present on the failed build command, despite being in the Properties dialog "Command Line" page as pasted above. The issue was that I was building...
73,677,991
73,678,042
I want to take inputs of 2d vector using ranged based for loop. How can i do?
As a beginner i am exploring multiple methods to increase my clarity, so i did this question. // no problem with this looping method vector <vector<int>> vec(n,vector<int>(m)); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> vec[i][j]; } } // but i tried in this way using ranged based lo...
You need to take the values by reference in the range base for-loops. Otherwise v1d and x will be copies and any changes you make to those copies will not be affecting the content of vec in any way. for(auto& v1d : vec) { // or: std::vector<int>& v1d // ^ for(auto& x : v1d) { // or: int& x // ^ ...