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,459,315
70,459,344
Unpacking Vector/Set in for loop
Like in Python, we can unpack list of lists in a for loop as follows: coordinates = [[2,2], [5,99]] for x, y in coordinates: print(x+y) Is there any way to do the same with vector/set of vectors/sets in C++? Somewhat Like vector<vector<int>> coordinates {{2,3}, {5,99}}; for(auto x, y : coordinates) cout << x+y...
Yes, but not with vector<vector<int>> because the size of (the inner) vector is not known at compile time. You need std::vector<std::pair<int, int>>: std::vector<std::pair<int, int>> coordinates {{2,3}, {5,99}}; for(auto [x,y] : coordinates) cout << x+y;
70,460,571
70,460,632
Is static_assert compiled into the binary file
I'd like to use static_assert in my C++11 project to do some compile time check. As my understanding, static_assert won't be executed at runtime, right? If so, when I compile my project by executing the command about compilation, such as gcc ..., the compiler will build the static_assert into the binary file or the sta...
Is static_assert compiled into the binary file No. As my understanding, static_assert won't be executed at runtime, right? Right. the compiler will build the static_assert into the binary file No. the static_assert will be totally ignored, just like a comment? No, it's not a comment - the expression is checked,...
70,460,772
70,465,325
C++ SFML Text flickers when drawn
I have an SFML RenderWindow, and when it closes, it'll display a confirmation message. I've run into this same problem a lot of times: the confirmation message (an sf::Text) is drawn when the Event::Closed is called, but it only stays when the event is called; I think till the click on the close button is registered (c...
Keep an explicit variable with the state of the game, and change your game code based on that: enum class GameState { Playing, Closing }; GameState phase = GameState::Playing; while (app.isOpen()) { // Process events sf::Event event; while (app.pollEvent(event)) { // Close window : exit i...
70,461,138
71,200,379
Rare segmentation fault during object creation with new
In a Java application, I use JNI to call several C++ methods. One of the methods creates an object that has to persist after the method finished and that is used in other method calls. To this end, I create a pointer of the object, which I return to Java as a reference for later access (note: the Java class implements ...
After removing my std::set from the code, the error did not occur anymore. Conclusion: std::set in multithreading must be protected to avoid unrecoverable crashes.
70,461,330
70,461,663
Problem encountered while trying to create dynamic modules in omnet++
I'm a beginner and I'm learning network simulation with Omnet++. I have been trying to create dynamic modules (Clients) and connect it to a staticlly created module (Server) but I'm getting an error with the function getParentModule() saying: use of undeclared identifier 'getParentModule'. Here is my Server class: #i...
You have declared create_grp() as a standalone function so it cannot know what is getParentModule(). I recommend declaring create_grp inside your class Server. EDIT create() requires const char* as the first argument, but you provide std::string. You should use c_std() to convert std::string into const char*, for examp...
70,461,982
70,462,810
Winapi : How do I for my button send different message according to the key pressed?
I created a button, that when clicked, will open an .exe file and close the current application: HWND Button = CreateWindowEx(0, L"Button", L"Exe Application", WS_BORDER | WS_VISIBLE | WS_CHILD, 500, 500, 200, 200, hWndParent, (HMENU)BUTTON_EXE, 0, 0); And in the WindProc: switch (uMsg) { case WM_COMMAND: ...
You can check whether a key is pressed while handling WM_COMMAND messages by calling the GetKeyState function. Depending on its return value you can then implement different logic. It's important to call GetKeyState (as opposed to GetAsyncKeyState) to get the key state at the time the button was clicked.
70,462,796
70,463,362
Modules naming conflict
Is there anyway to use exported class/function without importing a module? Consider this example: System.ixx export module System; export class String {...}; System2.ixx export module System2; export class String {...}; Is there anyway to use it like System::String or System2::String? Obviously when I import both m...
Modules change how you access code from multiple files, but that's all they do. They do not (for the most part) affect the fundamental nature of C++ as a language. C++ already has a tool for managing name conflicts between disparate libraries and source locations: namespaces. As such, C++ modules have no need to solve ...
70,463,537
70,463,988
Convert tm of another timezone into tm of the GMT timezone
I'm using chrono and c++20. I have a tm struct for EST timezone, but can't figure out how to obtain the corresponding time in the GMT zone. Here is what I've been thinking: tm timeInAmerica = {0}; timeInAmerica.tm_year = 75;//1975 timeInAmerica.tm_month = 0;//January timeInAmerica.tm_mday = 31; timeInAmerica.tm_hour = ...
using namespace std::chrono; tm timeInAmerica = {0}; timeInAmerica.tm_year = 75;//1975 timeInAmerica.tm_mon = 0;//January timeInAmerica.tm_mday = 31; timeInAmerica.tm_hour = 23; timeInAmerica.tm_min = 23; timeInAmerica.tm_sec = 23; auto lt = local_days{year{timeInAmerica.tm_year+1900} /month(timeI...
70,463,661
70,463,778
Checking virtual function table using *(void**)this
The unreal engine source code has this bit in a validity check function: if (*(void**)this == nullptr) { UE_LOG(LogUObjectBase, Error, TEXT("Virtual functions table is invalid.")); return false; } In this case this being a pointer to an instanced object of a class. I understand what the conversion and derefere...
There are two separate questions here: what does this code do, and does it work? One common way that vtables are implemented is by storing a pointer to the vtable at the base of the object. So, for example, on a 32-bit machine, the first four bytes of the object would be a pointer to the vtable, and on a 64-bit machine...
70,464,155
70,574,529
Pre-schedule parallel tasks with Intel TBB
I have multiple batches processed one by one in a serial fashion and each batch's elements are computed in parallel. As I repeat this operation dozens of times, it seems to introduce an little overhead with thread sheduling. I would like to know if it's possible to set those tasks in advance and then call them during t...
For scheduling a TBB task, a rule of thumb is that a task should execute for at least 1 microsecond or 10,000 processor cycles in order to mitigate the overheads associated with task creation and scheduling. Pre-scheduling the tasks in advance will not help in overcoming the thread scheduling overhead. we are assuming ...
70,464,448
70,464,516
Libcurl - CURLMOPT_TIMERFUNCTION - what is it for?
Tell me please, i just can't figure out what the CURLMOPT_TIMERFUNCTION parameter is used for. Yes, of course I read the entire description about CURLMOPT_TIMERFUNCTION: CURLMOPT_TIMERFUNCTION timer_callback hiperfifo And I still don't understand what he does and why he is wanted. For example: Certain features, such a...
This is for curl to take action when requests were not answered in time. You need to call curl back periodically so it does its own internal housekeeping. Imagine you made a request to curl and curl took action on it but could not connect at that time. Curl cannot hang the process waiting for the connect so it returns ...
70,464,503
70,464,695
Array typedef pointer decomposition in function parameter
I have a simple array typedef typedef char myString[8]; And one function that takes a myString and another that takes a myString*. Interestingly, both of these functions have the exact same implementation and produce the exact same output: void foo(myString s){ std::string stdstr(reinterpret_cast<char*>(s), 8); ...
You introduced the alias myString for an array type typedef char myString[8]; So this function declaration void bar(myString* s){ is equivalent to the declaration void bar( char ( *s )[8] ){ If you have an array declared for example like char str[8] = "1234567"; and are calling the function bar like bar( &str ); t...
70,464,616
70,464,738
why do you add __ for inclusion guards?
#ifndef is used to tell the compiler that a given file should only be included once, as specified here: Why are #ifndef and #define used in C++ header files?. But often times, I see: #ifndef __somecode__ rather than: #ifndef somecode Is there a good reason to do this?
(prefix) __ for inclusion guards There a good reason to do this, when the code is part of the implementation's library. Using a name containing a __ is reserved for the implementation. It will not conflict with good user code. Your user code should not do this. 17.6.4.3.2 Global names [global.names] Certain sets ...
70,464,661
70,465,087
Generic object for derived classes for instantiation and returning purposes
I want to create a graph object which can switch between following different mathematical functions as I plot along it. I am currently keeping the current math function as an object inside the graph object, so it knows what to follow when I call its plotting function, and am trying to use polymorphism to describe diffe...
As @PaulMcKenzie suggested, just use polymorphism (for example, with smart pointers). That is, you manage pointers to a base class, MathExpression, and you create heap instances of the derived classes, Polynomial and Exponential (with new or make_unique or make_shared). Since you seem to be returning instances of your ...
70,466,212
70,466,480
AVX2: CountTrailingZeros on 8 bit elements in AVX register
I would like to have an implementation for a function like _mm256_lzcnt_epi8(__m256i a), where for every 8 bit element the number of trailing zeros is counted and extracted. In a previous question to implement counting leading zeros there is a solution using a lookup table. I wonder if one can use the same method for t...
The same LUT as in the answer by chtz in that question should work. Saturation trick won't work, but _mm256_blendv_epi8 can be used to select which LUT results to use. The low LUT is the answers for values 0..15, for 0 it is 0xFF to see in the other LUT via blendv. Like this (not tested): __m256i ctz_epu8(__m256i value...
70,466,219
70,466,627
Is assigning empty std::vector same as swaping for an empty std::vector?
C++ delete vector, objects, free memory states that in order to release allocated heap memory after clearing an std::vector, one can do: vector<int>().swap(myVector); That makes sense, but I wonder whether the following wouldn't achieve the same. Can someone tell me whether there's a difference? myVector = vector<int>...
In accord with the standard, assignment from a rvalue (ie: move assignment) for (non-std::array) containers is not allowed to invoke the move constructor or assignment operators of T unless the allocator for that container does not propagate on container move-assignment. This means that the only valid implementation fo...
70,466,470
70,466,640
how to sort letters followed by its position to create a word using linked list in c++
my program is for sorting a letters entered by the user and each letter is followed by its position to create a word using linked list " the word should be ended by -1 to stop insertion". my problem is when I enter the input nothing happen after that I think the problem is at the function printList(Node* head) put I ...
There are a handful of (potential) bugs in your code. Here is the first one I found: Node* newNode(char x, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = x; // OOPS, you probably mean new_node->x = x new_node->data = new_data; ne...
70,466,533
70,467,129
What exactly it means that functor in c++ have a state and other regular function doesnt have a state?
I am new to STL concepts in C++, and when I am going through a functor I have a struct, at that point the functor has a state, whereas other regular functions don't have state. What does it actually mean? So far, I saw info that says a functor has state so it can access and store the data of its class where the operato...
"State" refers to data that is remembered and carried between subsequent calls to a function or class method. Your MyFuncPtr is stateful, as it carries a data member a whose value is set in MyFuncPtr's constructor and is remembered and used through all calls to MyFuncPtr::operator(). You are setting the state once, an...
70,466,830
70,467,147
Count overlapping occurrances of substring within string
#include<iostream> using namespace std; int main () { int z=0; int count=0; int set=0; string str1="lol"; string str2; cin>>str2; for(int x=0;x<str2.size();x++) { if(str1[z]==str2[x]) { z++; count++; if(count==3) { ...
The implementation count1 below will avoid creating a std::string if you pass a char pointer or a C string. The second implementation count2 is probably yet more efficient. #include <iostream> #include <cstdint> #include<iostream> std::size_t count1( const std::string_view& needle, const std::string_view& haystack ) ...
70,467,051
70,467,201
Experiencing SIGTRAP error when executing gtest with smart pointers
I have a gtest that runs to test allocation of some attribute in one of my classes. This test executes fine when stepping through the debugger with both assertions passing. However, when the code block finishes, a segmentation error is thrown: Running main() from C:/Users/user/repos/atvalue_cpp/Google_tests/lib/src/g...
The line: auto child = std::shared_ptr<Unit>{this}; puts the object currently under construction under the ownership of a new shared pointer. However, after construction of new objects in the lines such as std::shared_ptr<Unit> child1 {new Unit(11, "Child 1", parent, 30)}; the Unit objects are again put under the own...
70,467,159
70,467,499
how do i change values of a global struct inside main/another function in c?
so i'm making a blackjack game in c for fun and to practice coding. currently the way i have it set up is instead of just making a variable for the card, since face cards have the same value and aces have two different possible values, i made a struct to store a few different parameters and a function to change said pa...
You need to pass the struct as a pointer, otherwise the function will work on a copy of the struct. Change the signature to void cleanUpCards(struct card *cardInput) { ... } and access the fields of cardInput with "->" instead of ".". Also, call it with cleanUpCards(&playerCard1); ...
70,467,646
70,467,701
Why can I declare a float in a header file, but not a custom struct type?
Why can I declare a float like: Player.h (compiles) #include "Component.h" #include "Vector2.h" class Player : public Component { public: float positionX; float positionY; }; but can't declare a my Vector2 struct like: Player.h (does not compile) #pragma once #include "Component.h" #include "Vector2.h" ...
If your Vector2 doesn't have a parameter-less constructor, C++ won't know how to construct it. You need to declare how to construct your Vector2 in the Player constructor using parameter initialization, like so: Player::Player() : position(0,0) { // player initialization here } Another option is to store an std::u...
70,467,700
70,468,595
What is LeastMaxValue in std::counting_semaphore<LeastMaxValue>?
Is it the max allowed value of the inner counter? But how is it possible to talk about minimum max value? Shouldn't max value be const? How can it be changed? What is difference between LeastMaxValue and counter? As its name indicates, the LeastMaxValue is the minimum max value, not the actual max value. Thus max() ca...
Shouldn't max value be const? Yes. In fact, counting_semaphore<LeastMaxValue>::max() is required to be constexpr, meaning that it is not just constant, but a compile-time constant. For a given LeastMaxValue, the max can vary from compilation to compilation, but no more than that. Perhaps that's the source of your con...
70,467,957
70,468,041
Multithreading and sequence of instructions
While learning multithread programming I've written the following code. #include <thread> #include <iostream> #include <cassert> void check() { int a = 0; int b = 0; { std::jthread t2([&](){ int i = 0; while (a >= b) { ++i; } std::cout...
Since ++a always happens before ++b a should be always greater or equal to b Only in its execution thread. And only if that's observable by the execution thread. C++ requires certain explicit "synchronization" in order for changes made by one execution thread be visible by other execution threads. ++a; ++b;...
70,468,292
70,468,329
no match for 'operator*' in C++
I'm overloading operator * and + to read some class' variables from files. I have written the following code: class X { public: double getLength(void) { return length; } void setLength( double len ) { length = len; } // Overload + operator to add two Box ...
The error means what it says: There is no operator* for int * X and no operator+ for X + int. You only have overloaded operators for X * int, X * X and X + X. You can add a converting constructor and make the operators free functions, then implicit conversions work on both operands (note that the getter should be const...
70,468,317
70,468,466
Template function cannot recognize lambda referred by an auto variable
In c++17, I have a template function which takes some kind of lambda as input. However it only recognizes those with explicit types and ones using auto are rejected. Why this is the case and any way to combine auto variables and template function taking lambda with specified form as input? #include <iostream> #include ...
There are actually two fundamental issues here which cause the deduction to fail: The first is that the type of a lambda expression is never std::function<Signature> for any signature Signature. However, your function expects a non-const reference argument. As the types differ a conversion is needed which would be a t...
70,468,654
70,468,799
How to fix Segmentation Fault (core dumped) error when using sprintf for system commands in C++
I am experimenting with using system commands in C++, and I am trying to make a pinger. Below is my script: #include <stdlib.h> #include <iostream> #include <stdio.h> using namespace std; int main() { char ip; char *cmd; cout << "Input IP: "; cin >> ip; sprintf(cmd, "ping %s", ip); system(cmd); return 0; } The code ...
I strongly suggest to not mix C and C++ when not needed. That means, use the C++ versions of the C headers and only use the C headers when you need to. In C++ there is std::string which can be concatenated via +. In your code ip is a single character and cmd is just a pointer. You fail to make it point to some allocate...
70,468,766
70,468,843
Can you interleave variadic parameters in call sites?
Is it possible to interleave template parameters inside of function call sites? I effectively want to do implement the following, but I don't know how (psuedo code): template <size_t... indices, typename... Ts> void foo(const Things *things) { static_assert(sizeof...(indices) == sizeof...(Ts)); constexpr n = si...
Like this: template <size_t... indices, typename... Ts> void foo(const Things *things) { std::apply([](auto...args) { bar(args...); }, std::tuple_cat(std::make_tuple(indices, parse<Ts>(*(things++)))...)); } If bar is a lambda instead of a function template, you can just pass bar directly as the first a...
70,468,791
70,468,934
Why a O(logn) slower than O(n) function?
I met a strange issue when I solve codechef problem Lowest Sum. There is area of codes to calculate the numbers of pair(i,j) which sum(a[i]+a[j])<X, the idea is to enumerate each a[i], accumulate the numbers which smaller than X-a[i] in vector b. there are two ways to find the number smaller than X-a[i] in vector b: O...
The "code for reference" initializes j only once outside the i loop. Thus, if uncommented, the "O(n)" version actually looks like: int j=K-1; // <----------- HERE for(int i=0; i<K&&mid-a[i]>=b[0]; i++) { //int j=K-1; // <----------- NOT HERE while(j>=0 && mid-a[i]<b[j]) { --j; } ...
70,469,031
70,469,090
Difference between pointer call and refrence call
I was randomly playing with pointers and refrences. class Product { int price,qty; public: void setData(int price, int qty) { this->price = price; (*this).qty = qty; } void billing() { cout << price * qty; } }; int main() { Product *PenObj; (*PenObj).setData...
Product *PenObj; simply declares a pointer, but it doesn't point anywhere meaningful. You are calling setData() and billing() on an invalid Product object, which is undefined behavior. You need to create the object, eg: int main() { Product *PenObj = new Product; (*PenObj).setData(50,25); // or: PenObj->setDat...
70,469,129
70,469,215
how to put files and exported functions in one dll?
for some reason, I needed to put a file in a DLL. I knew I could put it in a pure resource DLL, but I didn't want anyone else to know how to read the file。 So I want to be able to put this file in a DLL along with the functions on how to read the file. Does anyone know how to do that ? Thanks
Here is one idea that works for both text and binary files alike. Store the file as base64 encoded with $ cat file.txt Hello World Hello World Hello World Hello World Hello World Hello World $ cat file.txt | base64 > base64.txt $ cat base64.txt SGVsbG8gV29ybGQKSGVsbG8gV29ybGQKSGVsbG8gV29ybGQKSGVsbG8gV29ybGQKSGVsbG8gV...
70,469,290
70,469,490
Converting HTML resource to string in MFC
I get jargons while converting HTML resource to CString in an MFC application. Any help will be appreciated. I am compiling on VC++ 2022, obviously with unicode. CString GetHTML(const int& RESOURCE_ID) { CString str; HRSRC hrsrc = FindResource(NULL, MAKEINTRESOURCE(RESOURCE_ID), RT_HTML); if (hrsrc != NULL)...
My psychic powers suggest that the your HTML resource file is ascii, but you are casting the ascii bytes returned by LockResource to be a unicode string LPCTSTR (pointer to TCHAR). Simplest approach would be to have your function return a CStringA instead of a CStringW and do all your processing on the string as ascii....
70,469,428
70,469,585
avoiding code duplication in different classes where the function does the same in C++
I'm kinda new to OOP so this question feels a bit weird but I want to know what I should do in this case Say I have a Tup4 class which just holds 4 doubles, and two classes Point4 and Vec4 that extend Tup4. Now, checking for equality in Tup4 is just comparing whether all 4 doubles in each tuple are (approximately) equa...
Tup4 is a concept not a class. Vec4 snd Point4 satisfy that concept. Most of Vec4 and Point4 are implemented as templates. In the rare case you need to handle Tup4s in runtime polymophic way, don't use inheritance, use type erasure like std function. But you probably won't. struct Tup4Data{ double v[4]; }; template...
70,469,462
70,472,240
WSL Ubuntu 20.04.3 error: XDG_RUNTIME_DIR not set in the environment
I use Ubuntu 20.04.3 WSL on Windows 10. I compiled my c++ program (which uses the SDL2 library) into an executable file named "main". g++ -o main main.cpp CApp.cpp -lSDL2 -std=c++17 When I try to run the executable with the following command: ./main it returned: error: XDG_RUNTIME_DIR not set in the environment.
Thanks for the comments. The answer is already answered here: QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-aadithyasb' As for why the executable cannot be run in WSL, the reason is because WSL2 (as of December 2021) has not yet supported GUI app. It is only available on Windows 11 Insider. Here ...
70,470,207
70,470,543
error: passing ‘const std::unordered_map<char, int>’ as ‘this’ argument discards qualifiers
I am struggling with understanding why auto p in the following code snippet is const type, which prevents the query cnt_w[p.first]. I understand the error msg error: no viable overloaded operator[] for type 'const std::unordered_map<char,intmstd::hash<char>, because in c++,when the key is not existed in the unordered_m...
You're doing wrong in the first case. You should use [&cnt_w = cnt_w] or just [&cnt_w]. cnt_w here is non-const. What you're doing is getting the address of cnt_w
70,470,598
70,470,668
in c++ how to loop an array in return statement
public async Task < IActionResult > Events( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest httpRequest, ILogger log) { ValidateResponse res = eventService.ValidateSchema(); if (res.Valid == false && res.Errors != null) { string[] messages = new ...
Once option is to join the messages array to a string: return new OkObjectResult($"No of events posted {cloudEvents.Count} and errors:{String.join(\",\", messages}");
70,471,187
70,471,258
Create a 2D array using vector (C++) from a set of available points
I have a set of points generated using the function linspace (similar to the one in MATLAB): vector<double> x_coord = linspace(-5,5,11); // Output = -5 -4 -3 -2 -1 0 1 2 3 4 5 vector<double> y_coord = linspace(-5,5,11); // Output = -5 -4 -3 -2 -1 0 1 2 3 4 5 vector<vector<double>> coord( x_coord.size() , vector<doub...
Just keep it simple, use push_back and a range-for loop: vector<vector<double>> coord; coord.reserve(x_coord.size() * y_coord.size()); for(auto x : x_coord){ for(auto y : y_coord){ coord.push_back({x,y,0}); } }
70,471,311
70,471,327
Can't fix this error when running my code
I get this error when I'm trying to run my code: "error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive] 9 | int *a = GC::allocate(sizeof(int));" I am trying to make a function that acts as a garbage collector and right now am first trying to make the dynamical allocation for pointers (since the pointers a...
You could explicitly cast the return value: int *a = (int*) GC::allocate(sizeof(int));
70,471,628
70,471,737
Should I move on return when variables are not local
A have a few questions regarding copy elision and move. Let's assume I have the following code: class A {}; class B { public: A get1() const { A local_var; return local_var; } A get1bad() const { A local_var; return std::move(local_var); } A get2() const { re...
I read a lot of people saying to not do move on return. From what I gather it's because with copy elision, on case get1, the compiler will not call constructor + move constructor but rather just one call to the default constructor, while case get1bad forces the compiler to call constructor + move. If the operand to a...
70,471,920
70,471,969
Why primitive to class type conversion destroys object values?
Why in the below code when I set c1 = 10 destroys all other values of variables (a, b, c) of the object. The statement should call the constructor and as the constructor is defined it sets the values of a to 10, but when I try to access values of b and c; it is giving me garbage values. #include<iostream> using namespa...
This is equivalent to c1 = abc(10); The constructor abc(int k) doesn't initialize values b and c, therefore the member variables contain some random values. These random values, from the temporary abc(10) object, are then copied to c1. The same is true for constructor abc(), here neither member variable is initialize...
70,472,515
70,473,252
Simple boost program with nvcc - error: declaration does not declare anything [-fpermissive]
Background I want to use boost library to serialize some objects in cuda. I have a bigger Makefile with nvcc compiling about 20 files. I hope to write the smallest working example of Makefile with boost library and then add it to my larger makefile Boost library localization Makefile LIBS=--relocatable-device-code=tru...
You have not given your variable a name. Try changing it to: boost::optional<string> exampleName;
70,472,526
70,472,542
Is it possible to inherit from a template base class with virtual function overriding with template argument?
When I use class Derived: public Base<int*>, I thought the Base class template is a member function like virtual void foo(const int* a) {} because of explicit instantiation during compilation. However, If I write like this, it never shows "Derived class". What's happening? #include <iostream> using namespace std; temp...
Note that for const T, const is qualified on T itself. Then given T is int*, the parameter type of Base<T>::foo, i.e. const T would be int * const (const pointer to non-const int), but not const int * (non-const pointer to const int). You should change Derived::foo to virtual void foo(int* const a) { cout << "Deriv...
70,472,553
70,472,662
Stateful C++ Input Iterators post increment problem
I was implementing an iterator that takes another float values producing input iterator and returns true if a rising was detected. So, the iterator works effectively as a Software-ADC (Analog-Digital-Converter). I've minimized the actual code to the following: #include <iterator> template<typename It> struct ADCFilter ...
This can be done by reimplementing the operator so that its internal data holds just the bool value, instead of the floating point value from which the bool value is derived only when the iterator gets dereferenced. In other words, the dereferencing iterator should simply be: bool operator*() const // It should be cons...
70,472,760
70,472,806
Phone contact list with Qt
I just started learning Qt and would like to try creating phone contact list. Through I couldn't find from where to start. I would be glad for any suggestions.
For a phone contact list I suggest looking at QListWidget. It has functions to insert/remove items and you can get signals when items are altered or when a new item is clicked.
70,473,909
70,473,986
C++ error: no match for 'operator[]' (operand types are 'const my_array_over' and 'size_t' {aka 'long unsigned int'})
#include <iostream> using namespace std; class my_array_over { size_t len = 1; int *a = new int[1]; public: my_array_over() { a[0] = 0; } my_array_over(size_t ln, const int *o) : len(ln), a(new int[ln]) { for (size_t n = 0; n < ln; ++n) a[n] = o[n]; } ~my_array_over() { delete[] a; } ...
In this statement std::cout << a2[i] << std::endl; there is used the subscript operator for an object of the type my_array_over that (the subscript operator) is not defined within the class. It seems you mean std::cout << a2.get( i ) << std::endl; Otherwise you need to define the subscript operator within the class d...
70,474,035
70,474,378
Can std::atomic_flag be safely destroyed after calling notify_all?
In my code, I want to use a std::atomic_flag to synchronize two threads. Specifically, I would like to use the new wait and notify_all features that are introduced in C++20. In a nutshell: one thread is waiting for the flag to become ready while another thread will set the flag and issue the notification. The catch, ho...
No, it is not safe. From the standard In the standard ([atomics.flag]), the effects of atomic_flag_wait are described as follows: Effects: Repeatedly performs the following steps, in order: Evaluates flag->test(order) != old. If the result of that evaluation is true, returns. Blocks until it is unblocked by an atomic...
70,474,090
70,474,722
read write various data types on special files
I have hard time understanding how read and write to non-regular files ( such as stdin/out, socket, device ) work. I have following client/server program. client #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include ...
int sendBuff[] = {0x27, 0x3f, 0x5a }; on your platform int is 4 bytes and if it was little endian would look like this in memory: hex: 27 00 00 00 3f 00 00 00 5a 00 00 00 The first four bytes, the equivalent of your int, is 27 00 00 00 so when your server attempts to write as in : write(connfd, sendBuff, 3); It will ...
70,474,367
70,474,541
Get the interface to be used by socket according to IP on Linux, with C/C++
According to this answer, the interface to be used by a socket will be selected automatically by the system if the destination address is specified when calling connect. What I am looking for is a simple way to know the name of that interface before calling connect with C or C++. I know this can be done with the comman...
You can open a netlink socket and query the routes then filter the one you need. Here is an article on Linux Journal that describes this method: https://www.linuxjournal.com/article/7356 And here is an implementation in C of it: https://gist.github.com/javiermon/6272065 It just needs a bit of adjustment for your needs...
70,474,530
70,474,633
About std::function usage and if-else problem
as the below code, I don't want so many "if else" class A { public: void f0() { cout << "f0" << endl; } void f1() { cout << "f1" << endl; } void f2() { cout << "f2" << endl; } //..... more functions fn()... }; class B { public: void f(int n) {...
You can use std::function with a lambda wrapper, vector<function<void()>> f_v {[this]() { obj_a.f0(); }, [this]() { obj_a.f1(); }, [this]() { obj_a.f2(); }}; f_v[n](); or use pointer-to-members directly, vector<void (A::*)()> f_v { &A::f0, &A::f1, &A::f2 };...
70,474,834
70,476,967
I can't load my game resources into SFML with CMake
I am programming a little game in C ++ using Visual Studio Code with CMake as the Build System. So far there hadn't been any problem with accessing resources, but since I decided to tidy up my project by organizing it in directories, my GetTexture, GetSoundBuffer and GetFont functions are unable to load images from the...
When you run an executable in another location, the relative path will be different from what it was during compilation. One solution is to make everything relative to the executable's location as in: namespace fs = std::filesystem; int main( int argc, char* argv[] ) { fs::path path( fs::canonical( argv[0] ) ); ...
70,475,117
70,475,234
The while loop should end after reading the third line in my file but why does it run the fourth time?
void Load_from_file() { ifstream fin("Data.txt"); //fin.open("Data.txt"); if (!fin.is_open()) cout << "Error while opening the file" << endl; else { int f_id; int u_id; int priority; char acc_type; char d...
The problem is the condition in the while statement while (!fin.eof()) { fin >> f_id; fin >> delim; // skipping the comma fin >> u_id; fin >> delim; fin >> priority; fin >> delim; fin >> acc_type; } ...
70,475,509
70,475,618
Linked List Implementation is crashing
I am trying to implement Linked List in C++, when I use the new operator to create the Linked List object (e.g. LinkedList *Head = new LinkedList; etc.) the linked list works fine. But if I use normal pointer object declaration (e.g. LinkedList *Head, *node1, *node2, *node3, *node4;) the program crashes. Could any one ...
LinkedList *Head, *node1, *node2, *node3, *node4; Merely declaring a pointer in C++ does not mean it points to anything. You need to initialize these so they point to a valid address in memory. Typically this would either be with new or by statically allocating them, and then taking the address of those when you need ...
70,475,588
70,475,713
Why does chrono::system_clock returns microseconds whereas clock_gettime returns nanoseconds
std::chrono::system_clock::time_since_epoch().count() gives me a result in microseconds. I want the current time in nanoseconds. But I can't use high_resolution_clock because on my system it is an alias on steady_clock (the monotonic clock). I know my system is nanoseconds capable, because if I use clock_gettime(CLOCK_...
I am getting a correct nanosecond-resolution epoch time. Are you? clock_gettime is required to return a time in nanoseconds, regardless of what clock you're accessing. This doesn't mean that CLOCK_REALTIME actually provides this resolution. It may internally only have microsecond resolution and expresses nanoseconds ...
70,475,637
70,476,433
Storing end pointer to uninitialized array in constexpr context
I'm trying to create a constexpr friendly small buffer optimized vector type that stores a begin, end and capacity pointer as usual, but when it is default constructed the begin and capacity pointer point towards local memory before reallocating to heap when required. However I cannot figure out how to store the capaci...
There are multiple problems with your code: T* is not a valid iterator for your representation, as the Ts are actually a member of a structure. The iterator needs to operate on the array's value type. Using storage[N] is an out of bounds access, even if you just try to use the address of the member within. One way fi...
70,475,976
70,476,311
Redirect data from multiple streams to a single stream while keeping original data
To put it simply, I'm trying to create one stream that links to a file std::ofstream outFile{pathToFile, std::ios_base::app};. This file is a log file that, ideally, would receive copies of both stderr and stdout. When an error would occur, for example, the error would be printed in the console and in the file. I've tr...
The IOStreams internally use a std::streambuf to actually write (or read) characters. If you just want to redirect all characters written to another stream, you can just redirect the respective stream buffer. You should restore the original stream buffer eventually, though, as the streams are flushed on destruction and...
70,476,093
70,476,467
Using the ROOT framework to plot a mathematical function in C++
I'm trying to plot a function graph using the "ROOT" data analysis framework with C++. I've tried to use this code (found in a user guide on the web): Int_t n = 20; Double_t x[n], y[n]; for (Int_t i=0;i<n;i++) { x[i] = i*0.1; y[i] = 10*sin(x[i]+0.2); } // create graph TGraph *gr = new TG...
Did you follow the steps here, https://root.cern/primer/?#interpretation-and-compilation ? Here is a working example. demo.cpp #include <TApplication.h> #include <TGraph.h> void guiDemo() { Int_t n = 20; Double_t x[n], y[n]; for (Int_t i=0;i<n;i++) { x[i] = i*0.1; y[i] = 10*sin(x[i]+0.2); } ...
70,476,898
70,476,950
"Undeclared identifier" when trying to define function template
I want to define a function that decides whether two arrays of doubles are (approximately) equal. Here's my code: Comparisons.h : #pragma once #include <array> const double EPSILON = 0.0001; bool areFuzzyEqual(const double& d1, const double& d2); template<int n> bool fuzzyEquality((const std::array<double, n>)& a1,...
Just rewrite this line bool fuzzyEquality((const std::array<double, n>)& a1, (const std::array<double, n>)&a2) as bool fuzzyEquality(const std::array<double, n>& a1, const std::array<double, n>& a2) and you should be good.
70,476,960
70,477,124
Different implementation in JPEG library (C-Lang)
Please refer to the attached screenshot of two different implementations of a JPEG library file (linux/windows). Filename is /libijg12/jcarith.c One of them has an extra macro, both have the same function name. My question is: Does the first version is overridden by the second one?
In the one in the right (Windows) the top one is just a declaration or prototype, it does not include the body of the function. Declarations come usually in headers. In this case, it's unusual that the author put the declaration together with the definition of the function. The opposite is more common - to place the bo...
70,477,099
70,477,136
Concisely declare and initialize a multi-dimensional array in C++
For example in 3 dimensions, I would normally do something like vector<vector<vector<T>>> v(x, vector<vector<T>>(y, vector<T>(z, val))); However this gets tedious for complex types and in large dimensions. Is it possible to define a type, say, tensor, whose usage would be like so: tensor<T> t(x, y, z, val1); t[i][j][k...
It's possible with template metaprogramming. Define a vector NVector template<int D, typename T> struct NVector : public vector<NVector<D - 1, T>> { template<typename... Args> NVector(int n = 0, Args... args) : vector<NVector<D - 1, T>>(n, NVector<D - 1, T>(args...)) { } }; template<typename T> struct NVec...
70,477,637
70,477,962
Convert borrowed_iterator<reverse_view<T>> to borrowed_iterator<T>
I have buffer: char line[1024] which contains a line read from a file. I want to find the last new-line (\n) in it, then replace all , with (space) before it. The code I came up with: const auto end = rng::find(line | rng::views::reverse, '\n'); // Find last occurrence of `\n` rng::replace(line, end, ',', ' '); // Re...
while end is a borrowed_iterator<reverse_view<T>>. In fact, the type of end is just std::reverse_iterator<char*>, you can use base() to get the underlying base iterator: rng::replace(line, end.base(), ',', ' '); Demo.
70,477,663
70,477,712
Why is ^[[A printing and need of pressing enter?
#include <iostream> int main() { bool con = true; while (con) { if (getchar() == '\033') { getchar(); switch(getchar()) { case 'A': std::cout << "Up arrow" << std::endl; break; case 'B': ...
This is just how terminal input works on most operating systems. It is the operating system itself that handles keyboard input, and collects typed input into an internal buffer; the backspace key, and perhaps other special keys, provide the means for editing partially-entered text. Only the Enter key results in the app...
70,477,737
70,477,763
For Loop Misbehavior in C++ and Qt 6.2
First of all i'm a complete beginner in C++ and Qt and i'm using Qt 6.2 and C++11. This is the code that i have problem with: QSet<QList<QString>> listSet; for(int i = 0; i < 10; i++) { QList<QString> myList; for(int r = 0; r < 10; r++) { myList << "Item" + QString::number(r); } listSet.inse...
QSet is a collection of unique objects. The first code snipped produces 10 equal to each other myList objects. Thus, QSet gets only one unique myList object: qInfo() << listSet.count(); outputs 1. The second snippet makes not equal myList objects, they differ by the first list items, and qInfo() << listSet.count(); out...
70,478,014
70,478,184
c++ clang-tidy gives errors related to llvm-libc
I have been having trouble getting clang-tidy to work on my local computer. My code is filled with these three errors: error: declaration must be declared within the '__llvm_libc' namespace [llvmlibc-implementation-in-namespace,-warnings-as-errors] error: 'connect2AtLevel' must resolve to a function declared within the...
clang-tidy is composed of several modules that can be activated or deactivated in several ways. You might use all of them, none of them or some of them. This is the current list of checks: Name prefix Description abseil- Checks related to Abseil library. altera- Checks related to OpenCL programming for FPGA...
70,478,192
70,478,587
Arduino: PROGMEM malloc() issue causing exception
I am trying to dynamically allocate memory for a char pointer stored in the flash memory. I need to read a file from flash memory using LittleFS file system and copy it to a character array which also needs to be stored in the flash memory using PROGMEM. I cannot store it in the RAM because of limited space. Also I can...
PROGMEM is processed by the linker at build time. Linker positions the array into flash memory address space. Only constants can use the PROGMEM directive. malloc allocates heap memory which is an address range in the dynamic RAM. It is possible to write to flash at runtime like the LittleFS library does, but that is n...
70,478,438
70,478,472
The output of the recursive function is coming out to be wrong , i cant find any mistake in the code
The purpose of the function is to find the numbers in a given array can form the given sum or not. It can use the numbers in the array as many times as required to get the sum. Can anyone find the the flaw in the logic. I am using recursion to solve the problem #include <bits/stdc++.h> using namespace std; bool finds...
You have a semicolon after the if statement. That signifies the end of the if statement. if (findsum(rem,arr) == true); { return true; } The code above returns true regardless of the value of the condition. This mistake is common enough that modern compilers will warn you if you turn warnings on, which you should....
70,478,554
70,478,745
OpenGL, GLFW, GLM: Camera Translates x Units to the Right, but Everything also Moves x Units to the Right with It
I am developing a game engine. Currently I am working on the camera system. When I translate it Time::getMainLoopDeltaTime() units to the right, everything in the scene moves to the right along with it when everything should look like it is moving left. I cannot figure out what I am doing wrong. These are the technolog...
Apparently, what I thought was wrong was actually right, but and incomplete implementation of the camera system. Translating the camera/gameObject matrix to the right will also move everything to the right. To solve this, we can negate the position of a copy of the transformation matrix every time we need to use it to ...
70,478,765
70,497,805
Why is C++ function's inputs become outputs in the blueprint?
I have a blueprint function library "TextManager", and it has a test_function "Test". Function's declaration is: UFUNCTION(BlueprintCallable, Category = "Custom", meta = (Keywords = "testfunction")) static void TestFunc(FString & InString, int & InInt); and definition: void UTextFileManager::TestFunc(FString &...
In C++ (both in Unreal and other use cases), using reference-type parameters is common approach when you want multiple "output" values from a function, and can't use a single return type. For example: void Main() { int MyNumber, MyNumber2; SetTwoNumbersTo1(MyNumber, MyNumber2); } void SetTwoNumbersTo1(int& FirstOut,...
70,479,001
70,479,056
Reverse of array in c++
int main() { int num[5]; int num2[5]; int n; int j = 0; cout << "provide size of array" << endl; cin >> n; for(int i =0; i< n; i++){ cin >> num[i]; } cout << "the size of n is " << n << endl; while(n != 0){ num2[j] = num[n-1]; n--; j++; } f...
If you cannot use swap, you could use addition and subtraction instead #include <array> #include <iostream> void reverse( int* arr, unsigned n ) { if ( n==0 ) return; unsigned i=0; unsigned j=n-1; for ( ; i<j; i++,j-- ) { arr[i] = arr[i] + arr[j]; arr[j] = arr[i] - arr[j]; arr[i...
70,479,032
70,480,749
Why does std::totally_ordered<float> return true?
The cpp reference (https://en.cppreference.com/w/cpp/concepts/totally_ordered) says std::totally_ordered<T> is modeled only if, given lvalues a, b and c of type const std::remove_reference_t<T>: Exactly one of bool(a < b), bool(a > b) and bool(a == b) is true; If bool(a < b) and bool(b < c) are both true, then bool(a ...
Concepts have syntactic requirements, that some set of expressions exist and are of a type that provides certain behavior. The concept feature of C++20 can detect these. Concepts also have semantic requirements, requirements about the meaning of expressions, possibly relative to one another. The concept feature cannot ...
70,479,055
70,479,078
std::set iterating over all pairs
Consider code snippet 1: #include <set> #include <cstdio> int main() { std::set<int> intset = {1, 2, 3, 4, 5, 6}; for(std::set<int>::iterator it1 = intset.begin(); it1 != intset.end(); it1++) for(std::set<int>::iterator it2 = it1 + 1; it2 != intset.end(); it2++) printf("Pair {%d,%d}\n", *it1,...
it1 + 1 is a random access operation, so it requires the iterator to be a random access iterator, and since std::set<int>::iterator is not a random access iterator, it does not support this operation. ++it2 requires that the iterator is a forward iterator, and since std::set<int>::iterator is a bidirectional iterator, ...
70,479,182
70,483,931
Cast two pointers to a pointer of std::pair like struct
I have the following simple struct that resembles std::pair. I want to cast two pointers keys and Values to a pointer of the pair. How can I do this? Thanks! K* keys; V* Values; /* length of keys = length of Values goal: operation(keys, Values) ---> pair* */ template <typename K, typename V, K EmptyKey = K(-1)> struc...
You have to copy the keys and values into the pairs. template <typename K, typename V> pair<K, V>* KVToPairs(const K* k, const V* v, unsigned int length) { if (!k || !v) { return nullptr; } pair<K, V>* pairs = new pair<K, V>[length]; for (unsigned int i = 0; i < length; ++i) { pairs[i]....
70,479,325
70,479,405
return value Vs reference (in assembly)
After taking a look at a few questions (and answers) regarding this topic, I tried the below simple code in Compiler Explorer. #include <iostream> class TwoInts { public: TwoInts( ) = default; const int& getAByRef( ) const; int getAByVal( ) const; private: int a; int b; }; const int& TwoInts::...
Each member function gets this pointer as an implicit first function argument, as dictated by Itanium ABI (not to be confused with Itanium architecture) used by GCC. this is passed in the rdi register and a value is returned (if it's trivial, and here it is) in the rax (eax) register according to x86-64 System V ABI (s...
70,479,363
70,483,132
QVM - user-defined quaternion and scalar
I am trying use boost::qvm with boost::multiprecision. I built a user-defined quaternion, but I am not able to scale the quaternion. I would like to scale it by a number of type boost::multiprecision::cpp_dec_float_100. Bellow is my code. I also tried it with the out commented code. #include <bits/stdc++.h> #include <b...
The QVM defined operators do not get found with ADL, you need to help the compiler: using boost::qvm::operator*=; q *= x; You can make ADL work, probably in various ways. One way would to make boost::qvm an associated namespace for your type(s). Another would be to using the appropriate operators in your own namespace...
70,479,776
70,479,822
How to resolve the return type of a forwarding reference?
There is an existing expected<T,E> class which provides these typedefs and operators: value_type = T operator *(): expected<T,E>& -> value_type& const expected<T,E>& -> const value_type& expected<T,E>&& -> value_type&& const expected<T,E>&& -> const value_type&& Now I'm writin...
You can use decltype(auto) as the return type: #include <utility> template<typename E> decltype(auto) Unwrap(E&& e) { return e.has_value() ? *std::forward<E>(e) : throw e.error(); }
70,479,780
70,479,830
Misunderstanding of the structure С++
I apologize in advance for the question if it seems too "childish", but the question is: Here is such a simple code: #include <iostream> struct my_struct { struct fictitious_name fn_struct; }; int main() { } It is not compiled because the fictitious_name structure is not defined. But then if I rewrite it th...
This declaration struct fictitious_name fn_struct; introduces incomplete type struct fictitious_name. That is the size of an object of this type is unknown. As a result the compiler does not know how much memory to reserve for the object fn_struct. In this declaration struct fictitious_name* fn_struct; there is also ...
70,479,851
70,479,937
Priority Queue not printing the values pushed into it
I just started Data Structures and i have stumbled upon Priority queues, I wrote a simple program to print the values that i have pushed in the Queues but it wont print anything. #include<iostream> #include <queue> using namespace std; int main(){ priority_queue<int> maxi; priority_queue<int, vector<int>, gre...
You are getting the size of maxi and mini before adding elements to them. Since you're copying the value of the size (explained here), it wouldn't be updated when adding elements to the containers. Therefore your loop is not executed at all.
70,480,042
70,480,457
filtered INDEX on Sql Server table causes errors during Insert
I have a table in SQL Server 2019 which defined like this: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING OFF GO CREATE TABLE [dbo].[productionLog2]( [id] [int] IDENTITY(1,1) NOT NULL, [itemID] [binary](10) NOT NULL, [version] [int] NOT NULL, CONSTRAINT [PK_productionLog2] PRIMARY KEY...
The required session SET options for filtered indexes are listed in the CREATE INEX documentation: +-------------------------+----------------+----------------------+-------------------------------+--------------------------+ | SET options | Required value | Default server value | Default OLE DB and ODBC va...
70,480,115
70,480,116
How do I disable suggestions when I type '#'
When I type '#' vscode suggests "#pragma region" and "#pragma endregion". I never use those snippets and the suggestions can be quite annoying especially if I intend to navigate using arrow keys after typing '#'. I figured out that the suggestions come from snippets in the built-in extension "C/C++ Language Basics". Di...
Individual snippets may be disabled by opening the command palette (ctrl+shift+p), typing "insert snippet", pressing enter, and clicking with the mouse on the pictogram of an eye with a line over it thus removing the line. I don't know how to do the last part without a mouse. If you know please comment.
70,480,118
70,480,152
std::move Bug Spotted in C++ Primer 5th Edition
I looked at an example in C++ Primer explaining std::move. The example is as follows: int &&rr1 = 42; int &&rr3 = std::move(rr1); In the explanation of the above code snippet, it is written that: Calling move tells the compiler that we have an lvalue that we want to treat as if it were an rvalue. It is essential to r...
Both cases are safe because no move operation (move construction or move assignment) happens. For example, in auto&& str2 = std::move(str);, std::move(str) just produces an xvalue (rvalue) and then it's bound to the reference str2. In particular, std::move produces an xvalue expression that identifies its argument t. ...
70,480,180
70,489,808
How to correctly implement a function that will generate pseudo-random integers with C++20
I want to note that in C++ the generation of pseudo random numbers is overcomplicated. If you remember about old languages like Pascal, then they had the function Random(n), where n is integer and the generation range is from 0 to n-1. Now, going back to modern C++, I want to get a similar interface, but with a functio...
IMO, for most simple programs such as games, graphics, and Monte Carlo simulations, the API you actually want is static xoshiro256ss g; // Generate a random number between 0 and n-1. // For example, randint0(2) flips a coin; randint0(6) rolls a die. int randint0(int n) { return g() % n; } // This version is usefu...
70,480,903
70,485,335
How do I optimize serial communication for large data strings?
I'm working with an Arduino Uno and WS2812b LED stripes. What I'm trying to do: So I've a 12 x 10 grid of LEDs and I've made a software that maps these LEDs to a texture of the same size, which I can draw to. I now want to make multiple textures and send them one by one to the arduino to create something like an animat...
RGB has 3 bytes and addressing a single led of 120 takes 1 byte. Why you believe that it takes 12 byte instead of 4? Maybe you have to add some internal index to real address translation. And if you send always all pixels, there is no need to send the address at all. Makes 360 bytes + some start sync which can be a "br...
70,480,981
70,546,673
How to insert a dynamic multidimensional QComboBox into a LayOut
I'm trying to insert multiple QComboBoxes from a dynamic multidimensional QComboBox like : QComboBox **test = new QComboBox *[x]; test[x] = new QComboBox [y]; ui->QVBoxLayout->addWidget(test["one of x values"]["one of y values"]); But this gives me an error of : no viable convert from QComboBox to *QWidget. Using : ...
combobox1[currentTable] = new QComboBox [fieldAmount]; for(int tmp = 0; fieldAmount > tmp; tmp++){ ui->verticalLayout_2->addWidget(&combobox1[currentTable][tmp]); } where fieldAmount is int fieldAmount = (SQLDataBaseContet->record()).count()-1; // -1 as offset because of id
70,480,984
70,481,297
QOpenGLWidget linker error with QT example code
after several failed attempts to create a QOpenGLWidget.I tried to run the QT example code https://code.qt.io/cgit/qt/qtbase.git/tree/examples/opengl/2dpainting?h=5.15 But that does not work too. I get the same vtable error as in the previous attempts. Here is the complete error code. I already reinstalled QT and adde...
If you use Qt6, then you need to link against openglwidgets. See https://doc.qt.io/qt-6/qopenglwidget.html
70,481,071
70,481,153
is There some function that make a conversion from string to array in C++
string x = "Banana"; How do I convert it to a char like this: char x[]={'B', 'a', 'n', 'a', 'n', 'a'};
You can follow this way in c++ to convert a string into array of characters. #include <iostream> #include <cstring> using namespace std; int main() { // assigning value to string s string s = "Banana"; int n = s.length(); // declaring character array char char_array[n + 1]; // copying t...
70,481,141
70,481,206
"identifier "hInstance" is undefined" and "too few arguments in function call"
I'm trying to make a window with C++, but it's giving me this error. m_hWnd = CreateWindowEx( 0, CLASS_NAME, L"Window", style, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, hInstance, // first error line is here ...
The function expects 12 arguments instead of 11. It seems you forgot to specify the argument rect.left, paired with the argument rect.top, As for the second error then you should check whether the declaration of hInstance is visible in the point of the function call. Instead of hInstance you could use the expression ...
70,481,294
70,481,342
Why is raw string literal parsed before trailing backslash?
From Phases of translation, backslash joining next line happens in Phase 2 and string literal evaluation happens in Phase 3. Then why does the following code does string evaluation before? #include<string> #include<iostream> int main() { std::string s = R"(before\ after)"; std::cout << s; } gives: before\ aft...
Raw string literals explicitly undo phases 1&2: If the next character begins a sequence of characters that could be the prefix and initial double quote of a raw string literal, such as R", the next preprocessing token shall be a raw string literal. Between the initial and final double quote characters of the raw strin...
70,481,856
70,481,919
How to make the parameter list of a function cleaner?
In a video that I recently watched, Kate Gregory suggests that if a function has a huge parameter list (e.g. 4+ parameters) one should put all those parameters in a struct (i.e. make them members of the struct) and after initializing an instance of the struct, pass it to the said function (obviously this requires refac...
The struct should be in a header file, probably on its own in its own header file. Have you considered this? Adding the convert function to the struct, so it can use the parameters directly, it also allows you to reuse them later. #include <iostream> #include <string_view> #include <span> #include <vector> struct Para...
70,482,021
70,482,243
Select value randomly from groups of values of different types
I have arrays of types int, bool and float: std::array<int, 3>myInts = {15, 3, 6}; std::array<bool, 2>myBools = {true, false}; std::array<float,5>myFloats = {0.1, 15.2, 100.6, 10.44, 5.5}; I would like to generate a random integer(I know how to do that) from 0 to the total number of elements (3 + 2 + 5) so the generat...
Most probably, you need to think how to satisfy your requirements in a simpler way, but it is possible to get literally what you want with C++17. If your compiler doesn't support C++17, you can use corresponding boost libraries. Here is the code: #include <array> #include <iostream> #include <tuple> #include <variant> ...
70,482,493
70,483,126
Use of incomplete template types in templates
This is follow up to a question I asked a few weeks ago in which the answer was that it is ill-formed, no diagnostic required, to use a type in a template that is only complete at the time of the template's instantiation but not at the time of its definition. My follow up question is is this still true in the case in w...
This is legal. The rule of thumb is that everything that depends on template parameters is checked when the template is instantiated. Everything else is either checked when the template is first seen, or when it's instantiated (e.g. MSVC tends to check everything late, and Clang tends to do it as early as possible).
70,482,497
70,529,386
Detecting compile-time constantness of range size
compiler explorer link Consider the following: // Variant 1 template<auto> struct require_constexpr; template<typename R> constexpr auto is_constexpr_size(R&& r) { return requires { typename require_constexpr<std::ranges::size(std::forward<R>(r))>; }; } static_assert(!is_constexpr_size(std::vector{1,2,3,4})); st...
If you look closely at the specification of ranges​::​size in [range.prim.size], except when the type of R is the primitive array type, ranges​::​size obtains the size of r by calling the size() member function or passing it into a free function. And since the parameter type of transform() function is reference, ranges...
70,482,511
70,482,595
-Wstack-usage=byte-size in GCC
The above-mentioned GCC flag has caused some confusion for me. Here it says the following: -Wstack-usage=byte-size Warn if the stack usage of a function might exceed byte-size. The computation done to determine the stack usage is conservative. Any space allocated via alloca, variable-length arrays, or related construc...
Why the stack usage of main is only 112 bytes despite that it calls all the other functions? Stack usage is calculated by GCC is for this function only. This is also in the documentation: "Warn if the stack usage of a function might exceed byte-size". Doesn't it keep the callee on its stack frame until the callee re...
70,483,340
70,483,396
Calling a C++ constructor without parameter does not set values to 0
Can someone explain why my constructor is not setting Fraction c,d,e values to 0 when no parameter is provided? Results are: Fraction c=0,0 d=0,6e23 e=6e23,0. I have found the workaround of setting Fraction::Fraction() {} to Fraction::Fraction() : m_num(0), m_deno(0) {} but I thought using Fraction::Fraction() {} would...
If you do not assign default values to C++ default types (for example: int, float, char) class variables inside the constructor, they are not going to be defaulted to zero. That will lead you to undefined behaviour. Check here to see in which cases the variables will be zero: Default initialization in C++ If you want t...
70,483,521
70,483,596
Is there any way my class take input value like array in C++?
I want write a class and take input value like array int arr[] = {1,2,3,4} myFunc f = {a,b,c,d}; Is there any way my class take input value like array in C++?
This is what std::initializer_list is for: #include <vector> #include <iostream> class foo { private: std::vector<int> nums_; public: foo(std::initializer_list<int> init) : nums_(init.begin(), init.end()) {} void display() { for (auto n : nums_) { std::cout << " " << n; ...
70,483,740
70,483,780
Linker says a function is already defined if I try to define it in another file (running tests)
I have the following files in a testing project: Test.cpp: #include "pch.h" #include "CppUnitTest.h" #include <iostream> #include "PrintOne.cpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace PointandVectorCreationTest { TEST_CLASS(PointandVectorCreationTest) { public: ...
I'm not defining printOne anywhere in Test.cpp. Actually, you are, when you #include the source code of PrintOne.cpp into Test.cpp. If you then compile and link both Test.cpp and PrintOne.cpp together, the linker indeed sees 2 definitions of printOne(), one in each .obj file. For what you are attempting to do, you n...
70,484,127
70,485,494
Looking for a proof on why my algorithm in codeforces works
I'm trying prove the correctness of my algorithm. This is the problem in codeforces: https://codeforces.com/contest/1428/problem/C Here's my code in C++ which was accepted: #include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; int main() { int num, ans, top; string s;...
Great write-up. This may be more commentary than the "formal proof" you might be seeking. Here's something to consider: You don't need the ans variable at all. You simply print top when the inner for-loop completes. When the inner for-loop completes, I would assert that ans==top anyway. Hence, this simplification: ...
70,484,561
70,484,713
C++ : gcc compiler warning for large stack allocation
Consider: void largestackallocation() { double a[10000000]; } int main() { return 0; } On compiling this with MSVC (Cl.exe and MSBuild.exe), a warning C6262 is issued suggesting to move allocation to heap instead of the stack. The compilation is in release mode with the following options: /permissive- /ifcOut...
-Wlarger-than="max-bytes" might be what you're looking for. It warns you whenever an object is defined whose size exceeds "max-bytes".
70,485,111
70,515,364
Why installed libtorrent shows Import Error?
I have built libtorrent with boost with this commands in the boost root folder : bootstrap.bat b2 --hash cxxstd=14 release and after I have added BOOST_ROOT and BOOST_BUILD_PATH to PATH variable. I also have downloaded OpenSSL and build it then have copied to Visual studio 15 2017 compiler include and libs folder repe...
I found the answer. While building libtorrent python binding 2 factors are important: 1- openSSL version 2- linking type python comes with openssl v.1.1 (or similar based on python version) , if building python binding with openssl v.1.1 (which is the latest version while I am writing) one dependency solved otherwise,...
70,485,255
70,485,868
Is it possible to wrap a member function of a C++ class?
I'm trying to wrap a member function of a C++ class. I've successfully wrapped system functions such as fstat, so the GNU linker, ld, creates a reference to __wrap_fstat and the real fstat is called by __real_fstat, but I can't seem to wrap a class member function. Here's a simple example of a class. I'd like to wrap t...
In C++, all symbols names got mangled to ensure uniqueness of the symbol names, when function names are overloaded, placed in classes or subclasses, inside namespaces, etc. The linker has no knowledge of the C++ original symbol names and only handles mangled symbol names. So to wrap a C++ member function, you have to w...
70,485,731
70,485,974
Is `std::format` vulnerable to format string attack? How to mitigate it?
I would like to refactor C style code using printf, fprintf, etc... to C++. Is std::format vulnerable to format string attack, as the aforementioned C functions? If I search for format string attacks, all I find is stdio format string vulnerabilities. I would like to know more about if std::format is vulnerable, and ho...
I would like to know more about if std::format is vulnerable, and how to mitigate it, even if I have to format user provided strings. Even if you use std::vformat (which accepts a run-time string), the input is verified against the types of the other arguments and std::format_error is raised upon mismatch (while std:...
70,486,230
70,486,498
Qt QGraphicsSceneMouseEvent member access to incomplete type 'QMouseEvent' Error
I am getting an error I don't know how to resolve. I created a class CustomScene that inherits QGraphicsScene and I want to override the mouse functions in this class. I am trying to create a rectangle on the scene by dragging and dropping and when even I try to get the position of the mouse using event->pos().x() I ge...
A "member access to incomplete type" usually happens when you are trying to work with a type (i.e. call a method) that has only been declared using forward declaration. In this case QGraphicsSceneMouseEvent is forward declared in qgraphicsscene.h. The actual declaration is in qgraphicssceneevent.h. To use that just put...