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
70,566,857
70,567,492
How to center align a pattern?
How can I align this arrow tail centered unded the arrow head? ** **** ****** ******** ********** **** **** **** **** Here is my code: #include<iostream> using namespace std; int main() { int n; cout<<"enter size"; cin>>n; int rows,columns; cout<<"enter numbers"; cin>>rows>>columns; for(int k...
Assuming you display fixed spaced characters on a terminal, the general algorithm is: Take the width we of the element you want to center. Take the width WA of the area it needs to be centered in Print (WA-we)/2 whitespaces before the element Considering that in your case WA would be 2*n and we would be columns, yo...
70,567,396
70,568,568
Retrieve a type from a string known at compile time
Is it possible to get a type according to a string known at compile time? Mainly with constexpr std::string_view. #include <bits/stdc++.h> template <std::string_view> struct MakeType {}; template <> struct MakeType<"int"> { using type = int; }; template <> struct MakeType<"float"> { using type = float; };...
Yes, you can do such things, even if I currently did not see why we need it. But it did not work on base of std::string_view as we need a data type which contains the data in the object itself. As C++20 offers a simple way to define a constexpr string type via template parms, we have all what we need! template<size_t N...
70,567,569
70,567,607
C++11 Template Class with Multiple Definitions
In summary, I would like to have a templated class that can either have a class member that is a std::tuple or an integral type. The essence of what I want to do is pasted below. #include <tuple> #include <vector> #include <string> template<typename T> class DATA { public: ...
C++14 and newer: template <typename T, typename ...P> struct A { std::conditional_t<sizeof...(P) == 0, T, std::tuple<T, P...>> value; }; C++11: template <typename T, typename ...P> struct A { typename std::conditional<sizeof...(P) == 0, T, std::tuple<T, P...>>::type value; };
70,567,800
70,573,278
How to launch UWP app with app's main window in background using url
I want to launch UWP app from another app. For example I want to launch apps with launch protocol (ms-people:, msnweather:, etc.). I am using API LaunchUriAsync. It is launching the app. But the new app that is launched gets the focus and its main window comes in the foreground on top of the app that I am interacting w...
How to launch UWP app with app's main window in background using url I'm afraid LaunchUriAsync api does not contain such options to launch app's main window in background using url. But we have a workaround that push the launched app into background manually if the app was launched with uri. The OnActivated event han...
70,568,026
70,568,299
How do I use system("chcp 936") in my dialog based project?
The code below is supposed to convert a wstring "!" to a string and output it, setlocale(LC_ALL, "Chinese_China.936"); //system("chcp 936"); std::wstring ws = L"!"; string as((ws.length()) * sizeof(wchar_t), '-'); auto rs = wcstombs((char*)as.c_str(), ws.c_str(), as.length()); as.resize(rs...
There are two distinct points to considere with locales: you must tell the program what charset should be used when converting unicode characters to plain bytes (this is the role for setlocale) you must tell the terminal what charset it should render (this is the role for chcp in Windows console) The first point depe...
70,568,167
70,578,766
Libcurl - curl_multi_poll + curl_multi_add_handle - in one thread - never waits
The curl_multi_poll function in conjunction with curl_multi_add_handle - for some reason it never waits for an event and immediately returns: Simple example: #include <iostream> #include <curl.h> int main() { curl_global_init(CURL_GLOBAL_ALL); CURLM* CURLM_ = curl_multi_init(); CURL* CURL_ = curl_easy_i...
The code doesn't call curl_multi_perform() so it doesn't actually do anything and whatever libcurl wants to do, it still wants to do...
70,568,513
70,568,925
Access bits in memory
I want to assemble a message bit by bit, then handle the message as a vector of unsigned characters ( e.g. to calculate the CRC ) I can assemble the message OK, using either a std::vector<bool> or a std::bitset I can copy the assembled message to a std::vector doing it bit by bit. ( Note: the meesage is padded so that...
Apparently neither of those classes define the layout. Just write your own class and define the layout you want: template <int size> class BitSet final { private: unsigned char buffer[size / 8 + (size % 8 != 0)] = {}; public: constexpr bool get(size_t index) const noexcept { return (buffer[index / 8] >> (ind...
70,568,575
70,577,614
How to get the edges of a 3D Delaunay tessellation with CGAL?
The question is clear from the title. I tried a ton of variants of const DT3::Finite_edges itedges = mesh.finite_edges(); for(DT3::Finite_edges_iterator eit = itedges.begin(); eit != itedges.end(); eit++) { const CGAL::Triple<DT3::Cell_handle, int, int> edge = *eit; edge.first->vertex((edge.second+1) % ...
No need to use addition or modular arithmetic. The solution is simpler: const DT3::Finite_edges itedges = mesh.finite_edges(); for(DT3::Finite_edges_iterator eit = itedges.begin(); eit != itedges.end(); eit++) { const DT3::Edge edge = *eit; const DT3::Vertex::Info v1_info = edge.first->vertex(edge.secon...
70,568,700
70,568,758
Thread of a member function
Mainly for test purposes, I want to run a member function on a thread. Endless tries - and still, only error messages, Please - can anyone explain the cause of the error and some best practices of doing so? Thanks #include <thread> #include <iostream> using namespace std; class Test { public: int x = 1; int ...
Your std::thread object lives only until the end of the expression in which it is created as a temporary. When it is destroyed and the thread is still in a joinable state, std::terminate is called, which aborts your program. You should store the std::thread object somewhere (e.g. in the Test object or in main or locall...
70,568,786
70,569,307
C++ Not able to instantiate a Template Class
Let me put it step by step. The problem is I am not able to instantiate a Template class. Pls help where am i doing wrong. I have a template class as below : template <typename K, typename V> class HashNodeDefaultPrint { public: void operator()(K key, V value) {} }; Then I have a specific class that belongs to th...
You think much to complicated :-) If you already use templates, you can specialize them if you need. That did NOT require new class names! Starting with: template <typename K, typename V> struct HashNodePrint { void operator()(K key, V value) {} }; // and specialize for int,int: template<> struct HashNodePrint<i...
70,569,170
70,569,576
Does going through uintptr_t bring any safety when casting a pointer type to uint64_t?
Note that this is purely an academic question, from a language lawyer perspective. It's about the theoretically safest way to accomplish the conversion. Suppose I have a void* and I need to convert it to a 64-bit integer. The reason is that this pointer holds the address of a faulting instruction; I wish to report this...
You’re parsing that (shockingly informal, for cppreference) paragraph too closely. The thing it’s trying to get at is simply that other casts potentially involve conversion operations (float/int stuff, sign extension, pointer adjustment), whereas reinterpret_cast has the flavor of direct reuse of the bits. If you rein...
70,569,651
70,569,741
polymorphism with vector and function?
I have basically the following code: class A{/*something*/}; class B : public A{/*something else*/}; void foo(B* aux){/*something something*/} int main() { vector<shared_ptr<A>>content; content.emplace_back(new B()); foo(content[0].get());//error, invalid conversion from A to B return 0; } Trying to...
B is always an A, but A is not necessarily always a B, so your foo function cannot accept an A as a B. You could use a dynamic_cast to check whether A is a B for a specific runtime instance, and then call foo after you know for sure that it is a B, but in most cases that is not the best design (see static vs dynamic po...
70,569,736
70,569,843
How to Iterate over number of variadic template Types
I'am currently learning C++ and i am currently building a very simple Entity Component System. For that i have a Function getComponentType which maps each Component to a uint8_t. A Signature is just a std::bitset I would like a method like this. Signature signature = createSignature<TransformComponent, GraphicsComp>();...
From C++ 17 onward you could use a fold expression: template<typename... T> Signature createSignature() { Return Signature((((unsigned long long int)1) << getComponentType<T>() | ...)); } The unsigned long long int cast seems a bit weird, but I left it the same as the question to clarify the use of the fold expres...
70,570,822
70,573,713
Print all visible rows in QTableView in c++
I have QTableView with 100+ rows in it. But at a time only 6 rows are visible. To see next set of rows, I have to use scrool bar. I want to print visible rows in QTableView. But could not do that. I could just able to print single selected row. QItemSelectionModel *select = _table->selectionModel(); QModelIndexList...
You can get the current line number through the value() of the verticalScrollbar, and you can also get the number of displayable lines through pagestep(). This is my code ,you can try it: void TesWidget::onbtnClicked() { int start_index = ui.tableView->verticalScrollBar()->value(); int page_cnt = ui.tableView->...
70,570,860
70,571,138
How to cast nonconst variable to constant static integral class member variable via reinterpret_cast in C++?
I am reading a book on writing modern C++ code for microcontrollers which is named "Real time C++". I am trying to write the codes in the book myself. However, while copying the code from the book and trying to build it, I got a compilation error of: error C2131: expression did not evaluate to a constant. message : a...
It is unclear what the intention behind the reinterpret_cast is, but the program is ill-formed. constexpr on a variable requires that the initializer is a constant expression. But an expression is disqualified from being a constant expression if it would evaluate a reinterpret_cast. Therefore the initialization is ill-...
70,571,273
70,571,518
Template based Linked List - What should be Returned in search operation?
I am working with Templates and defined the below templated ListNode. template <typename T> class ListNode{ private : public: ListNode *left; ListNode *right; T data; ListNode(T data){ this->data = data; } }; If I implement the search Operation on this Linked list with the below...
One option is to keep things simple: return the address of the found item, and nullptr if the item cannot be found: template <typename T> T* List_search(T srch_data) { ListNode<T> *curr = head; while (curr) { if (comp_fn.compare_data (curr->data, srch_data) == 0) ...
70,571,380
70,572,145
Can a type be defined inside a template parameter list in C++?
In the following definition of template struct B, a lambda is used as a default value of a non-type template argument, and in the body of the lambda some type A is defined: template <auto = []{ struct A{}; }> struct B {}; Clang and MSVC are fine with this definition, but GCC complains: error: definition of 'struct<la...
[temp.param]/2 says: Types shall not be defined in a template-parameter declaration. Taking this as written, GCC is correct to reject this code: this prohibition is not constrained to type-id of a type parameter, but applies to anywhere within template parameter declaration. Including nested within a lambda. This se...
70,571,655
70,571,714
constexpr std::string in C++20, how does it work?
Apparently, the constexpr std::string has not been added to libstdc++ of GCC yet (as of GCC v11.2). This code: #include <iostream> #include <string> int main( ) { constexpr std::string str { "Where is the constexpr std::string support?"}; std::cout << str << '\n'; } does not compile: time_measure.cpp:37:31:...
C++20 supports allocation during constexpr time, as long as the allocation is completely deallocated by the time constant evaluation ends. So, for instance, this very silly example is valid in C++20: constexpr int f() { int* p = new int(42); int v = *p; delete p; return v; } static_assert(f() == 42); ...
70,572,014
70,572,079
template class which accepts either a typename or int without auto
Is it possible to have a class template accept either of one (unsigned int, typename) parameter, based upon what was given? Example of what I mean: template<??> class Bytes { // .... }; Bytes<4> FourBytes; Bytes<int> FourBytes; Bytes<DWORD64> EightBytes; Iam aware of the template<auto T>, though was thinking if t...
Template parameters need to either be a type, or a value, there isn't a placeholder for something that can be either a type or a value. That said, you can make a couple factory functions to help you. That could look like template<std::size_t N> class Bytes { // .... }; template <typename T> auto make_bytes() { re...
70,572,683
70,572,702
C++ error: too many initializers for 'int [2]'
I keep getting this error when declaring an int[2] array, but it looks fine to me. error: too many initializers for 'int [2]' int <array_name>[2] = { 0, 255, 255 }; ^ am I doing someting wrong?
You declared the size of array is 2 but gave it 3 elements, I think just change it to int <array_name>[3] will fix the problem
70,573,038
70,573,092
If I've separated a template into a header and source, is there any way to compile it to its own object file?
I like header files to exist as self-documenting references. I try to keep them to declarations with documentation comments, and then program all the implementation in my source files. Essentially a documented interface. I'm working on a project making heavy use of templates and instead of filling up the header with im...
Is there no way at all around this? Yes, there is. If you instantiate a template explicitly in the translation unit where the functions are defined, then you can use those instances in other translation units. But that of course limits what template arguments can be used to those that you've chosen for explicit insta...
70,573,188
70,573,204
Why different behaviour of synthesized default constructor for static and local variable of user defined class type?
In the sample program below, Why is the output different for static & automatic variable of user defined class type ? /* test.cpp */ /* SalesData Class */ class SalesData { public: SalesData() = default; // other member funcations private: std::string bookNo; unsigned int units...
The default constructor has the same behavior on s and s2. The difference is, for static local variables, Variables declared at block scope with the specifier static or thread_local (since C++11) have static or thread (since C++11) storage duration but are initialized the first time control passes through their declar...
70,573,267
70,573,633
How do you define a "Hello World" function in a seperate file in c++
and I apologize for asking a very basic question, but basically, I'm not able to wrap my head around include "fileImade.h" I'm trying to write a main function, that's something like int main() { int x = 5; int y x 6; std::cout << add(x, y) << std::endl; } where add() is defined in a separate .cpp file, and #include -e...
The logic of the file separation may be imagined as: (single file program) /// DECLARATION of all functions needed in the main int add(int x, int y); // declaration of add /// int main() { std::cout << add(2, 3) << std::endl; return 0; } /// IMPLEMENTATION of all functions needed in the main int add(int x, in...
70,573,583
70,573,617
Assigning the reference of a stack allocated variable to a pointer
Given the following function: void test(queue<string>* out) { queue<string> abc = queue<string>(); abc.push("abc"); out = &abc; } Theoretically, the abc variable is allocated on the stack and at the end of the function it must automatically pop out of the stack. But I am assigning the reference of that variab...
The first function is safe, but not equivalent to the second. You are just assigning a value to the pointer out which is a local variable. That local variable is not connected to the caller and the assignment is not observable by the caller. Your function has no side-effects. It is equivalent to void test(queue<string>...
70,573,940
70,574,195
Strict aliasing accross DLL boundary
I've been reviewing C++'s strict aliasing rules, which got me thinking of some code at my previous job. I believe said code violated strict aliasing rules, but was curious why we didn't run into any issues or compiler warnings. We utilized a core .DLL to receive network messages that were handed off to a server applica...
From what I understand, receiveNetworkMessage() invokes undefined behavior Correct. LoginNetworkMessage which was streamed byte-for-byte to the server. Is this portable? No, network communication that relies on binary compatibility isn't portable. Packing/endianness issues aside, I believe it's not since LoginNetw...
70,574,049
70,574,140
How to do a callback using a std::function() as reference?
I want to write a callback like this template<typename T> T GetValue(T (*CallBack) (const string), string in) { T value; try { value = CallBack(in); } catch(std::invalid_argument &e)///if no conversion could be performed { cout << "Error: invalid argument: --> " + string(e.what(...
Link: https://godbolt.org/z/69fTzW36z You have to use the correct function signature - the one which stoi has. As per this link: https://en.cppreference.com/w/cpp/string/basic_string/stol, the signrature is int stoi(const string&, size_t* pos = nullptr, int base = 10) So making the changes (see // CHANGE HERE) #include...
70,575,154
70,728,856
how to achieve Read/Write on YL160 Magnetic Stripe 4in 1 encoder?
i have recently bought a Magnetic Reader/Writer from China (YL160 4 in 1 Reader/Writer) and it came with the Demo application along with the API. What i need mainly from this device is Magnetic Stripe Write, i need to write data to a blank HiCo magnetic card. When i open the demo application under the magnetic stripe t...
Per the product image on Amazon (See ASIN # B09L17C3PG): Magnetic cards are read-only.
70,575,466
70,575,557
Reversible string transformation
I have a string returned from an external C++ lib after saving a record. This string is a key to be used if you want to retrieve the saved record via the lib. I would like to hide the specific key format returned by the lib and return something like a hash code to the user, so that the user can use this key string to q...
It sounds like you want to obfuscate the string so that the user can't use it directly. The question is, how obfuscated does it need to be? If a trivial amount of obfuscation is all that is required, there are any number of simple algorithms that can do that (ROT13, XOR, nybbleizing, etc). You could combine them or ...
70,576,019
70,576,379
why do I have to use int &n instead of int n as parameter?
I have to define a function to delete an element in an array, here is the code void delete_element(int a[], int n, int pos) { if (pos>=n) pos=n-1; else if (pos<0) pos=0; for (int i=pos-1;i<n-1;i++) { a[i]=a[i+1]; } --n; } and here is an example: int n; printf("Enter the length o...
This function doesn't delete an element in an array actually, because it just overlaps the data at pos with the next data, and the size is not changed. It seems that n is array's size, so when you use int n, the size is passed as value, so outer n is not changed. And when you use int& n, the size is passed as referenc...
70,576,360
70,576,673
Zlib Installation - mingw compiler
I just downloaded Zlib's source code from the website -> https://zlib.net/ zlib source code, version 1.2.11, zipfile format .... - US (zlib.net) And I'm struggling with setting up this library, So I'm trying to get some help from some experienced people. And an example will be helpful for me to start with. I'm us...
the steps I use: open cmd.exe type sh You should see a prompt like that: sh-3.1$ once in sh, change dir to your lib dir., so for me is: cd /c/Users/ing.conti/Documents/zlib1211/zlib-1.2.11/ when there, you should ber allowed to call ./configure You should see a message saying: "Please use win32/Makefile.gcc inste...
70,576,797
70,578,075
How to Halt Sound Effect in SDL2
How would I halt the playing of a sound effect in SDL2? Currently I'm playing sound effects using the SDL2 Mixer with this code. Mix_PlayChannel(-1, soundEffect, 0); However I want the play to be able to not have to listen to the entire sound effect and when they leave the menu the sound effect should stop. I've tried...
To stop the Mix_Chunk started with Mix_PlayChannel, you have to use Mix_HaltChannel as explained in this answer for the opposite problem.
70,577,320
70,577,860
Why does getline() cut off CSV Input?
I'm trying to read and parse my CSV files in C++ and ran into an error. The CSV has 1-1000 rows and always 8 columns. Generally what i would like to do is read the csv and output only lines that match a filter criteria. For example column 2 is timestamp and only in a specific time range. My problem is that my program c...
I can't see a reason why you data is being cropped, but I have refactored you code slightly and using this it might be easier for you to debug the problem, if it doesn't just disappear on its own. int main() { string path("D:/Audit.csv"); ifstream input_file(path); if (!input_file.is_open()) { ...
70,577,560
70,595,754
Are seq-cst fences exactly the same as acq-rel fences in absence of seq-cst loads?
I'm trying to understand the purpose of std::atomic_thread_fence(std::memory_order_seq_cst); fences, and how they're different from acq_rel fences. So far my understanding is that the only difference is that seq-cst fences affect the global order of seq-cst operations ([atomics.order]/4). And said order can only be obs...
As I understand it, they're not the same, and a counterexample is below. I believe the error in your logic is here: And said order can only be observed if you actually perform seq-cst loads. I don't think that's true. In atomics.order p4 which defines the axioms of the sequential consistency total order S, items 2-...
70,577,774
70,603,292
Why does the function about getting current time return a wrong time point
I'm working with C++11 and I wrote a function to get the current time point: template <typename T = std::chrono::milliseconds> using Clock = std::chrono::time_point<std::chrono::system_clock, T>; // get current time point template <typename T = std::chrono::milliseconds> inline Clock<T> getCurrentTimePoint(int8_t time...
Well, this is a very stupid mistake. template <typename T = std::chrono::milliseconds> inline Clock<T> getCurrentTimePoint(int8_t timeZone = 0) { return std::chrono::time_point_cast<T>(std::chrono::system_clock::now()) + std::chrono::hours {timezone}; // typo error! timeZone, instead of timezone } The vari...
70,577,852
70,577,952
How to map generic templated compile-time functions
I'd like to have some sort of structure/type/map which can contain std::function specialisations (to contain my callbacks) which have the type known at compile time, without having to do any sort of virtual inheritance or making all my types inherit from a base type. e.g. I'd like GenericFunction in here to hold the st...
You can store std::function<void(void*)>, something like: class Test { public: Test() = default; template <class CallbackDatatype> void attachCallback( const std::string& key, const std::function<void(const CallbackDatatype&)>& callbackFn) { m_callbackMap[key] = [=](void* payloa...
70,578,205
70,579,488
std::ctype Derived Class Fails to Compile for char
The code below fails to compile with: override did not override any base class methods & do_is is not a member of ctype. It works fine for wchar_t. Tested on VC++ 2022, default settings. [EDIT] I got the same result for online GCC. It looks like it is a feature, but why? #include <locale> struct fail_t : std::ctype<ch...
Perhaps not a complete answer, but the cppreference site page for the std::ctype<char> specialization1 does briefly explain (bolding mine): This specialization of std::ctype encapsulates character classification features for type char. Unlike general-purpose std::ctype, which uses virtual functions, this specializatio...
70,578,277
70,578,906
Using perfect fowarding in STL predicate
Does it make sense to use perfect forwarding in some STL algorithm ? What will be the deduced type ? auto it = std::find_if(cont.cgebin(), cont.cend(), [](auto&& element){ return myFunction(std::forward<decltype(element)>(element)); }) I suppose the L-value version will be...
The deduced type of element depends on how the lambda is used within find_if. find_if will never move by itself (you could pass a movable-iterator to find_if, but then it's not find_if that's doing the move, but the dereference operator on the iterator). find_if will pass the value returned by the dereference operator ...
70,578,331
70,620,067
SFML: Object's shape not rendered in window
I want to be able to render sf::CircleShape (representing pointwise charges) when pressing mouse buttons on the window. The problem is easy enough, however the shapes that I want to draw are attributes of a class Charge. The Scene class implements window management and event polling/ rendering methods and it has an att...
Your range-based for loop uses auto instead of auto&, thus you're constantly creating temporary copies of the Charge class. Additionally, you shouldn't mix sf::Mouse::getPosition() with events. The mouse events already provide the position: event.mouseButton.x / event.mouseButton.y.
70,578,669
70,578,716
Using 'new' when creating a linked list
I've been trying to create a linked list in C++. I am trying to avoid using the keyword new when creating it, but it doesn't seem to work // Linked lists struct Node { int value; Node *next; Node( int val ) : value( val ), next(nullptr) {}; }; int main() { vector<int> vec = { 2,5,7,1,4,7 }; //...
Saying Node temp( v ) will create a local variable scoped to the for loop. On each iteration the local variable will be created, and at the end of the iteration destroyed. You're storing a pointer to the local variable, which is undefined behaviour. What is probably happening is that the local variable is being created...
70,578,807
70,579,111
bitwise conversion of decimal numbers to binary
The code works fine for some values like for eg 10 the output is 1010 which is correct but for 20 or 50 or 51 the output is wrong or atleast seems so to me. please help ! #include <iostream> #include <math.h> using namespace std; int main() { int n; cin >> n; int ans = 0; int i = 0; w...
After trying to run your code, it works. 51 correctly comes out as 110011 and 50 as 110010 and 20 as 10100. Those are the correct bit values, you can try calculating them by counting or by just adding 10 (i.e. 1010) in different ways.
70,578,986
70,579,579
ARMv7 NEON: Unpack 32 bit mask to 64 bit mask
I have a 32 NEON bit mask that I need to unpack to 64 bits like so: uint32x4_t mask = { 0xFFFFFFFF, 0xFFFFFFFF, 0, 0 }; uint64x2_t mask_lo = { 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF }; uint64x2_t mask_hi = { 0, 0 }; What I came up with so far is this: uint64x2_t mask_lo = vmovl_u32(vget_low_u32(mask)); // { 0x00000...
It’s unclear why do you want 0xFFFFFFFF to unpack into 0xFFFFFFFFFFFFFFFF If you want sign extend, use reinterpret intrinsics, and vmovl_s32 for the unpacking. This will unpack 0x80000000 into 0xFFFFFFFF80000000 If instead you want to duplicate the uint32_t lanes, use vzipq_u32 intrinsic with your source vector in both...
70,579,550
70,581,590
Why am I unable to enter elements in the linked list while the function is working otherwise?
I wrote a program to merge two sorted linked list into one and this function was the one I used to do it but it's not working. The code of the function is as follows is as follows: void combine(Node **temp, Node *temp_1, Node *temp_2){ while(temp_1 != NULL || temp_2 != NULL){ if(temp_1->data > temp_2->data){ ...
The issue is the while condition: while(temp_1 != NULL || temp_2 != NULL){ This will allow the execution of the body of the loop when just one of those two pointers is null, and this will result in undefined behaviour on the first statement in that body: if(temp_1->data > temp_2->data){ The || should be an &&. Th...
70,579,657
70,816,049
{fmt} How to install and use fmtlib in Visual Studio?
I am trying to install fmtlib and I have downloaded the zip folder and extracted it, what do I do next to use it in my Visual Studio 2022 project? Because it's my first time installing an external library. Im using windows 10.
Once you have downloaded and extracted the fmtlib, Open Visual Studio and create new project New Project -> Console App replace the application file where main method is present with below code. First line (#define FMT_HEADER_ONLY) is mandatory, which tells compiler to compile fmt header file also. #define FMT_HEADER_O...
70,579,990
70,580,105
Why does binary search algorithm require returning the recursive calls?
I was implementing recursive binary search and I ran into this problem that really confused me. Here is the code that I was initially running: ''' int recursiveBinarySearch(int* arr, int start, int end, int key){ int middle = (start + end) / 2; if (start >= end)return -1; if (arr[middle] == key)return middle...
Let's assume, X is the function we are calling from the main function. And there is a function Y which is being called from function X. Function Y does some computation and calculates the result for X. So you should just call function Y and return it's result like below. Y() { // Some computation return result; } X(...
70,580,020
70,580,203
I try to write something from a class to a file but it has undefined refrence error c++
I try to write somthing from my class to a file bu it has this error C:\Users\Lenovo\AppData\Local\Temp\ccaLsCIe.o:main.cpp:(.text+0xe7): undefined reference to `CoronaVaccine::CoronaVaccine(std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::__cxx11::basic_string<char, std::char_traits, std::all...
The problem is that you have provided only a declaration for the parameterised constructor CoronaVaccine (string="", string="",int=0,string="");. You can solve this by providing the corresponding definition as shown below: //define the constructor. This uses constructor initializer list CoronaVaccine::CoronaVaccine (st...
70,580,209
70,580,287
Getting mismatched types error when i tried to assign numeric value to array object using pointer
I have initiated an array of 6 elements and tried to print it using a function called 'print'. I have used array object from the stl library. I passed the address of the array object to the print function. When I tried to change the value of the array object in the print function I am getting mismatched types error. #i...
In *(*arr+2)=2; you deference the array pointer and try to add 2 to it and then dereference that result to assign 2. I assume you want to assign 2 to the element at index 2 in the array. You do not need to use pointers here though, take the array by reference. And, never #include <bits/stdc++.h>. #include <array> //...
70,580,647
70,580,730
Libcurl - how can you explain this behavior curl_multi_poll
This is my third question about curl_multi_poll, but now I seem to have done everything according to the rules: #include <iostream> #include <curl.h> int main() { curl_global_init(CURL_GLOBAL_ALL); CURLM* CURLM_ = curl_multi_init(); CURL* CURL_ = curl_easy_init(); curl_easy_setopt(CURL_, CURLOPT_...
As is explained in the documentation, curl_multi_poll() can return "early" without any socket activities when libcurl has "other stuff" to do. Most notably things that are based on timers or timeouts. Sometimes enabling CURLOPT_VERBOSE and watching that output helps explain what it does at a specific moment in time.
70,580,681
70,581,229
function returning - unique_ptr VS passing result as parameter VS returning by value
In c++, what the preferred/recommended way to create an object in a function/method and return it to be used outside the creation function's scope? In most functional languages, option 3 (and sometimes even option 1) would be preferred, but what's the c++ way of best handling this? Option 1 (return unique_ptr) pros: f...
In modern C++, the rule is that the compiler is smarter than the programmer. Said differently the programmer is expected to write code that will be easy to read and maintain. And except when profiling have proven that there is a non acceptable bottleneck, low level concerns should be left to the optimizing compilers. F...
70,580,799
70,581,965
Should I use compare_exchange_weak(or strong) when check atomic<bool> variable is set?
Below code is an usage example of atomic<bool> from book c++ concurrency in action chapter 5. Why do they use compare_exchange_weak for checking b is set and why do they use !expected inside while loop ? bool expected=false; extern atomic<bool> b; // set somewhere else while(!b.compare_exchange_weak(expected,true) && ...
Wow that is a confusing piece of code. Firstly the obvious point, the compare_exchange_weak version (might) change the value of the underlying atomic value. b.load() does not, so they are not equivalent. To explain... while(!b.compare_exchange_weak(expected,true) && !expected); b.compare_exchange_weak(expected,true) ...
70,581,597
70,588,507
Why does this_thread::sleep_for not reduce CPU usage of while loop
I have a while loop as follows: while(true){ //do stuff std::this_thread::sleep_for(std::chrono::milliseconds(100)); } When I look at the CPU usage it is almost 100% ... is there any way to do something like this while preserving CPU cycles without having to use complicated condition variables? EDIT: "do stuf...
I figured out the reason: During the logic of the code ("// do stuff") there was a continue statement. The continue statement caused the thread to skip over the sleep statement causing it to loop continuously. I moved the thread_sleep to the top of the while loop and the CPU usage went from 99% to 0.1%
70,581,832
70,581,932
How do I replace this raw loop with an STL algorithm or iterators? (avoiding unchecked subscript operator)
I'm implementing a generic clone of the Snake game in C++ as an exercise in following the C++ Recommended Guidelines. I'm currently working on the Snake's update() method, which is tiggering a Guideline-violation for using the unchecked subscript operator in a for loop: Prefer to use gsl::at() instead of unchecked sub...
You can std::rotate the snake so that the old tail is the front element, and then overwrite that with the new segment. void Snake::update() noexcept { auto new_head = head() + heading; std::rotate(body_segments.begin(), body_segments.end() - 1, body_segments.end()); head() = std::move(new_head); } Alternatively,...
70,581,961
70,582,049
Multilevel static inheritance member accessing with CRTP
I've been trying to implement a multilevel inheritance using CRTP in C++. But I'm facing the problem of accessing members with more than 2 levels. There is no problem with 2 levels, I'm using the friend and private constructor technique. The problem faces when I try to add another level to the hierarchy. Here's my exam...
In AnimState, value is inherited from a base that depends on a template parameter. Because of that, it must be accessed using this->value, or AnimState::value, or State<...>::value. That's probably because value could also be the name of a global variable, and may or may not exist in the parent depending on the value o...
70,582,103
70,595,658
Windows Toast Notification callback not being invoked
I managed to send Toast messages but once clicked, the callback is not invoked. This is the toast-tutorial that was used. The messages should be sent through classic Win32 and in order to do this, a shortcut needs to be created which contains the AUMID and the CLSID. This is explained in Step 5 of the tutorial, where f...
Just on the name alone it seems to me like you need to set the PKEY_AppUserModel_ToastActivatorCLSID property on the .lnk and not just the AUMID. MSDN says: Used to CoCreate an INotificationActivationCallback interface to notify about toast activations. This page is marked as pre-release but does have a different Ins...
70,582,109
70,582,374
C++ std::thread arguments must be invocable after conversion to rvalues
I'm clueless on whats going on here here is a simple code example of what I'm trying to achieve: main.cpp #include <iostream> #include <thread> int main(int argc, char** argv) { constexpr int SIZE = 10; std::array<int, SIZE> arr{0}; auto add = []<typename T>(std::array<T, SIZE>& arr) { for (int ...
std::reference_wrapper is not a std::array, so T cannot be deduced. add(std::ref(arr)); doesn't compile neither. You might use std::thread t1([&](auto arg){ add(arg.get()); }, std::ref(arr)); Demo
70,582,161
70,582,463
std::string constructed from subrange of char array calls strlen
It is similar to LeetCode C++ Convert char[] to string, throws AddressSanitizer: stack-buffer-overflow error The code is #include <string> int main() { char buf[10] = {6, 6, 6, 6, 6, 6, 6, 6, 6, 6}; std::string s{buf, 2, 3}; return 0; } Execution ends up with address sanitizer complaining about strlen's ...
Check cpp insights. It is great tool to see what was used during overload resolution. It generates this: #include <string> int main() { char buf[10] = {6, 6, 6, 6, 6, 6, 6, 6, 6, 6}; std::string s = std::basic_string<char, std::char_traits<char>, std::allocator<char> >{std::basic_string<char, std::char_traits<char...
70,582,321
70,661,018
glfw window with no title bar
I am trying to make a way to toggle my window between windowed mode and fullscreen mode. I had done it successfully except for one problem. The title bar is not working! You can’t move the window either. Without this piece of code everything works just fine. setFullscreen method: void Window::setFullscreen(bool fullscr...
@tomasantunes help me figure this out. in setFullscreen I am setting the window to be at 0, 0 or the top left of the screen. The title bar didn't actually disappear is was just off screen. so if I set the window to be at 100, 100 instead I get the title bar back. This was pretty dumb of me to make a stupid mistake like...
70,582,577
70,605,436
Static linking of SDL2 2.0.18 with VS 2019, (memcpy already defined bug MT setting.)
I tried to compile and link a very simple SDL2 example code. It works for all the following configurations: Win32 release and debug for both MD and MT setting in runtime lib. x64 release and debug with runtime lib \MD When I compile and link with x64, release and \MT I get this error: Error LNK2005 memcpy alrea...
Thanks to keltar advice about the SDL_LIBC flag Solution is in the file SDL_config.h change the following starting from row 32 #if defined(__WIN32__) #include "SDL_config_windows.h" #elif defined(__WINRT__) .... and change it to this #if defined(__WIN32__) #if defined(_WIN64) #define HAVE_LIBC 1 #endif #include "SDL_c...
70,582,675
70,582,757
What order does gcc __attribute__((constructor)) run in relation to global variables in same translation unit?
I saw this question answering some of this, but at least not clearly my question. I suspect that I should probably not access any global variables that requires code to execute (e.g. std::string), but how about POD variables? std::string s = "hello"; const char* c = "world"; extern std::string s2; // (actually below in...
The documentation says: However, at present, the order in which constructors for C++ objects with static storage duration and functions decorated with attribute constructor are invoked is unspecified. !strcmp(c, "world") is probably safe to assume. char* c = "world"; This is ill-formed because string literal does...
70,582,957
70,584,031
Threads appear to run randomly.. Reliable only after slowing down the join after thread creation
I am observing strange behavior using pthreads. Note the following code - #include <iostream> #include <string> #include <algorithm> #include <vector> #include <pthread.h> #include <unistd.h> typedef struct _FOO_{ int ii=0; std::string x="DEFAULT"; }foo; void *dump(void *x) { foo *X; X = (foo *)x; std::co...
See Peter's note - pthread_join should be called with the thread id, not the status value that pthread_create returned. So: pthread_join(t_id[ii], NULL), not pthread_join(t_status[ii], NULL). Even better, since the question is tagged C++, use std::thread. – Pete Becker
70,583,131
70,583,255
How to specify default initialization conditionally based on templated member variable type
I have a templated class that uses std::conditional to determine the type of a particular member variable. However, I'd like to also change the default initialisation behaviour (either in the ctor list initialisation, or in the member declaration itself) depending on that condition, as one of the options is a singleton...
std::conditional_t<UseSingleton, Singleton&, NotSingleton> m_member = []() -> decltype(m_member) { if constexpr (UseSingleton) return Singleton::getInstance(); else return {}; }(); If you don't want this to be a default initializer, you can also put it in the member init...
70,583,395
70,587,711
Why is std::regex notoriously much slower than other regular expression libraries?
This Github repository added std::regex to the list of regular expression engines and got decimated by the others. Why is that std::regex - as implemented in libstdc++ - so much slower than others? Is that because of the C++ standard requirements or it is just that that particular implementation is not very well optimi...
Is that because of the C++ standard requirements or it is just that that particular implementation is not very well optimized? The answer is yes. Kinda. There is no question that libstdc++'s implementation of <regex> is not well optimized. But there is more to it than that. It's not that the standard requirements inh...
70,584,096
70,585,784
Exception: STATUS_ACCESS_VIOLATION at rip=0010040108D when executing program
I have a problem with execution of the project compiled in eclipse Version: 2021-12 (4.22.0) The program is just 2 files: function.asm .code32 .global array .section .text array: pushl %ebp movl %esp, %ebp pushl %ecx pushl %esi movl 12(%ebp), %ecx movl 8(%ebp), %esi ...
OK, I've managed to figure this out I've finally successfully executed the program by compiling at my cygwin64 that is linked to my ECLIPSE And I've used two simple commands: as function.asm -o function.o g++ main.cpp function.o And the AT&T assembly syntax for the external function: .code32 .global array .section ...
70,585,114
70,595,092
Imported target "Boost::system" includes non-existent path "/include"
I am a newbie with CMake please bear with me. I have a library (libvpop) which I created in c++ using some Boost components (system and date_time). I can link to it without a problem in windows but on Ubuntu, I am getting an error that implies the path to the boost include files cannot be found. Here is the simple CM...
I have found a work around thanks to this article: https://github.com/VowpalWabbit/vowpal_wabbit/issues/3003 Something in the Boost cmake process is causing boost to look for the include files at /include when they are really at /usr/include. I created a symbolic link for /include to point to /usr/include and this all...
70,585,249
70,585,451
Is there any way to convert a array pointer back into a regular array?
I am trying to pass an array through a function but when I try to get the length of the array it gives me the length of the pointer. Is there any way to convert the array pointer back into a regular array? float arr[] = {10, 9, 8] void func(float arr[]) { // now I want to figure out the size of the array int le...
You can declare the parameter a reference to an array. void func(float (&arr)[10]) { // but you have to know the size of the array. } To get around having to know the size, you can template on size template<int Size> void func(float (&arr)[Size]) { // Now the size of the array is in "Size" // So you don't ...
70,585,477
70,585,623
How to use enum as starting args with aliases
I am trying to use enum as starting args. It should works as aliases pairs so "i" and "info" should have same value, etc... I know it is possible to use if/else with flags, but i would like to done this using for eg. switch with int value. #include <iostream> #include <string> namespace startFlags { enum class fla...
You need to cast enum classes if you'd like to print them as int (or something else) even though the underlying type is int: Example: #include <iostream> namespace startFlags { enum class flag { i, info = i, // both will be 0 e, encrypt = e, // both will be 1 d, decrypt = d, // ... ...
70,586,050
70,586,170
How to construct an array using make_unique
How can I use std::make_unique to construct a std::array? In the following code uptr2's declaration does not compile: #include <iostream> #include <array> #include <memory> int main( ) { // compiles const std::unique_ptr< std::array<int, 1'000'000> > uptr1( new std::array<int, 1'000'000> ); // does not co...
std::make_unique< std::array<int, 1'000'000> >( { } ) does not compile because the std::make_unique function template takes an arbitrary number of arguments by forwarding reference, and you can't pass {} to a forwarding reference because it has no type. However, std::make_unique< std::array<int, 1'000'000> >() works j...
70,586,056
70,586,114
How to change c++ code to make clang-tidy modernize-use-transparent-functors happy
We have the following c++ code using catch2 framework: auto check2 = [](size_t exp, size_t val, auto comp) { REQUIRE(comp(exp, val)); }; check2(10, 20, std::equal_to<size_t>{}); and clang-tidy generates the following /test_lingua.cpp:1236:36: warning: prefer transparent functors 'equal_to<>' [modernize-use-transpa...
You simply replace std::equal_to<size_t>{} with std::equal_to<>{} (C++14 and above, uses template default argument) or std::equal_to{} (C++17 and above, uses CTAD). This way the std::equal_to<void> specialization is used, which generically compares two arguments a and b of any types as if by a == b (plus perfect for...
70,586,376
70,586,449
Assigning values to std::array of std::optional objects
I am trying to fill a std::array of std::optional objects as below. class MyClass { private: int distance; MyClass(int x, int y); friend class MasterClass; }; MyClass::MyClass(int x, int y) { distance = x+y; } class MasterClass { public: MasterClass(std::array<std::optional<int>,5> xs, std::array...
Looks like maybe you are coming from Java, or C#. When you assign a value in c++, it is rare that you will use new. The issue is, that you are basically doing this: std::optional<MyClass> o = new MyClass(); o is of type, std::optional<MyClass> and new My Class() is of type MyClass *. You can see from here that there i...
70,586,470
70,587,501
How to speed up my Print all partitions of an n-element set into k unordered sets
how to speed up my program? my task: 1<=k<=n<=10, time 1 sec Print all partitions of an n-element set into k unordered sets. Partitions can be output in any order. Within a partition, sets can be displayed in any order. Within the set, numbers must be displayed in ascending order. Follow the format from the example. ex...
Thanks every one removed the num function, added the sum variable to func, which increase by 1 when pushing, and decrease it by 1 when pop
70,587,080
70,705,202
Alpaca Traders API Unable to Connect with httplib
I am attempting to use the C++ wrapper for the Alpaca Traders API for the found here: https://github.com/marpaia/alpaca-trade-api-cpp#client-instantiation However, I'm having trouble even connecting to my paper trading account. Here is the code from the wrapper for getting the Alpaca account: httplib::Headers headers(c...
I found the problem. After looking over the documentation on the cpp-httplib github, the SSLClient doesn't have the https:// at the beginning of the URL, and me having that in there was causing the problem. So you want: httplib::SSLClient client("paper-api.alpaca.markets"); and not: httplib::SSLClient client("https://...
70,587,148
74,369,544
Why is AUDCLNT_E_ENDPOINT_CREATE_FAILED triggered when I use WASAPI to create an audio endpoint on a Windows computer?
I used Core Audio to collect audio on a Windows computer. There was no problem at first, but after calling the initialize interface many times, the AUDCLNT_E_ENDPOINT_CREATE_FAILED error message appeared. Does anyone know the reason? API link is as follows:https://learn.microsoft.com/en-us/windows/win32/api/audioclient...
Finally, I found the answer, the computer appeared AUDCLNT_E_ENDPOINT_CREATE_FAILED error msg, because of the Kaspersky anti-virus software baned the audio stream from computer to SDK. Therfore, I configured the white list of software, and SDK run normally.
70,587,488
70,596,088
Conan on windows claims setting isn't set, it is set
I am trying to port a program from Linux to windows. The program is built with conan. Currently I run: conan install . -if build -s build_type=Debug I get this error: ERROR: : 'settings.compiler.cppstd' value not defined I have this in my conan.py: class ConanFileNeverEngine(ConanFile): generators = "pkg_config"...
Settings are external, project wide configuration, they cannot be defined or assigned values in conanfile.py files. Settings are defined in your profile, like the "default", you can see it printed when you type conan install, something like: Configuration: [settings] arch=x86_64 arch_build=x86_64 build_type=Release com...
70,587,536
70,588,156
What is function name in c++
I know the function name in ASM is just the address of the first instruction in the function. So I think the function name should be the right value in c++. But why I also can get the address of the function name. And both can be assigned to the function pointer like these: typedef int (*Func)(); int A(){ return 1;...
Lets take a look at line by line explanation of your code snippet. typedef int (*Func)(); //Statement 1: This means Func is just another name for a "pointer to a function that takes no parameter and returns an int //Here you are defining a function named A that takes no parameter and returns an int int A(){ retur...
70,588,019
70,588,256
Converting between instances of a class template using a member function
I have a couple of strong types that are just aliases of a class template that contains useful shared code. template <typename T> struct DiscretePosition { public: int x{0}; int y{0}; // ... useful generic functions }; struct ChunkTag{}; struct TileTag{}; using ChunkPosition = DiscretePosition<ChunkT...
Here is one possible generic solution that allows you to specialize a get_scaling_factor function for conversions you want to allow: godbolt link #include <iostream> struct ChunkTag{}; struct TileTag{}; template<typename T, typename U> consteval double get_scaling_factor(); template<> consteval double get_scaling_fa...
70,588,183
70,588,273
How can I transform int to string then join with std::ranges::views?
#include <iostream> #include <numeric> #include <ranges> #include <vector> #include <string> #include <string_view> int main() { auto str = ( std::views::iota(1) | std::ranges::views::take(5) | std::ranges::views::transform([](int x) -> std::string_view { return std::to_string(x...
If I use std::string for return type of lambda for transform, it throws many error on compile time. What you have observed is a C++20 defect that has been resolved by P2328. If you use a newer compiler version that has already implemented P2328 (such as gcc-11.2), your code will be well-formed. Before P2328, I think ...
70,588,538
70,588,780
How to efficiently write a function for this?
I have a long string which I separate to shorter strings and parallelize them. How to write a function which passes the thread count and separates the string to that many shorter segments? This is how I've been doing //Thread count is 4 seg = content.length() / 4; string dataSeg1, dataSeg2, dataSeg3, dataSeg4; dataSe...
I think you should use a loop because you have a number of lines of code that are almost identical. Using your code as a base: static const unsigned int numberOfThreads = 4; const size_t segmentLength = content.length() / numberOfThreads; std::vector<thread> threads; for (int threadCount = 0; threadCount < numberOfThre...
70,588,853
71,017,830
UE4. Widget component doesn't show up when its outer is controller
As it's said, in UE 4.27 widget component doesn't show up when its outer is player controller. But in 4.18 version it worked. Could you please explain why ? And how ( if it's possible ) can I make it work in 4.27 ? Widget is set in the widget component. To reproduce: .h: UPROPERTY(EditDefaultsOnly) TSubclassOf<UComicFX...
Okay. The answer is: APlayerController derives from AController. And AController in it's constructor calls SetHidden(true); and it affects it's children ( or actors whose outer is the controller ). To solve just add in your Controller constructor: SetActorHiddenInGame(false);
70,588,880
70,589,821
what is the logic behind it? how output came
In c++, I am not able to understand this code logic. Can someone explain it? Output is 0 3 5 7 9 11 13 15, mainly if(i&1){continue} logic behind it. #include<iostream> using namespace std; int main(){ for(int i = 0; i<=15; i+=2){ cout<<i<<" "; if(i&1){ continue; } i++; ...
i & 1 performs a bitwise AND between i and 1. So if i == 13, then you are performing: 1101 AND 0001 --------- 0001 So when i == 13, if(i & 1) would be essentially if(1) or if(true). Similarly, if i == 10, 1010 AND 0001 = 0000, so if(i & 1) would be essentially if(false). Now you might see a pattern, what y...
70,589,479
70,589,519
Nesting comments is not allowed in C/C++. But what do the following errors mean when you try to put one comment pair inside the other?
Consider the following code from 'C++ Primer' by Lippman, #include <iostream> /* * comment pairs /* */ cannot nest. * "cannot nest" is considered source code, * as is the rest of the program */ int main(){ return 0; } On compiling, $cl -EHsc .\Program.cc Microsoft (R) C/C++ Optimizing Compiler Version 19.30.3070...
A comment starts with a /* and ends at */. So in the example, the comment is /* * comment pairs /* */ The fact that there is a second /* inside the comment does not "restart" it. It still ends an */. So then the compiler tries to interpret cannot nest. as source code. Its best guess seems to be that int cannot could...
70,589,728
70,589,801
No Function to Pointer Decay during Assignment
In the below given code snippet, when i wrote f = A; then why doesn't A decay to a pointer to a function? //Func is alias for "pointer to a function that returns an int and does not take any parameter" typedef int (*Func)(); int A(){ return 1; } int main() { Func* f = &A;//cannot convert ‘int (*)()’ to ‘int (*...
why doesn't A decay to a pointer to a function? The error message says that a function (int()) cannot be implicitly converted to a pointer to a pointer to a function (int (**)()), because the type of the expression (A) is a function. The function would decay if there was a valid conversion sequence to the target type...
70,589,732
70,590,127
Transpose a 2D vector matrix
Is there a way to find transpose a 2D vector matrix without allocating another 2D vector?? Sample Testcase Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Code that I tried class Solution { public: void rotate(vector<vector<int>>& matrix) { int i,j, n=matrix.size(),temp; ...
Below is the code for inplace(Fixed space) || n*n matrix class Solution { public: void rotate(vector<vector<int>>& matrix) { int i,j,n=matrix.size(); for(i=0; i<n; i++) { // Instead of j starting with 0 every time, its needs to start from i+1 for(j=i+1; j<n; j++) { ...
70,590,059
70,590,426
C++ how to define custom key in map(It's a little different from similar problems)?
I want to define a map like: #include<map> struct key{ vector<int> start_idx; vector<int> len; }; map<key, int> m; I looked at other questions and found that I could write the comparison function like this struct Class1Compare { bool operator() (const key1& lhs, const key2& rhs) const { ..... ...
You can have data members in you comparer. struct Class1Compare { bool operator() (const key1& lhs, const key2& rhs) const { // uses lhs, rhs and file } char * file; }; Your map will require a non-default constructed Class1Compare. char * file = /* some value */ map<key, int, Class1Compare> m({...
70,590,092
71,620,646
Is it guaranteed to be 2038-safe if sizeof(std::time_t) == sizeof(std::uint64_t) in C++?
Excerpted from the cppref: Implementations in which std::time_t is a 32-bit signed integer (many historical implementations) fail in the year 2038. However, the documentation doesn't say how to detect whether the current implementation is 2038-safe. So, my question is: Is it guaranteed to be 2038-safe if sizeof(std::...
Practically speaking yes. In all modern implementations in major OSes time_t is the number of seconds since POSIX epoch, so if time_t is larger than int32_t then it's immune to the y2038 problem You can also check if __USE_TIME_BITS64 is defined in 32-bit Linux and if _USE_32BIT_TIME_T is not defined in 32-bit Windows ...
70,590,194
70,590,515
small object optimization useless in using std::function
Many topics told us that use small object like lambda expression could avoid heap allocation when using std::function. But my study shows not that way. This is my experiment code, very simple #include <iostream> #include <functional> using namespace std; typedef std::function<int(int, int)> FUNC_PROTO; class Test { ...
Older versions of libstdc++, like the one shipped by gcc 4.8.5, seem to only optimise function pointers to not allocate (as seen here). Since the std::function implementation does not have the small object optimisation that you want, you will have to use an alternative implementation. Either upgrade your compiler or us...
70,592,633
70,592,911
Why does the sizeof a class give different output in C++?
According to the cppreference, When applied to a reference type, the result is the size of the referenced type. But in the following program, compiler is giving different output. #include <iostream> using namespace std; class A { private: char ch; const char &ref = ch; }; int main() { c...
Firstly you're asking for the size of the object, not of the reference type itself. sizeof(A::ref) will equal 1: class A { public: char ch; const char &ref = ch; }; int main() { cout<<sizeof(A::ref)<<endl; return 0; } The object size is 16 because: The actual size taken up by the referen...
70,592,980
70,593,488
C++ error: no matching function for call to ''"
Although this question has been asked previously on the community, however, those other cases are different from mine, and their solutions cannot be applied in my case. So I have a very big header "rrc_nbiot.h" file with the following struct: #include "rrc.h" namespace asn1 { namespace rrc { ... // SystemInformationBl...
Thanks to @molbdnilo in the comments, I fixed the error. It was as just as he said. When I call the member function, I should not pass the argument it as a pointer in my case. The argument should be like this: sib2_ref->pack(bref);
70,593,236
70,594,325
Boost.Spirit X3 -- operator minus does not work as expected
Consider the following code: TEST_CASE("Requirements Parser Description", "[test]") { namespace x3 = ::boost::spirit::x3; std::string s = "### Description\n\nSome\nmultiline\ntext." "\n\n### Attributes"; std::string expectedValue = "Some\nmultiline\ntext."; auto rule = x3::lit("##...
Probably operator precedence. The unary + operator takes precedence over the binary - operator. This leads to: From the boost manual: The - operator difference parser matches LHS but not RHS. LHS is +x3::char_ RHS is (x3::lit("###") >> *x3::space >> x3::lit("Attributes")) Now LHS +x3::char_ matches as many characters a...
70,593,479
70,593,868
Is it possible to change value of a constant variable via reinterpret_cast?
all. I have read a code snippet from a book where the author tries to set the value of a register via direct memory access (he simulates this process). He used reinterpret_cast<volatile uint8_t*> for this. So, after reading his code, out of curiosity I have tried to apply the same code for a constant variable, and I ex...
The thing that is interesting for me, how the program output is 5, while debugger clearly indicates the value of a is 10? This depends entirely on the compiler. It could output 10, 5, crash, ... because it is undefined behavior. If you want to know why the output of the binary created by a particular compiler has a c...
70,593,602
70,593,891
Socket recv() made my string into a char "C:\User" 'C'
Why does string a return 'C' instead of "C:\Users\Desktop\Project phoneedge\ForMark\Top"? When I tested it in a empty c++ project, and before I moved some of my code from ThreadFunction to StartButton it worked(The UI is suppose to update constantly but the socket recv() is cockblocking it causing it only update once s...
The TCP protocol passes the data by byte stream. It means the client passes the data byte by byte rather than pass all the data at one time. When you receive the data from the client. The passing procedure maybe not be finished. So you need to check whether the data is finished passing after receiving some data by one ...
70,593,668
70,593,874
Changing bool on this from inside lambda
I have a bool on a AActor, that I'd like to change from a lambda function, how shall I capture the bool so it is actually changed? I currently use [&], which should pass this by reference as I understand it, however changing the bool from inside the lambda function doesn't change it on the actor. [&] () { bMyBool = tru...
I have no idea what you have done, but your code will do what we expect by using the following environment around your single code line: int main() { bool bMyBool = false; auto l= [&] () { bMyBool = true; }; l(); std::cout << bMyBool << std::endl; } And as in your edit mentioned, you use it in a class...
70,593,988
70,594,687
mingw vs msvc on implicit conversion of string literals
I have a std::variant of different types including int32_t, int64_t, float, double, std::string and bool. When I assign a string literal (const char*, which is not present in this variant), I assumed it will be implicitly converted to std::string and it worked as I expected with MinGW (9.0.0 64-bit). But with MSVC (201...
The behavior of variant changed for this exact case in C++20. See What is the best way to disable implicit conversion from pointer types to bool when constructing an std::variant? for a longer discussion.
70,594,562
70,594,596
Why can't conversion to non-scalar types be performed if a suitable assignment operator exists?
struct Foo { int val; Foo() : val(-1) {} explicit Foo(int val_) : val(val_) {} Foo& operator=(int val_) { val = val_; return *this; } operator int () const { return val; } }; int main() { Foo foo = 1; // error Foo foo2; foo2 = 2; // works fine return 0; } error: conversion from 'i...
Unlike foo2 = 2;, Foo foo = 1; is not assignment, but initialization. Only constructors would be considered (to construct foo). The appropriate constructor Foo::Foo(int) is marked as explicit then can't be used in copy initialization like Foo foo = 1;. If you make Foo::Foo(int) non-explicit then the code would work; di...
70,594,842
70,595,459
Why does my vector store a copy of my object, and not the original value, in c++?
I have a mid-term assignment in which we conduct 3 sets of unit tests with documentation etc for a program from our course. The program I chose is a physics simulation. Within this program, there are two classes, Thing and World. I am able to independently create these objects. I tried adding the Thing object to the Wo...
Its right in the definition of void push_back (const value_type& val);... Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element. so when you call things.push_back(*thing);, you are adding a new element to the 'things' vector which is a ...
70,595,062
70,595,260
Using class type as template argument type when create class definition
I have a base class BaseCmd like: template<typename T> class BaseCmd { public: private: T m; }; and then derived class Cmd1: class Cmd1 : public BaseCmd<Cmd1::A> { public: struct A { int c, d; }; }; but I'm getting error: error: incomplete type ‘Cmd1‘ used in nested name specifier Is it even possible t...
You cannot have a member of type Cmd1::A before Cmd1 is complete. The simple fix is to define A outside of Cmd1. However, if for whatever reason you want to define A inside Cmd1 you can add a layer of indierction like this: template<typename T> class BaseCmd { public: private: T m; }; class Cmd1 { public: str...
70,595,133
70,598,756
Is there a way to call a function without adding to the call stack?
I've some goto-laden C++ code that looks like #include <stdlib.h> void test0() { int i = 0; loop: i++; if (i > 10) goto done; goto loop; done: exit(EXIT_SUCCESS); } I'd like to get rid of the gotos while (mostly) preserving the appearance of the original code; that more-or-less rules-out for, while...
My solution is to write an exec() routine that stops the recursion: template<typename Func> void exec(const Func& f) { using function_t = Func; static std::map<const function_t*, size_t> functions; const auto it = functions.find(&f); if (it == functions.end()) { functions[&f] = 1; wh...
70,595,235
70,595,523
CMake way of wildcard values on set variables
I have the next snippet on a CMake based project set(Headers ./include/MyLib/main.hpp ) set(Sources src/main.cpp ) add_library(${This} STATIC ${Headers} ${Sources}) How can I indicate to recursively include all the interface files under the: ./include/MyLib/{ /* File name here */ }.ixx and all the source f...
One solution is to replace set() by: file( GLOB_RECURSE Headers ./include/MyLib/*.ixx ) and same thing for your source files.
70,595,264
70,624,756
Measuring elapsed time, storing the start time as a primitive type
I need to measured elapsed time in ms I need to store the start time as a primitive type I need to retrieve the start time as a primitive type, when making the comparison to determine how much time has elapsed Any suggestions? I have C++17 and do not want to use any external libraries (like boost). std::chrono wou...
You can simply do this by: double time = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC; See the below code for better understanding. #include <iostream> #include <time.h> using namespace std; int main() { double start = 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC; for(int i=0;i<1e9;i++); double end...
70,596,101
70,596,287
Why is fstream put function filling 4GB of space on my drive?
For whatever reason, my program is filling up 4GB of space on my drive. Why? I narrowed it down to this for loop using breakpoints: int blockPos = 1; char blockAddressPos = 0x00; for (int d = 0; d < img.width * img.height * img.channels; d++) { tf.write(blockPos, blockAddressPos, (char)img.data[d]); //printf("B...
According to /J (Default char Type Is unsigned), by default char is signed in Visual C++. So after blockAddressPos exceeds 0x7F, it wraps around and most likely becomes negative, e.g. 0x80 = -128. When you pass this negative value to tf.write(), the line unsigned int location = (block << 8) | blockAddr; promotes block...
70,596,564
70,605,124
Why does calling methods on a protobuf Message throw a pure virtual method called error?
I'm trying to use the Google Protobuf library and I want to store a bunch of different message types together in a container and get their names as I pull them out of the container. I think I can use the interface type google::protobuf::Message to do this. Here is what I have so far. #include <iostream> #include "addre...
address_book is on the stack it will be deleted when it goes out of scope, no smart pointer can prevent that. Just create your book with std::make_shared, that will be on the heap and its lifetime will be managed from the std::shared_ptr. { auto address_book = shared_ptr<google::protobuf::Message>(new tutorial::Add...
70,596,946
70,596,987
Why does this function not print the coordinates properly?
As i said in the title im having an issue while trying to print coordinate values like this while using a std::thread #include <array> #include <thread> struct Vec2 { int x; int y; }; void dostuff2(Vec2 x) { std::cout << x.x << x.y << " "; } void dostuff(Vec2 Oven[3]) { for (int i=0; i<3; ++i) {...
The main function could end before the thread finishes, meaning the life-time of Oven ends and any references or pointers to it will become invalid. If you don't detach the thread (and instead join it) then it should work fine. Another solution is to use std::array instead, in which case the thread would have its own c...