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
68,039,359
68,039,916
static_assert causing program to not compile even though the assert is in the header of a function template
I am having some trouble with template metaprogramming. I am trying to create a templated function that automatically adjusts an array based on an enum class, and I was attempting to do this using substitution failure is not an error. I seem to be setting ambiguous overloads, and it seems as if my substitution failure ...
it seems as if my substitution failure is not an error is not correctly working. The rule is "Substitution Failure Is Not An Error". However, this only applies to the process of finding a type. What's happening here is that finding a matching type actually succeeds, but it lands on a type that happens to have a faili...
68,039,408
68,040,820
command push_back results an exit code -1073741819 (0xC0000005) c++
I'm trying to make kind of a little game using c++, and I have to move a character from one point on the map to another one. When I try to do that by push_back and then erase from the source point I get this exit code. What am I doing wrong? My code for moving is: void Game::move(const GridPoint & src_coordinates, cons...
If you look attentively, in the program you trying to push the character to the end: this->grid_characters.push_back(Pair(dst_coordinates,(*it_src).character)); this->grid_characters.erase(it_src); First of all, after you push a new element in the vector, it will likely reallocate data to have enough capacity ...
68,039,765
68,039,849
Add elements of 2d array in C++
I have this 2d array: vector<vector<int>> arr = {{1, 1}, {1, 3, 2}, {1, 6, 11, 6}}; I want to add the lasts elements of each row (1 + 2 + 6), and then the second-lasts (1 + 3 + 11), and so on ((1 + 6), (1)). How can I do that? Btw sorry for my english (not native...
You can do that by, for example, Calculate the maximum number of elements of the elements of arr. Iterate from 0 to the maximum number minus one. Retrieve the ith element counted from the last element with checking if the element has i element or more. Add the elements. #include <iostream> #include <vector> using std...
68,039,832
68,040,055
Template that accepts only iterators pointing to arithmetic types
I'm trying to teach myself the SFINAE pattern and for a thing I'm writing I wanted to write a function that accepts start, end iterators to a value of an arithmetic type (e.g. for summing). This is what I came up with: My main.cpp: #include <iostream> #include <vector> #include "summer.hpp" int main() { std::vec...
Okay, where do I start... typename std::enable_if_t<...> is wrong, remove typename. You only need it if there is :: to the right of the template parameter, e.g. in typename std::enable_if<...Iter...>::type. ::value_type is misplaced, it must be right after Iter. ...::value_type needs typename. std::is_arithmetic<.....
68,039,884
68,039,922
C++ STL: How to copy vector iterator?
I have following code, that fails due to read access violation: #include <vector> using namespace std; vector<int>::iterator myIterator; void foo(vector<int> vec) { myIterator = vec.begin(); } int main() { foo({ 10, 20, 30, 40 }); *myIterator; // Here it fails. return 0; } After some debugging, I f...
vec is only defined within the scope of foo. Since myIterator is an iterator that points to vec, it is no longer valid outside of foo. Trying to dereference such an iterator results in a read access violation. You need to define vec somewhere (in main for example), then pass a reference to it in foo, something like: vo...
68,040,292
68,040,365
Please, help me understand this "pack expansion does not contain any unexpanded parameter packs" compiler error
template<typename ...> bool foo(std::tuple<std::string,float> bar...) { std::vector<std::tuple<std::string,float>> barList(bar...); // ... } This does not seem to generate any syntax error. There is no error indicator at that line in the editor, but the compiler stops with [bcc32c Error] Foo.cpp(117): pack e...
Your syntax is wrong. Your function is equivalent with: bool foo(int bar...) { std::vector<int> barList(bar...); // ... } Notice there is no variadic templates at all, and there is nothing to unpack - instead, you have created a C-style variadic function. One easiest way to change your function would be: temp...
68,040,354
68,040,388
Why does the default argument not work in a template function?
struct A {}; template<typename T> void f(int n, T m = 3.14159) {} int main() { f(8, A{}); // ok f(8); // error: no matching function for call to 'f' } See online demo Why does the default argument not work in a template function? EDIT: I also tried following, and wonder why it didn't work as well. void ...
Default function arguments don't affect template argument deduction. You need a default argument for the template parameter too: typename T = double. As for void g(int, auto = 3.14159), there seems to be no way to fix it.
68,040,421
68,040,452
'Error: void value not ignored as it ought to be' but I'm not setting anything with a void?
I've been trying to iterate though a list of objects, but it keeps throwing this error at me whenever I try to call my display function. Main source Stocks gamestop("Gamestop", "GMSP", 21.45f); Stocks heroShop("Heros Shop", "HESP", 0.35f); Stocks amazon("Amazon", "AMZN", 8.36f); Stocks iphone("Iphone", "IPHN", 56.34f);...
*itr->display(); should be: itr->display(); itr-> is a shorthand for (*itr). Adding an extra dereference (*) makes it *(itr->display()); display() returns void, which cannot be dereferenced.
68,040,513
68,040,568
C++ Remove last comma when printing AVL tree elements
I know similar questions have been asked but I can't seem to find an answer for printing via a recursively called function. I am trying to print preorder, postorder, and inorder traversals of an AVL tree and have implemented the functions recursively. i.e. void inOrder(Node* root) { if(root != nullptr) { in...
Make an internal implementation function that maintains a flag that indicates whether the data item to be output is the first one. Then prepend the output with a comma for all items but the first. void inOrderImpl(Node* root, bool& first) { if(root != nullptr) { inOrderImpl(root->left, first); if (f...
68,040,604
68,041,435
Efficient functor dispatcher
I need help understanding two different versions of functor dispatcher, see here: #include <cmath> #include <complex> double* psi; double dx = 0.1; int range; struct A { double operator()(int x) const { return dx* (double)x*x; } }; template <typename T> void dispatchA() { constexpr T op{}; ...
This likely isn't the answer you are looking for, but the general advice you are going to get from almost any seasoned developer is to just write the code in a natural/understandable way, and only optimize if you need to. This may sound like a non-answer, but it's actually good advice. The majority of the time, the cos...
68,041,036
68,041,842
Creating a base case for Variadic Template recursion with no template arguments
I'm trying to use recursion with variadic templates. I would like the base case to have zero template arguments. After looking through stackoverflow answers to previous questions, I have found two kinds of responses to this problem: You should not specialize templates functions. Herb Sutter wrote about that here: http...
Here's another solution (without specialization), which uses a C++20 requires clause to resolve the ambiguity: template <typename... Args> requires (sizeof...(Args) == 0) constexpr int NumArguments() { return 0; } template<typename FirstArg, typename... RemainingArgs> constexpr int NumArguments() { return 1 + ...
68,041,283
68,041,791
Choleskey Decomposition in C++ via Lapack dpotrf gives invalid result
I'm trying to take the choleskey decomposition of a 1D double array using Lapack's dpotrf function. It seems to work for some cases, but others it has strange behavior. Here is my code: int main(){ int N=2; int INFO; double A2 [2*2] = { 1,1, 1,4 }; printf("%f %f\n", A...
this is incorrect, as it isn't lower triangular It is correct since the original data in the upper triangular is not overwritten. In the 3x3 case you are printing the wrong elements. Take a close look.
68,041,405
68,041,921
Who allocates the memory for control block of shared_ptr when using custom new() operator with a class
Suppose I have a code like this: class Foo { private: int x; public: void* operator new(size_t size); void operator delete(void* p); }; int main() { auto ptr = std::shared_ptr<Foo>(new Foo()); return 0; } The shared_ptr will create separate control-block and object-block. I suppose the memory fo...
The shared_ptr will create separate control-block and object-block. I suppose the memory for the object block will be created using the Foo::operator new(). Nope. You already passed in the pointer to the object, so it only needs a control block. In fact, I believe no shared_ptr construction allocates a single object...
68,041,763
68,041,804
Why is the semicolon at the end of the init-statement within the for statement mandatory?
This is how the C++17 standard defines the for statement: for ( init-statement conditionₒₚₜ ; expressionₒₚₜ ) statement I've also looked in https://en.cppreference.com/w/cpp/language/for: attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement Therefore, I can only unders...
The semicolon is mandatory because init-statement includes the semicolon. Quote from N3337 6.5 Iteration statements: for (for-init-statement condition_{opt}; expression_{opt}) statement for-init-statement: expression-statement simple-declaration 6.2 Expression statement: expression-statement: expressio...
68,041,906
68,042,350
boost::asio::co_spawn does not propagate exception
I'm dabbling in coroutines in respect to boost::asio, and I'm confused by exception handling. Judging by the examples in the docs, it looks like any 'fail' error_code is turned into an exception - so I hopefully assumed that any exception thrown would also be propagated back to the co_spawn call. But that doesn't app...
boost::asio::co_spawn creates a separate thread. This means that exceptions are not propagated. You can read more about this here: Will main() catch exceptions thrown from threads? How can I propagate exceptions between threads? But co_spawn supports a completion handler with the signature void(std::exception_ptr, R)...
68,042,230
68,042,536
How to use the return value from a dynamic_cast on references properly?
We use dynamic_cast operator to safely convert a pointer or a reference to a base type into a pointer or a reference to a derived type. struct Foo{ void f() const{ std::cout << "Foo::f()\n"; } virtual ~Foo() = default; }; struct Bar : Foo{ void f() const { std::cout << "Bar::f()\n";...
Intended as a placeholder for the comment by @1201ProgramAlarm. Simply put, A failed dynamic cast for a reference throws an exception. – 1201ProgramAlarm From the IBM docs: You cannot verify the success of a dynamic cast using reference types by comparing the result (the reference that results from the dynamic cast)...
68,042,255
68,042,654
Using concepts to detect empty parameter packs
In an answer to another question I posted, Jack Harwood shared a nice solution to detect empty variadic parameter packs using concepts. The example problem is to compute the number of parameter pack arguments using recursion. I reproduce his solution below. template <typename... Args> concept NonVoidArgs = sizeof...(Ar...
The concepts themselves are correct but the problem is that the example uses them incorrectly and is itself faulty. In the given code the concept is imposed on an argument basis instead of the entire parameter pack. Your current version template<typename FirstArg, NonVoidArgs... RemainingArgs> constexpr int NumArgumen...
68,042,274
68,042,856
C++20 ranges - how to modify a range?
I have a vector defined as: auto xs = std::vector<double>(5) = { 1.0, 2.0, 3.0, 4.0, 5.0 }; and I've created a view on this vector: auto vi = xs | std::ranges::views::drop(1); for example. However, I'd like to convert the view data into an actionable range or another vector so that I can modify it. So far, I've tried t...
However, I'd like to convert the view data into ... another vector so that I can modify it. You can use the constructor of std::vector that accepts a pair of iterators: template< class InputIt > constexpr vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); std::ranges::ac...
68,043,552
68,043,570
QProcess can't start python script
The problem is that the python script doesn't run. I expect to see an output file (tmp.json) in the directory but I do not. There are some questions with the same issue but the solutions did not work for me. The python.exe path is correct as I used to use python.h instead of Qprocess to embed python. main #include "mai...
The character \ is used for escape sequences in Python, so you should write \\ to express \ in strings. import json with open('F:\\NLP\\google_corpus\\scrape_python\\qt\\cpy2tmp.json', 'w') as json_obj: json.dump(2, json_obj)
68,043,671
68,053,900
Why is this local QMultiMap detaching when modified?
To give some background: in my project I put a debug breakpoint inside QMap::detach_helper because I wanted to see if I could spot any occurrences when implicitly shared QMaps were detaching due to an oversight e.g. using find when constFind could have been used. I didn't expect to hit it very often because mostly I am...
Q(Multi)Map does not detach on every insert but only on the first one when the map is not yet initialized: QMultiMap<int, int> mm; mm.insert(42, 43); // detach_helper is called because the container needs to be initialized mm.insert(43, 44); // detach_helper is not called
68,044,072
68,044,132
Why pointer to list create a 2D list structure
I'm trying to implement a hashtable. I understand list<int> *table is a pointer to list(entries), and in the constructor, I init the size of the list(represents how many entries). I'm very curious why this can be a list of list(2D list) structure, why I can perform table[key].push_back(...); Thanks class HashTable { p...
I think you should learn how pointer work. There are 'size' of list as you make in Initializer. table[0], table[1] ... all of these are list. Think about the case of int. int* table = new int[size]; table[0], table[1] all of these are int. list<int>* table = new list<int>[size]; then table[0], table[1] all of these a...
68,044,151
68,044,310
array of size N, with N not initialized, but no error and runs fine
I created an array of size N, where N is a variable and not initialized. arr[N] is of variable size. It should give an error but it runs fine. #include<iostream> using namespace std; int time_calculator(int ,int *,int ); int main(){ int N,RN,i; int arr[N]; cin>>N; cin>>RN; for(i=0; i<N ;...
The problem is not it being uninitialized, but rather not being a compile-time constant. The program is ill-formed (i.e. not valid C++) because of this. Most compilers don't enforce strict standard compliance by default, but you can configure them to do it. For MinGW/GCC you could use following flags: -std=c++xx -pedan...
68,044,222
68,044,233
C++: Why/How a Break Statement Works In This Code?
I have started to use C++ programming language as a complete beginner. With the aim of becoming a better programmer for my STEM degree and with the goal of competitive programming in mind. I have started Functions and Loops in C++ recently and there was a problem I was not sure how to approach. The probelem: "Write a f...
In your case if k % k1 does not show that the k1 being a factor of the k, the loop is broken after the print statement. If the k % k1 does show that the k1 being a factor of the k, it also breaks out of the loop. So, either of the break statements leads to the loop termination on the first iteration here. If you test f...
68,044,266
68,044,714
How to flush buffer manually?
this is same Question but not answered properly. Code #include<iostream> int main() { char ch='a'; std::cout<<ch; } Output a so here only one character in output stream which leads to buffer. so buffer is not full still it shows ouput on screen. Means buffer is flushed automatically. so please give example w...
You can see whether your stream is buffered by sleeping between outputs, e.g.: #include <iostream> #include <thread> int main() { for (int i = 0; i < 50; i++) { char ch = 'a'; std::cout << ch << "\n"; std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } On some platform...
68,044,643
68,047,597
OpenGL best practice for putting two different mesh in the same vertex VBO
After some searching, it is said that the separated VAOs which shares the exact same shader attribute layouts, merging these into one VAO and put all these datas into one VBO so that I can draw this objects with only one draw call. This perfectly makes sense, but how about uniform variables? Say that I want to draw tre...
The purpose of batching is to improve performance by minimizing state changes between draw calls (batching reduces them to 0, since there is nothing between draw calls). However, there are degrees of performance improvement, and not all state changes are equal. On the scale of the costs of state changes, changing progr...
68,044,731
68,045,014
cpp - Implement a merge sort function without using void return type (recursively)
I intend to create a recursive merge sort function that returns a pointer to the sorted array. Below is my implementation of the program. The output produced by the code mostly consists of garbage memory locations. Since it is a recursive function, I'm having trouble debugging it. What scares me is whether I have under...
Your code have returned the local array's address, which is invalidated after function returned. Then gabarage data is printed: int sortedArray[n1+n2]; int *ptr = sortedArray; // pointer to the sorted array Change into int *ptr = new int[n1 + n2]; auto sortedArray = ptr; Then we get a non-garbage value, but w...
68,044,788
68,050,822
wxPopupTransientWindow not showing content correctly
I'm creating a C++ wxWidgets calculator application. I'm implementing trigonometric functions, and to save on space I've reunited all of them in a single button. If you right click on the button then, a popup is created, which contains buttons for all the functions. I'm using a derived wxPopupTransientWindow class for ...
To get the buttons to layout in the popup window, in the constuctor for expandMenu I think you just need to change panel->SetSizer(sizer); to SetSizerAndFit(sizer); Layout(); From a UI perspective, I think a split button might be a better way to implement the functionality you are describing. wxWidgets doesn...
68,045,041
68,045,604
I wrote a program to divide and array into two new arrays but for some reason, the elements of the original array is changing. C++
I don't understand why my original array i.e. arr[] changing (changing as in the order of number is changing, the last four elements are becoming the first four), Please explain why is that happening even when I have not assigned it anywhere. #include <iostream> using namespace std; int main() { int arr[] {5,4,1,8...
It's called Undefined Behavior. You accidently rewriting memory which not allocated for you arrays array1[i]=arr[i]; array2[i]=arr[i+4];
68,045,063
68,045,134
What does the value from dereferencing a function pointer means
#include <iostream> void PrintTheValue(int(*func)(int a)); int main(int argc, char **argv) { PrintTheValue([](int a) {return a; }); return 0; } void PrintTheValue(int(*func)(int a)) { std::cout << *func << std::endl; } In my concept of understanding the func, it would be a pointer to an int passed ...
In my concept of understanding the func, it would be a pointer to an int passed by value. func is a pointer to function, which takes an int and returns int. But in this case I'm passing a lambda which doesn't seem to be called anywhere. You're passing a lambda without capturing, which could convert to pointer to fu...
68,045,475
68,050,692
boost::asio::connect reports success on wrong subnet
Using Boost v1.74: int main() { auto ctx = boost::asio::io_context{}; auto socket = boost::asio::ip::tcp::socket{ctx}; auto ep = boost::asio::ip::tcp::endpoint{ boost::asio::ip::make_address_v4("192.168.0.52"), 80}; boost::asio::connect(socket, std::array{std::m...
Any IP address of the form 192.168.xx.xx is a non-internet-routable network. This means no internet routers will route it. So the only way packets get routed off your subnet is if you configure a route on your own router or host. 192.167.xx.xx is an internet routable network, Presumable there is a host out there on the...
68,045,625
68,054,814
qt sqlite didnt create table
i have written a code in qt c++ to make database and insert user input informations . the code create db but didnt create tables and insert informations . please look at photos to understand my problem better. tnx for your helping. make db make table 1 and insert data make table 2 and insert data result : db created bu...
You can user lastError(), to check sql function errors q.exec("....."); qDebug()<<q.lastError(); The function description could be found here
68,045,643
68,047,356
Why is there no forward declaration in concepts c++?
When I try this example: template <typename T> concept only_int = std::same_as<T, int>; int add_ints(only_int auto&&... args) { return (std::forward<decltype(args)>(args) + ... + 0); } It works... but when I only declare it like this: template <typename T> concept only_int; ... // defined later on... It would ...
If you could forward-declare concepts, then you could use them recursively. By preventing forward-declaration, there doesn't have to be an explicit provision in a concept declaration to stop you from using them recursively.
68,045,818
68,046,914
Make a object accessible by only its library, and not by any other routine in the program
Lets say I have two (or more) c functions func1() and func2() both requiring a buffer variable int buff. If both functions are kept in separate files, func1.c and func2.c, How do I make it so that buff is accessible to only func1() and func2() and not to the calling routine(or any other routine). Here is an example set...
One typical approach to this problem is to give the global variable a name that begins with _. That is, in func1.c you might write int _mylib_buff; And then in func2.c, of course, you'd have extern int _mylib_buff; Now, of course, in this case, _mylib_buff is technically an ordinary global variable. It's not truly "...
68,045,829
68,046,523
Expected behaviour for a standard container when comparison object always returns either true or false
What is the expected behaviour when the custom comparison object always return same result(could be either true or false but is always same), while putting the elements in a standard library container, say std::set or a std::map. For example struct A{ int i_mem; double d_mem; }; bool operator > (const A& first, ...
If the comparator always returns false then a < b || b < a is always false so std::set will treat all elements as equal and only ever contain one element. If the comparator always returns true then a < b && b < a is always true which makes no sense and violates strict weak ordering which leads to undefined behaviour.
68,045,900
68,048,619
How to Center Tabs of wxNotebook in wxWidgets
Hi am using wxWidgets and want to center the tabs in wxNotebook. The default position of the tab buttons are left(screenshot attached). That is they are aligned to the left of the window. How can I make the tab buttons to be at the center of the screen? In the screenshot two tab buttons/controls are shown which are ali...
@JasonLiam, The answer to both questions is: You can't. Centering tabs in wxNotebook is supported and is done by default on OSX only. You can try to add a hidden tab, but I doubt it will help with the second problem. HTH!
68,046,046
68,046,121
Overloading << operator in C++ requires friend
I'm learning C++ and specifically the operator overloading. I have the following piece of code: #include <iostream> #include <string> using namespace std; class Vector2 { private: float x, y; public: Vector2(float x, float y) : x(x), y(y) {} Vector2 Add(const Vector2& other) const; Vector2 op...
The operator<< must be defined as non-member function (as well as operator>>). Let's take a look at the case when our class has defined the operator<< as a member function, we would have to do output like so: // Member function, lhs is bound to implicit this ostream& operator<<(ostream&) const; Myclass obj; obj << std...
68,046,154
68,046,319
How Can I Get Value_Type on both value and pointer by using template in c++?
template<class T> struct TypeInfo { using value_type = is_pointer<T>::value ? T * : T; }; This code is just pseudocode. I wanna find value type for each pointer and value. I'll using this like sizeof(TypeInfo<something>::value_type ). Can you help me?
You can do it like this: template<class T> struct TypeInfo { using value_type = std::remove_pointer_t<T>; };
68,046,293
68,046,346
How to use libcurl with this request and get json server answer c++?
I have some requests and i want to usen them in libcurl. But i dont know how to do this So whot should i do implemete this in code like "curl.get(dsds) curl.header("", "")" curl "https://pterodactyl.file.properties/api/client/account" \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ -H 'Aut...
Basic function for downloading something from web is #include <iostream> #include<curl/curl.h> static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } std::string curlDownload(std::string link){ ...
68,046,437
68,046,828
Redirecting std::fstream to output to std::cout stream
How to redirect std::fstream object to output to standart output stream? So I could use my object instead of std::cout.
fs.std::ios::rdbuf(std::cout.rdbuf()) would make fs use the same underlying stream buffer as std::cout. I wouldn't recommend it, though.
68,046,787
68,047,114
Convert std::chrono::milliseconds to ISO 8601 string
I've a std::chrono::milliseconds representing epoch unix time in milliseconds. I need to convert it into a string that follows the ISO 8601 format, like 2020-02-25T00:02:43.000Z. Using date library I was able to parse it, with following GetMillisecondsFromISO5601String method: #include "TimeConversion.hpp" #include <da...
The problem is that you're treating a time duration (milliseconds) as a time_point (time_point<system_clock, milliseconds>). All you need to do is convert the duration to time_point with explicit conversion syntax. The date lib has a convenience type alias for this type: sys_time<milliseconds>: string TimeConversion...
68,046,909
68,047,239
What type of __iter_concept<_Iter>
I watched std::random_access_iterator and other iterator concepts This is what the GCC implementation looks like template<typename _Iter> concept random_access_iterator = bidirectional_iterator<_Iter> && derived_from<__detail::__iter_concept<_Iter>, random_access_iterator_tag> && totally_...
How is it that __iter_concept<_Iter>, derived from random_access_iterator_tag? Because it's written to be. __iter_concept is not a concept; it's a type (or type alias). C++20 specifies a set of rules for determining the iterator category (forward, random access, input, etc) from a valid iterator that implements the C...
68,046,975
68,047,099
There is something strange with the c++ "delete" command
If deleting the pointer, why is the output 5 5?(I'm new) #include <iostream> using namespace std; int main(){ int* i = new int(5); cout<< *i <<endl; delete i; cout<< *i <<endl; return 0; }
Delete doesn't set 0 or any value to the memory i is pointing to. It just flags it as free so something can use it later. This leads to undefined behaviour
68,047,077
68,047,165
Why move constructor is not called in my code ? Also why dtor is not called just to destroy temp obj?
Lines in my code student g1(student("Larry"));//why move ctor is not called after overloaded ctor??? student g2 = "Delta";//Also here,why move ctor is not called after overloaded ctor??? Also why dtor is not called for unnamed temporary objects created just after???? Actually i am confused totally ,when move ctor is c...
In this line: student g1(student("Larry")); The g1 is constructed using a constructor due to copy elision. In order to move construct g1, you would need to do it explicitly in this case: student g1(std::move(student("Larry"))); In the case of vec.push_back(student("vickey")); the move constructor is called since std...
68,047,129
68,047,509
how to know how many device connectd to sqlserver remotly
hello i have a program linked with mysql server remotly i want to know devices connected number ?
It's unlikely you can count devices, however there is a system table information_schema.processlist which shows MySQL server process list, you can count hosts there. See details here on required privileges and fields.
68,047,438
68,047,487
now() cannot be converted to sys_days! I need today's date from now()
Having trouble with: auto n = std::chrono::system_clock::now(); std::chrono::sys_days sd = n; Why ? n is a time_point and sd is also time_point (actually time_point<system_clock, days>)??
Here's how you do it: #include <chrono> int main() { using namespace std::chrono; auto const n = system_clock::now(); sys_days sd = floor<days>(n); } Did I know this off the top of my head? No, of course not. It was in the examples of cppreference.com.
68,047,543
68,047,894
Template function to load big endian from byte array
I'm trying to implement template function, for reading from byte array in big endian order. This is my current implementation: template<typename T> T load_big_endian(const unsigned char* buf) { T res {}; std::size_t size = sizeof(T) - 1; for (int i = 0; i <= size; i += 1) { res |= static_cast<T>(buf[size - ...
Here's how I would do it: #include <algorithm> #include <cstddef> #include <type_traits> template <typename T> [[nodiscard]] T load_big_endian(std::byte const* const buf) noexcept requires std::is_trivial_v<T> { T res; std::reverse_copy(buf, buf + sizeof res, reinterpret_cast<std::byte*>(&res)); return res; ...
68,047,545
68,048,261
Is there an AVX2 instruction (and intrinsic) to broadcast load a 16 bit value 16 times into an __m256i?
In the following code, I can use avx2 to count the number of 1 bits in each position separately 16 bits at a time, but there are 4 missing instructions on the lines labelled loadLow16. I need an instruction that loads a 16 bit value and puts it in each 16 bits of the avx2 register (16 times). Is there an instruction to...
For your overall positional-popcount problem, see https://github.com/mklarqvist/positional-popcount for heavily optimized implementations, which are also correct unlike this, which you obviously haven't had time to debug yet since you were missing a building block. Adding multiple x & (1<<15) results in an int16_t elem...
68,047,972
68,066,866
Adding styles to QPushButton
I have created a qpushbutton in the source file ".cpp": QPushButton * btn = new QPushButton("Click me"); and now I want to add styles to it. Like changing the background, adding border-radius, changing the cursor, and so on.
This works fine for me: btn->setObjectName("mybtn"); btn->setStyleSheet(QString("" "#mybtn{background-color: #182848; border-radius: 5px; border: 1px solid transparent; color: white;}" "#mybtn:hover{background-color: white; border-color: #182848; color: #182848;}" ...
68,048,292
68,212,609
Converting an AVFrame to QImage with conversion of pixel format
I need to extract frames of videos to images in my QT application. I don't know in advance the pixel format of the source videos/frames (yuv, rgb...), But I need to obtain a reliable image pixel format such that I can consistently handle the images later. I'm using the ffmpeg libraries to get the frames, which are alre...
I figured it out in the end, using a manually allocated buffer, which isn't very clean C++ code but works faster and without deprecated calls. It's not possible to pass image.bits directly to sws_scale because QImages are minimum 32 bit aligned (https://doc.qt.io/qt-5/qimage.html#scanLine), meaning that depending on th...
68,048,422
68,048,469
Matrix initialization not working with higher values
I have to initialize a matrix which has to be later passed to a Cuda kernel. But I get a segmentation fault when I initialize the matrix. The code is as follows - #include <iostream> int main(){ size_t m = 512; size_t k = 32; size_t n = 32; float* a = (float*) malloc(m * k * sizeof(float)); ...
a[i*m + j] = 1.0f; This math is wrong. Using the terminology of i representing the row and j representing the column, there are k values per row, therefore this should be: a[i*k + j] = 1.0f;
68,048,434
68,048,462
Show Max and Min Temperature of entire week in C++
I want to develop a program in C++ which gets the temperature of entire week (7 days) and then shows the max and min temperature and also the day of that temperature. I'm using the following code: #include <iostream> #include <conio.h> using namespace std; int main() { //Declare Variables /*int Monday; int ...
Use == to compare instead of single = it displays Sunday because it is the last to be assigned
68,048,964
68,049,039
Why do we send a ref to ostream obj to ostream overloadings?
I didn't get the intuition behind this way of writing implementation when we want to create a class-specific ostream object. friend ostream& operator<<(ostream& out, Object& obj); It has such a use. It is passed one parameter while using with operator overloading. But during the definition, we've written ostream& out ...
friend ostream& operator<<(ostream& out, Object& obj); is a binary operator (like +, -, ...). It takes 2 operands and returns something. In this case it's auto result = operand1 << operand2; with result being operand1 (the original ostream) just like int operator+(int operand1, int operand2); int result = operand1 + ...
68,049,473
68,049,816
Transform uint64_t range in uint32_t range
I want transform an uint64_t into an uintw_t with w in { 8, 16, 32} preserving "range": #include <cstdint> #include <type_traits> Idea 1: f:[a,b]->[c,d] with f(a)=c, f(b)=d let a = 0, b = 2^64-1, c = 0 and d = 2^w-1. if f(x) = mx+n with m = (d-c)/(b-a) = (2^w-1)/(2^64-1) < 1 (we need float or double...), n = 0 templat...
Shifting is standard; you can get some simple rounding by first adding half of the least-significant preserved bit’s value before shifting, although that doesn’t implement proper round-to-even and you have to worry about overflow.
68,049,621
68,050,091
Reading and Writing with char* to file
I am wondering how can you write data of type char*,int,double using char* and also reading a whole file line by line using again char* ? I know it can be done with std:string really beautiful but I am interested with char*. I have created a Write() method which writes char* successfully but I don't know how to adjust...
I have created a Write() method which writes char* successfully but I don't know how to adjust it for ints and doubles [...] First of all, the function std::ofstream::write is intended for unformatted (binary) I/O. Since you are outputting text, it would be easier to use the formatted I/O functions, for example opera...
68,050,459
68,051,777
C++ nested designated initializer with pointer
I thought it would be useful to be able to initialize a struct that references another struct with a pointer, using the designated initializer. Such a pattern often happens in some APIs (e.g., Vulkan). For instance, consider the following structs: struct A { int v; }; struct B { int v; A* a; }; struct C {...
This is safe as long as the function doesn't store or return the referred object or its address or the nested pointers for later usage. The temporary objects will be destroyed at the end of the full expression and as such the mentioned stored / returned references / pointers would be invalid. [class.temporary] ... Tem...
68,050,647
68,050,701
In what cases do I need to consider byte order?
Do I need to consider endianness when serializing/deserializing data to write/read binary to/from the same machine? There's no network communication involved.
In what cases do I need to consider byte order? Always when de-/serialising. The reader has to interpret the bytes in the same order as the writer. When the processes are on the same system, it is generally safe to use the native byte order. That is not safe when multiple systems may be involved because the native by...
68,050,872
68,150,329
VisualStudio CMake dynamic library: include/link all used functions in *single* dll
I have a VisualStudio-2019 C++ Project which uses CMake and Ninja to build a dll, the Project uses functions from a few Libraries like protobuf and spdlog, which I have installed using vcpkg. When building, the output gets written to four distinct dll files and all of them are needed for the main-dll to run. Below are ...
Setting the mentioned flags or appending -static to the import library components had no effect, I went as far as set(BUILD_SHARED_LIBS OFF) set(CMAKE_EXE_LINKER_FLAGS "-static") set(CMAKE_MODULE_LINKER_FLAGS "-static") set(CMAKE_SHARED_LINKER_FLAGS "-static") set(CMAKE_STATIC_LINKER_FLAGS "-static") But this didn't h...
68,051,186
68,051,217
C++ primer 5th edition: dynamic_cast
I have this text from C++ Primer 5th edition: dynamic_cast<type*>(e) dynamic_cast<type&>(e) dynamic_cast<type&&>(e) In all cases, the type of e must be either a class type that is publicly derived from the target type , a public base class of the target type , or the same as the target type . If e has one of these typ...
I think the contrary he meant because if the type of e is derived from the type cast then we don't need a conversion or cast because they are implicitly convertible by inheritance If the type isn't the same, then there must be a conversion in order to arrive to the target type, whether that conversion is implicit or ...
68,051,216
68,051,311
send a member function as an argument to a member of templated class
I have a template basic class: i would like to send a member function as a parameter to another function, how can i do it? template <class T> class GenericButton { public: GenericButton(const T& t) :m_t(T) {}; auto& getT() { return m_t; } private: T& m_t; }; class Check { private: bool m_ge...
Something along these lines, perhaps: using Callback_t = std::function<void()>; GenericButton<Callback_t> m_button{ [this](){ changeType(); } }; Demo. I took the liberty to change GenericButton to hold the callback by value; holding it by reference is asking for trouble.
68,051,395
68,051,492
Why is my global variable vector not storing my data?
I read a text file which includes "," separated words. I read this file line by line. After taking a line, I split it in to words by using split function. Here I use ',' for separate words from the line. I defined a global vector so I thought I can store all the words in that vector. Everything works fine until the vec...
void split( string st,vector<string> evec){ The 2nd parameter to this split() function is called evec. It has absolutely nothing to do, whatsoever, with the global variable that just happens to have the same name. Just because it has the same name as the global variable doesn't mean that it's the same object, it is no...
68,051,489
68,051,553
context-select like features in C++
Imagine a situation where I'd like to call a function that does some amount of processing, but is time-bound. I could write a function in golang using context.Context and select. I'd imagine something as follows: package main import ( "context" "fmt" "time" ) func longRunning(ctx context.Context, msg stri...
Something along these lines, perhaps: void longRunning(std::atomic<bool>& stop) { for (;;) { if (stop) return; // Do a bit of work } } int main() { std::atomic<bool> stop = false; auto future = std::async(std::launch::async, longRunning, std::ref(stop)); future.wait_for(std::chrono::seconds(num_secon...
68,051,588
68,052,020
Segmentation Fault with glViewport (openGL C++ programming with GLFW and GLAD)
1) Problem summary: I am following exactly the tutorials on LearnOpenGL dot com. My program is crashing (with a segmentation fault) whenever glViewport is being called. How can I have it not crash while calling glViewport according to the code shown below (and in the tutorials). 2) What I have tried: Besides googling t...
After continuing to have this problem with other gl functions and with further research, the problem can be solved by putting the following code after the glfwMakeContextCurrent(window). This has solved all segmentation faults with the glViewport calls listed in the problem. gladLoadGL();
68,051,758
68,051,774
Separating ternary and equals operator
bool boolean = true; T* a = nullptr; T* b = nullptr; // What I have: (boolean ? a : b) = new T(); // What I want: ??? which = boolean ? a : b; which = new T(); How can I split that expression into two lines? At the moment I use up this ternary operator all over the place, so I think it would be better to just have i...
You can define it as reference: auto& which = boolean ? a : b; // or T*& which = ... which = new T(); ... delete which;
68,051,937
68,051,996
How to partially specialize std::unordered_map as a member of my templated class?
I can't seem to understand why this does not work: #include <unordered_map> #include <vector> template<typename T> struct Bar { Bar(const T &t) : x{t} {} T x; }; template<typename T> struct Foo { std::unordered_map<T, Bar<T>> u; Foo(const std::vector<T> &v) { for (const T &i : v) ...
As @songyuanyao has very cleverly noticed, the problem was that std::unordered_map::operator[] returns a reference to the mapped type, which requires a constructor that takes no arguments. Using std::unordered_map::insert solves this without requiring the introduction of such constructor in bar: #include <unordered_map...
68,052,113
68,052,126
deep copy problems in C++
So I have a class Rectangle with an overloaded operator= defined as follows: Rectangle& Rectangle::operator=(Rectangle &rhs) { if (this != &rhs) { m_x = rhs.m_x; m_y = rhs.m_y; m_width = rhs.m_width; m_height = rhs.m_height; m_intersection = rhs.m_intersection; } ...
Your problem is that you haven't declared the argument const. It should be this: Rectangle& Rectangle::operator=(const Rectangle &rhs)
68,052,257
68,052,293
Choosing template specialization of a base type with derived types
Is it possible to have the template specialization of a base type chosen for the derived types? If not, what is a possible solution to the following without having to specialize for each derived type? NOTE: This is a simplified version of our validator. Different types have different validation requirements template <t...
You can use partial specialization for all the derived classes of Bar. template <typename T, typename = void> class IsValid_Executor { public: auto IsValid(const T& InObj) -> bool = delete; }; then template <typename D> class IsValid_Executor<D*, std::enable_if_t<std::is_base_of_v<Bar, D>>> { public: auto IsVa...
68,052,544
68,052,562
C++ reference to the addition of variables?
how is this code snippet translated by the c++ compiler? int i = 5; int j = 4; int *p = &j + i; It creates a pointer 'p' equal to, the address of j + the address of i? the address of j + i? or something else?
Since the & operator has higher precedence than the +, you add to the address of the j the value of i, thus, you have undefined behavior if you'll try to dereference this pointer (p points to an invalid memory address). As was noted in the comments, an invalid address assign by itself does no harm, but the situation wi...
68,052,691
68,052,973
give the line input to vector until EOL
2 5 3 4 5 2 1 5 4 4 4 2 1 is the input, where 2 is the number of test cases, 5 is "not" the size of the vector, I have to read the whole line into the vector, but only able to read one line with the code I wrote. Can you suggest better code to read the input? int main(){ int t; cin>>t; while(t--){ ...
#include <iostream> #include <string> #include <sstream> #include <vector> #include <limits> using namespace std; int main(){ int t; cin >> t; while (t--){ int n, j; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string s; getline(cin, s); ist...
68,053,145
68,053,191
why bits sets are decreased after setting flag manipulator?
1 Code #include<iostream> #include<bitset> int main() { std::ios_base::fmtflags flag=std::ios::showpos; std::cout<<std::cout.flags()<<"\n"; std::cout<<flag<<"\n"; std::cout.flags(flag); std::cout<<std::cout.flags()<<"\n"; std::cout<<59.20<<"\n"; std::cout<<std::bitset<16>(40...
The flags function takes the new value, not a flag to add. What you're doing is replacing the flags entirely with showpos. If you want to do it with flags, you need to add the flag yourself: std::cout.flags(std::cout.flags() | std::ios::showpos);
68,053,402
68,053,665
How to sort vector of class contain CString?
I declared a class like this: class myclass{ array myarr; pair<PT3D,PT3D> mypair; ID myid; CString tag; } after fill data, i have a vector<myclass> myvec; How can I sort this vector based on the CString value of each class? bool SortCompare(const wchar_t* a, const wchar_t* b) { if (wcslen(a) ==...
Note CString provides less operator so you do not have to fall back to C-API like wcsncmp. You are making this overcomplicated. using C++11: std::sort(myvec.begin(), myvec.end(), [](const myclass& a, const myclass& b) { return a.tag < b.tag; }); C++20 has even something simpler called projection: std::ran...
68,053,581
68,053,963
Why aren't array access and pointer arithmetic equivalent with full optimization?
Why doesn't this code produce the same assembly? (g++ -O3) I know little of assembly but it seems case 2 accessing has less instructions, so should be preferred, right? I am asking this because I wanted to implement a wrapper class with an access operator that returns a pointer int* p = a[i] (so access is a[i][j], inst...
The expressions *(a + i*3 + j) and a[i*3 + j] are not equivalent at the level of C++. Since binary + associates left-to-right, the former is equivalent to *((a + i*3) + j) while the latter is equivalent to *(a + (i*3 + j)). They can produce different results if, for instance, the sum in i*3 + j would overflow int. Fo...
68,053,583
68,053,598
How to store values to container? c++
I'am trying to save the values to container, but add identidier not found. I can not also call function Array::add(*train) Error C2352 'Array::add': illegal call of non-static member function Train* train = new Train(number, path, time_of_departure); train->print(); add(*train); //void contains(); return train; C...
As the error msg suggest, you are calling the add msg like it were static what you instead have to do is use the object and call add method your custom class array looks like this: class Array { private: vector<Train>trains; public: Array(); void add(Train&train); Train find(); }; so you can do someth...
68,054,400
68,056,166
how to check if file already exists in qt simple mediaplayer
i have a simple media player and one of the features is that the player has a list of the videos that are opened , i want to create an additional feature where it checks wether the video or "file" has already been opened and stop it from opening i have tried something like this but it didnt work : bool fileExists(QStri...
this here makes no sense: bool fileExists(QString path)= QFileInfo::exists(path).isFile(); my suggestion to you is to define a method instead: bool MainWindow::fileExists(QString path) { QFileInfo fi(path); return fi.exists(path) && fi.isFile(); } and for using it: QString path{"/myPathToFile/myVideo.mp4"}; ...
68,054,501
68,054,835
Why is this constexpr-function giving me errors?
For debug purposes, I want to be able to get the name of a type as a string, and after some Googling I found this answer on SO: C++ Get name of type in template It presents this solution: #include <array> #include <cstddef> namespace impl { template <typename T> constexpr const auto &RawTypeName() { ...
The sample code only runs with C++17 or higher. It seems that you are using Visual Studio. And if so, you can go to the Project Protities and do the following change to make your code run properly.
68,054,530
68,054,622
How to scan UINT with width = 2 with fscanf()?
I need to read data like "01", but skip data like just "1". I tried fscanf(f, "%2lu ", &ulong), but seems that 2 is max length, not fixed. Yes, i know that i can do it with symbols like %c%c, but it's will be harder for reading code. What should i do?
Use "%n" conversion specifier #include <stdio.h> int main(void) { long n; int m1, m2; if (sscanf(" 123\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error"); if (m2 - m1 != 2) puts("error with 123"); if (sscanf(" 12\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error"); if (m2 - m1 != 2...
68,054,767
68,095,755
asio underlying behavior in async_receive
I have worked with asio library for a few projects and have always managed to get it work, but I feel there are somethings of it that I have not entirely/clearly understood so far. I am wondering how async_receive works. I googled around a bit and had a look at the implementation but didn't understand it quite well. Th...
Asio does not create implicitly any new threads. In general it is based on queue of commands. When you call io.run() the framework is taking the commands from the queue and executing them until queue is empty. All the async_ operations in ASIO push new commands to the internal queue. Therefore there is no risk of sta...
68,054,768
68,061,614
Modifying value of object pointed by a shared pointer
I have recently started working with shared pointers and need some help. I have a vector 1 of shared pointers to some objects. I need to construct another vector 2 of shared pointers to the same objects, so that modifying vector 2 would result in modification of vector 2. This is how my code looks like: This works fine...
The code for the setup described in the comments could be: #include <vector> #include <memory> #include <iostream> using namespace std; struct A { int a; A(int a): a(a) {} }; int main() { auto p_vec1 = make_shared<vector<shared_ptr<A>>>(); auto p_vec2 = make_shared<vector<shared_ptr<A>>>(); fo...
68,055,032
68,056,756
LNK2001 unresolved external symbol __imp_calloc when attempting to run a basic program with glfw and bgfx
I am trying to create an application with GLFW and BGFX but I am getting these errors: LNK2019 unresolved external symbol __imp__stdio_common_vsscanf referenced in function sscanf LNK2019 unresolved external symbol __imp_strspn referenced in function glfwUpdateGamepadMappings LNK2019 unresolved external symbol _...
You should be linking glfw3_mt.lib instead of glfw3.lib as you are using Multi-threaded Debug instead of Multi-threaded Debug DLL.
68,055,208
68,055,334
Invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and 'vector<char>')
I'm attempting to cast ASCII numbers to their corresponding letters of the alphabet using a sentinel controlled loop. The compiler gives me the error next to cout: Invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and 'vector<char>') I'm using XCode. This is my current code: #incl...
The std::vector does not have overload for the operator<<, so when you have the cout << Letters, we can say, that the vector does not have definition for what to do, when the << is applied to it. Some time later, you will know that classes can define an appropriate behavior when an operator is applied to them. These de...
68,055,395
68,055,640
How to help the compiler to optimize lambda calls?
The use of lambdas can be a great boost to code readability, when allowing data structure traversal to be extracted to a separate function. Here is a minimal example: static inline void forXY(int v, std::function<void(int,int)> body) noexcept { for(int y = 0 ; y<v ; y++) { for(int x = 0 ; x<v ; x++) { body(...
Do not use std::function, use templated argument for body so the compiler can actually see the lambda when compiling forXY. Otherwise it resorts to type erasure and virtual calls inside std::function. – yeputons Using this idea, here is the improved code: template <typename F> static inline void forXY(int v, F body) ...
68,055,538
68,055,756
How to Share Mutex, Condition Variable and Queue between two Classes C++?
When trying to learn threads most examples suggests that I should put std::mutex, std::condition_variable and std::queue global when sharing data between two different threads and it works perfectly fine for simple scenario. However, in real case scenario and bigger applications this may soon get complicated as I may ...
Typically, you want to have synchronisation objects packaged alongside the resource(s) they are protecting. A simple way to do that in your case would be a class that contains the buffer, the mutex, and the condition variable. All you really need is to share a reference to one of those to both the Consumer and the Prod...
68,055,544
68,055,605
C++ Reference Creation Syntax
When creating a reference in C++ why does the compiler request a value and not an address. For example: int i; int &j = i; is valid. int i; int &j = *&i; is valid. int i; int &j = &i; is incorrect. If you are equating the address, why does it request a value?
A reference is an alias to an already-existing object or function. In particular case, this is an lvalue reference, so it is a reference to an lvalue, the address of an object is not an lvalue. A reference to T can be initialized with an object of type T, a function of type T, or an object implicitly convertible to T....
68,055,829
68,055,843
How to write Numbers With Commas?
Sometimes in C++ I want to use large number like 1000000 and it's confusing. How can I use commas (if that is possible)? For example I want this to work int x = 1,000,000;
You an use the digit separator since c++14 int x = 1'000'000 Does this work for you?
68,055,987
68,056,076
error while initialising value of size in std::vector in c++
I am a beginner in programming and I observed something new while implementing vectors. my first code in vector initialization doesn't work but the second code works perfectly. please explain to me the reason behind it. code 1: #include <iostream> using namespace std; #include <vector> vector<long long int>v; v.reserve...
You might be looking for something like vector<long long int>v {1,2}; Using a list initialization or void MergeSort(std::vector<long long>& arr[],long long n){ long long count=0; if(n==1) return; std::vector<long long> U(arr.begin(), arr.begin()+n/2); std::vector<long long> V(arr.begin()++(n-(n...
68,056,180
68,056,273
how to get a length of char array char*
i have something like this char * array[] = {"one","two","three","five"}; how can I get its length (which is 3 here). if I use strlen() then I get the length of "one".
For starters you have to use the qualifier const in the array declaration. const char * array[] = {"one","two","three","five"}; To get the number of elements in the array you can write size_t n = sizeof( array ) / sizeof( *array ); If your compiler supports the C++ 17 Standard then you also can write #include <iterat...
68,056,421
68,056,649
Why use explicit inline when every class member function is implicitly inlined
I've been reading a c++ book, C++ Primer, and i was going through the class features and everything, and i encountered that, in a class most functions ( or every) are inline automatically. What difference does it really make? explicitly defining an inline function vs implicitly defining an inline function, we could ha...
If a definition of a member function is within the class body it is implicitly inline. If you only declare it in the class body and you place the definition outside of it you need to make it explicitly inline. This can be done in two ways: struct test { inline void foo(); }; void test::foo() { } Or struct test { ...
68,056,465
68,057,104
Getting the Error "reference to non-static member function must be called "
I am solving a problem on LeetCode to make a pair sort and give the output basically link - https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/ this is my code class Solution { public: bool sortbysec(const pair<int,int> &a, const pair<int,int> &b) { if(a.first == b.first...
You cannot pass a non-static member function to std::sort in that way because it would need an instance of Solution to call it on. Fortunately, the solution in this case is simple: since sortbysec doesn't reference any member variables, you can declare it static: static bool sortbysec(const pair<int,int> &a, ...
68,056,645
68,057,076
How can you get a "x" element from rand()?
I have a rand number generator. Now my question is how do I get for instance the first/second/third/fourth digit of the generated random number. Implementing this so the user can use a hint when guessing the number. example: result(rand): 9876 print hint 1: second number 8 print hint 2: fourth number 6 Whats the best w...
You have two options for solving this problem: Create one random number between 0 and 9999 and then calculate the individual digits. Create four random numbers between 0 and 9 which represent the individual digits and then, if necessary, calculate the whole number from the individual digits. Normally, doing option ...
68,056,770
68,056,813
why does it go into an infinite loop?
I am a beginner. This is a program to print a right angled triangle.The height and base should same. for example if input n = 3 then we should get the output as. * * * * * * I wrote the following code for this: #include<iostream> using namespace std; int main(){ int n; cin>>n; for(int i=1;i<=n;i++){ ...
You are decrementing i in while loop and incrementing in for loop. Use separate variable j. using namespace std; int main(){ int n; cin>>n; for(int i=1;i<=n;i++){ int j = i; while(j>=1){ cout<<"*"; cout<<" "; j--; cout<<j; } co...
68,057,969
68,058,079
C++ class const member intialization within constructor body
I have a problem with initialization of a const class member. I have to do many calculations before initialization of the const member, so I can't use this syntax Class::Class(int value) : value(value) {} I wish to initialize the member in the constructor body, for example: Class::Class(int value) { if (Function1(va...
Collect all the calculation into a static calculation function. struct Class { static int calcValue(int value) { if (Function1(value) { Function2(&value); return value; } return value * 2; } Class(int val) : value(calcValue(val)) {} };
68,058,071
68,062,475
replacing matrix of indices with corresponding vector with armadillo
I have an arma::umat matrix containing indices corresponding to an arma::vec vector containing either 1 or -1: arma::umat A = { {8,9,7,10,6}, {5,3,1,2,4}}; arma::vec v = {-1, 1, 1, 1, -1, -1, 1, -1, -1 ,1}; I would like to replace each element in the matrix with the corresponding value in the vector, so the output loo...
Saving the result into A is not an option, since A contains unsigned integers, and your v vector has doubles. Just create an arma::mat to contain the result and loop for each row to index v accordingly. One way to do this is using .each_row member. #include <armadillo> int main(int argc, char *argv[]) { arma::umat...
68,058,083
68,058,167
Static variable used in a template function
I am not able to understand the output of the below code:- #include <iostream> using namespace std; template <typename T> void fun(const T&x){ static int count = 0; cout << "x = " << x << " count = " << count << endl; ++count; return; } int main(){ fun(1); fun('A'); fun(1.1); fun(2.2); return 0; } Output:- x ...
When a template gets instantiated, with explicit or deduced template parameters, it's as if a completely new, discrete, class or function gets declared. In your case, this template ends up creating three functions: void fun<int>(const int &x) void fun<char>(const char &x) void fun<double>(const double &x) It's impor...
68,058,116
68,098,308
Cant find SDL.h - Windows, MingW, Cmake and SLD2 (in VSCode with CPP)
I want to add SDL2 to a Cmake Project, using C++ in VSCode on Windows, but using Mingw64 from Msys2 (g++). This is my current CMakeLists.txt: cmake_minimum_required(VERSION 3.5) project(TileGameStudio_Runtime LANGUAGES CXX) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED O...
I updated my CMakeLists.txt, cause i reinstalled the whole msys2 (since of a installation problem). This is the new One: cmake_minimum_required(VERSION 3.5) project(TileGameStudio_Runtime LANGUAGES CXX) set(CMAKE_CXX_FLAGS -v) set(CMAKE_VERBOSE_MAKEFILE ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_CXX_STANDARD 20)...
68,058,392
68,058,735
C++ Builder 10.3 can not assign to const wchar_t* from const char[18]
I have a simple code for directories handling, and here is a part of it. The problem is, that in older version of builder(I guess it is 6) it was working perfectly, now it throws [bcc32c Error] Unit1.cpp(32): assigning to 'PCZZWSTR' (aka 'const wchar_t *') from incompatible type 'const char [18]'. void __fastcall TForm...
You are using the TCHAR-based version of SHFILEOPSTRUCT, so its string fields will be based on either wchar_t or char depending on whether UNICODE is defined or not, respectively. In C++Builder 6 (where String was an alias for AnsiString), UNICODE was not defined by default. In C++Builder 2009 onward (where String is a...
68,058,640
68,058,763
Using concepts to select class template specialization
This question demonstrates how to use C++20 concepts to choose overloads for a function template. I'm trying to do something analogous: choose specializations for a class template. I'm starting with a class template for Angle<T> which wraps a floating point value containing an angle in radians. Using concepts, I can...
You say template<typename T> // requires (std::integral<T> || std::floating_point<T>) // optional struct Angle; template<std::integral T> struct Angle<T> { T m_degrees; }; template<std::floating_point T> struct Angle<T> { T m_radians; }; The template needs to be declared with a big enough domain to contain all of its ...
68,058,821
68,061,198
Why does std::sin() work in the CUDA kernel?
The following code compiles (with nvcc test.cu -o test) and runs without error, meaning that std::sin() does work on the device: #include <cmath> #include <vector> #include <cassert> #include <numeric> __global__ void map_sin(double* in, double* out, int n) { const int i = blockIdx.x * 512 + threadIdx.x; if (i < n...
Is std::sin() somehow marked __device__ when compiling with nvcc? No. It is apparently replaced with sin by the CUDA front end parser in the code which is passed to the GPU compiler, and then the normal overload mechanism is used to ensure the correct GPU math library function is substituted. The code which the GPU ...
68,058,981
68,059,029
Making a separate thread for rendering made my code slower
I had a method called run in which I am updating and rendering the game objects. void Run(olc::PixelGameEngine* pge) noexcept { Update(pge); Render(pge); } Frame rate then was fluctuating 300~400 frames in release mode and 200~300 frames in debug mode. I have yet to add lodes of game logic, so I thought I woul...
std::thread creates a thread. renderer.join() waits until the thread has finished. Basically the same logic as your first example, but you create and destroy a thread in your 'loop'. Much more work than before, not surprising that the framerate goes down. What you can do: define two functions, one for the update and o...
68,059,064
68,059,249
strange function-like syntax in c and c++
The following compiles: main() { int(asdf); } It seems this is some strange kind of declaration. I have tried to find code like this, but was unable to. Could someone explain?
It turns out the line int(asdf); is equivalent to int asdf; which obviously declares an ordinary local variable named asdf. But you can put parentheses around various parts of the declarator, whether you need to or not. So it's just the same if you write int asdf; or int (asdf); or int ((asdf)); Parentheses are a...
68,059,617
68,059,660
Why does 'std::function<void()>' take a lambda returning 'bool' without any warning?
#include <functional> void f() { // warning: return-statement with a value, in function returning 'void' return true; } std::function<void()> fn = [] { return true; }; // no warning int main() {} Why does std::function<void()> take a lambda returning bool without any warning?
Because that's how it's designed. If the return type in the template argument is void, it ignores the return type of the functor. This is in line with how std::is_invocable_r works. Also, it would be hard for a (non-magical) class to emit a warning. (Unlike failing with an error, which is easy.) Not to mention that the...
68,059,855
68,059,902
Map enum values to corresponding types with templates at compile time?
I have an idea of mapping enum values to corresponding data types, at compile time with templates. How can i do this? e.g. enum DataType { UNSINGED_INT; // uint32_t INT; // int32_t UNSIGNED_CHAR; // uint8_t CHAR; // int8_t } auto type = MapToDataType<DataType::UNSIGNED_CHAR>; // type will be uint8_t in this c...
Declare the enum class. Use class to avoid namespace pollution. #include <cstdint> enum class DataType { UNSIGNED_CHAR, UNSIGNED_INT, CHAR, INT }; Specialize a template for each enum entry: template <DataType> struct MapToDataType_t; template <> struct MapToDataType_t<DataType::UNSIGNED_CHAR> { using ...