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
67,736,513
67,737,695
How to use a shorter name for `setw`, `setprecision`, `left`, `right`, `fixed` and `scentific`?
I would like to use these STL functions in my code, but so many times that their presence makes the readability of the code cumbersome. Is there any way to define "aliases" for these commands?
iomanipulators are functions and to most of them you can easily get a function pointer (actually I didn't check, but for example having several overloads or function templates, would make it less easy): #include <iostream> #include <iomanip> int main(){ auto confu = std::setw; auto sing = std::setprecision; ...
67,737,674
67,805,938
pugixml - check if node exists or not
I get a child node this way: pugi::xml_node child = root.child("aaa") I would like to check if that child node exists. Should I just call child.empty() ?
The xml_node class has a logical bool operator overload that allows you to check that it exists by simply calling if (child) { ... } and similarly an operator! for checking if it doesn't exist with if (!child) { ... }
67,737,732
67,742,446
Can i store 2 * 12bit unsigned numbers in a file as 3 bytes in C++ using bit fields?
I`m working on an LZW compression app in C++. Since there are no data types that can store 12 bit numbers for representing table elements up to 4095 I thought that I can store 2 of those nrs as 3 bytes in a file and then read them as a struct with 2 unsigned short members. Is there a way to do that or I should just use...
Your question title and question body are two different questions with different answers. No, you absolutely cannot store 3 * 12-bit unsigned numbers (36 bits) in four bytes (32 bits). Yes, you can store two 12-bit numbers (24 bits) in three bytes (24 bits). The bit fields in C++, inherited from C, that you are trying ...
67,738,142
67,738,209
How do I send an operator into std::async?
I have currently a working example: #include <iostream> #include <future> int main() { auto result = std::async([](int left, int right){return left + right;}, 1, 1); std::cout<<"from async I get "<<result.get()<<"\n"; return 0; } This lambda does nothing but a simple addition, but I just fails to replace ...
You cannot have a reference or function pointer to a builtin operator see here, but you can use one of the utilities in the <functional> header: auto result = std::async(std::plus<>{}, 1, 1); If you're obsessed with passing a reference to an operator, you can have that with a wrapper type: struct Int { int value; }; ...
67,738,393
67,738,637
Nested class template type alias
This might be an easy question, but I can't seem to figure out the syntax to define a type alias for nested class templates. Basically, I have: template<class T> struct Outer { template<class U = T> struct Inner {}; } I want to be able to access the Inner class as a type from outside the class definition. I've...
You need extra template: template<class T, class U = T> using Inner = typename Outer<T>::template Inner<U>; Demo
67,738,633
67,739,092
Convert C++ code to x87 inline assembly code
I am trying to convert C++ code into x87 style inline assembly code. C++ code: double a = 0.0, b = 0.0, norm2 = 0.0; int n; for (n = 0; norm2 < 4.0 && n < N; ++n) { double c = a*a - b*b + x; b = 2.0*a*b + y; a = c; norm2 = a*a + b*b; } inline assembly code: double a = 0.0, b = 0.0, norm2 = 0....
There's a lot to improve with this one. Here are some points to start with: Do not program in MSVC-style inline assembly MSVC-style inline assembly may be easy to program in, but it also forces all variables to live in memory. Every time you read from or assign to one of your variables, a slow memory access is perfor...
67,738,672
67,738,766
Take only one value from variadic
I want to ask through this simple example: how could I take the last value from a variadic pack and print(1, 2, 3.14) to call print(3,14)? void print() { cout<<"--empty--"; } void print(x) { std::cout<<"Last Value from variadic pac--" << x; } template <typename T, typename... Types> void print(T var1, Ty...
With std::tuple, you might do template <typename T, typename... Types> void print(T var1, Types... var2) { auto x = std::get<sizeof...(Types) - 1>(std::tie(var2...)); print(x); // 3.14 } Demo
67,739,877
67,746,628
How to view the SQLite query that is reaching the .db/.sqlite file from my application?
I know that SQL Server has many tools including profilers and some tools that connect to the db and allow you to view the queries that reach it and the values that are then returned. In my Qt Desktop app, upon clicking a button, a query is prepared, values are bound and it is executed, but the results are wrong. Intere...
You can use sqlite3_expanded_sql() to see the query a prepared statement is executing, including the values bound to parameters in the query. Example: #include <iostream> #include <sqlite3.h> int main(void) { sqlite3 *db; if (sqlite3_open(":memory:", &db) != SQLITE_OK) { std::cerr << sqlite3_errmsg(db) << '\n'...
67,740,120
67,740,148
C++: Solution to this floating point error problem?
This is an example of my code: float a = 0.f; float b = 5.f; float increment = 0.1f; while(a != b) a+=increment; This will result in an infinite loop. Is there any solutions to it, or the only way to solve this is to set a tolerance?
Avoid using floating-point calculation when possible. In this case you can treat with the numbers as integer by multiplying them by 10 and dividing by 10 in the end. float a, b, increment; int a_i = 0; int b_i = 50; int increment_i = 1; while(a_i != b_i) a_i+=increment_i; a = a_i / 10.f, b = b_i / 10.f; increment =...
67,740,486
67,740,870
Trying to overload operator<< in template class
(this is an old exam for my current course) I'm trying to overload operator<< in a template class but when I compile the code and run the program i get this message: /usr/bin/ld: /tmp/cc2BvB2u.o: in function `main': /home/user/Skola/TDDI82/TENTA2017_1/UPPGIFT4/main.cpp:30: undefined reference to `operator<<(std::ostrea...
There are few problems with your code. Missing Constructor template<typename T> Wrapper<T>::Wrapper(T const& w): value(w){ } Wrapper<T>::Wrapper is a constructor is just nothing meaningful. Wrapper<T>::Wrapper doesn't raise any error because of SFINAE std::ostream& operator<<(std::ostream& os, Wrapper<T> const& w)...
67,740,534
67,741,678
Avoid multiple copy of data when composing objects at construction without dynamic allocation
We have hierarchical messages that are represented by classes. They are used to send messages between threads and components by serializing/deserializing. In our use-case, we use std::variant<InnerA, InnherB, ...>, but to simplify, our code is similar to this: class Inner { public: Inner(uint8_t* array, uint16_t ...
You can use inplacer (see this post). Your code will look like this: #include <type_traits> #include <array> #include <cstdint> #include <cstring> using namespace std; template<class F> struct inplacer { F f_; operator std::invoke_result_t<F&>() { return f_(); } }; template<class F> inplacer(F) -> inplacer...
67,740,674
67,741,818
redefining a macro not working as expected
I am in C++ defining blocks that go in a special area of memory. I want to define a block, then define the address of the next block in a variable that gets redefined for each block. #include <iostream> using namespace std; #define BASE_ADDRESS 0X1000 // type a gets 100 bytes #define TYPE_A BASE_ADDRESS #define NEXT...
Lets take a look at this example: #define MYMACRO 0 //MYMACRO = 0 #define ANOTHERMACRO MYMACRO //ANOTHERMACRO = MYMACRO = 0 int main() { return ANOTHERMACRO; } All good right? But if we do this: #define MYRECURSIVEMACRO 0 //MYRECURSIVEMACRO = 0 #define MYMACRO MYRECURSIVEMACRO //MYMACRO = MYRECURSIVEMACRO #unde...
67,740,782
67,741,208
C++ smart pointer auto free for dynamic array
I want to auto free my dynamic array. #include <iostream> #include <memory> void myFunction(int* arg) { // do something without delete } int main () { int* l_pBuffer = new int[8]; std::unique_ptr<int[]> l_autoFree(l_pBuffer); //<--- option 1 std::unique_ptr<int> l_autoFree(l_pBuffer); //<--- option...
Yes, you need to use std::unique_ptr<T[]> when using an array allocated with new[]. Otherwise, the array will not be freed correctly. A better option is to use std::make_unique<T[]>() instead, or even a std::vector.
67,740,941
67,754,261
Creating a template class and using it for returning pointers from a derived class
Introducing my issue with some comments. Each comment refers to the code below: comment1: myShapeVector stores Shape* comment2: Adding up the vector either with with circle or rectangle objects comment3: The returnPtr() member function is intended to be used for returning either a Circle* or an Rectangle* depending o...
Finally I found a very simple solution, which differs from my specifiations in the beginning and thats maybe why it was confusing. No need of template class, type casting, virtual inheritance etc. Anyhow I would like to post a way to do it: comment1: Instead of having one vector and storing derived class objects. I j...
67,741,676
67,773,627
A friend function accessing a private member of a friend class
Following the Czech song from Eurovision 2019 in Tel-Aviv It is known that in C++ a friend of a friend is not (automatically) a friend. Clang however differs on the following code with GCC and MSVC: class A { public: // forward declaration class Inner2; private: class Inner1 { char foo; ...
It seems to be a known defect in clang, bug id #11515, reported already in 2011, but still not fixed, apparently. An even simpler example that compiles, and shouldn't (from the bug report above): class A { int n; friend struct B; }; struct B { friend int get(A &a) { return a.n; // clang accepts, and should r...
67,741,949
67,742,524
Can can I make `std::ranges::views::elements` work with a range of my type
Consider a Point type with x, y and z values. If I have a range of Point objects, such as std::vector<Point>, what do I need to add to Point to make it work with the std::ranges::views::elements range adaptor? The intention is to do something like std::vector<Point> v{...}; for (auto x : v | std::ranges::views::element...
Can can I make std::ranges::views::elements work with a range of my type No, you can't†. The way that elements is specified, in [range.elements.view], it's constrained on: template<class T, size_t N> concept has-tuple-element = // exposition only requires(T t) { typename tuple_size<T>:...
67,742,162
67,742,283
Could std::vector<bool>::iterator implement its deref operator to return a reference to _Bit_reference?
Looping over std::vector<bool> in a range-based-for for altering the data, requires using either forwarding reference or just value type: std::vector<bool> bv(5); bool val = true; for(auto&& b : bv) { b = val; val = !val; } Or: std::vector<bool> bv(5); bool val = true; for(auto b : bv) { b = val; // yes, t...
vector<bool> does not contain Bit_reference or any other such types. And vector<bool> is required to be a multipass range. This means that whatever operator* returns, it can't be a reference to something stored in the iterator, since you can increment the iterator and still access the reference the previous value of th...
67,742,421
67,745,976
Implementing asynchronous delays
What would be a smart way to implement something like the following? // Plain C function for example purposes. void sleep_async(delay_t delay, void (* callback)(void *), void * data); That is, a means of asynchronously executing a callback after a delay. POSIX, for example, has a few functions that do something like t...
The simple but inefficient way would be to spawn a thread, have it sleep for delay, and then call the callback. This can be done in just a few lines using std::async(): auto delayed_call = std::async(std::launch::async, [&]{ std::this_thread::sleep_for(delay); callback(data); }); As mentioned by Thomas Matthew...
67,742,697
67,742,777
no suitable constructor exists to convert from "int()" to "std::function<int()>"
I am trying to pass two functions OnUserCreate and OnUserUpdate as parameters to another function which is then supposed to call them. However, I am getting an error saying no suitable constructor exists to convert from "int()" to "std::function<int()>" Here is a reproducible example that vaguely mimics my code. //ERRO...
You are trying to pass non-static class methods, which require an object instance to call them on. But you are not specifying that object. Try this instead: void Run() { win.ProcessMessage( std::bind(&App::OnUserCreate, this), std::bind(&App::OnUserUpdate, this) ); } Demo Alternatively: void R...
67,743,245
67,745,884
Dynamic Range Sum Queries
I was solving a CSES problem. It's a simple, Fenwick tree problem, and I write the code, which works perfectly on smaller inputs but giving wrong answers for larger inputs. the problem link: https://cses.fi/problemset/task/1648/ my solution to the problem: #include <bits/stdc++.h> using namespace std; typedef long long...
You ask what you are doing wrong, so here I go: You use #include <bits/stdc++.h>: Why should I not #include <bits/stdc++.h>? You use using namespace std;: Why is "using namespace std;" considered bad practice? You use typedef long long ll; which just obfuscates your code. You use global variables and fixed length arra...
67,743,302
67,743,445
what is difference between int32_t main() and int main()
I've seen some people use int main() for the main function while some use int32_t main(). What is the difference between both and where to use which.
(This answer is for C.) For a hosted C implementation (in contrast to a “freestanding” or “embedded” implementation, the 2018 standard says, in 5.1.2.2.1 1 that main shall be defined with a return type of int, except that an implementation may define other acceptable definitions. Specifically, it just says the return t...
67,743,353
67,743,585
How to add C++ flag -Wno-unused-function on cmake?
I added on my CMakeLists.txt on Android: SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable -Wno-unused-function -Wno-error") but I get multiple errors like this: error: unused function 'createParserError' [-Werror,-Wunused-function] There's nothing that could rewrite CMAKE_CXX_FLAGS.
With modern cmake, you can use add_compile_options and target_compile_options instead of setting the variable directly Thus in your context you can write add_compile_options(" -Wno-unused-variable -Wno-unused-function -Wno-error") to add the compile options to all targets or simply target_compile_options(LIBRARY_NAME ...
67,743,697
67,743,753
How can (x+1) > x evaluate to both 0 and 1?
I was learning about undefined behaviour and stumbled upon this code without any clear explanation: #include <stdio.h> #include <limits.h> int foo ( int x) { printf ("% d\n" , x ); //2147483647 printf ("% d\n" , x+1 ); //-2147483648 overflow return ( x+1 ) > x ; // 1 but How???? } int main ( voi...
When a program exhibits undefined behavior, the C standard makes no predictions regarding what the program will do. The program may crash, it may output strange results, or it may appear to work properly. In fact, compilers will often work under the assumption that a program does not contain undefined behavior. In the...
67,743,776
67,755,502
Identifying whether a PCI device is PCI or PCIe
I need to be able to identify whether a given PCI device is express or non-express at runtime. One possible way to ID this is to get the Configuration space and check for an extended section. If the extended section exists then it's a PCIe card. Specifically i would check the first four bytes to see if they are 0x100 a...
I think the best way is to look for the PCI Express capability, which is in the regular capability space, not the extended space. The presence of this capability indicates a PCIe device. The capability ID is 0x10.
67,743,844
67,743,991
Is the `const` keyword used in function declaration, or definition or both?
void test(int& in); void test(const int& in){ } int main(){ int a = 5; test(a); return 0; } Above doesn't compile with a link error: undefined reference to `test(int&)'. I have 3 questions on this: 1- Why do we get a link error? is it because adding const to the definition makes it a completely different functi...
In C++ the two functions: void test(int& in); void test(const int& in); are TWO different, overloaded functions. The first binds to "writeable" integers, the second - to constant ones. In your code: int a = 5; test(a); a is a modifiable object, hence void test (int &) is a better match from compiler perspective and ...
67,744,499
67,744,714
Why does this code using designated initializers in function parameters goes from ambiguous to not compiling when removing one function?
Consider the following code: struct A{ int x; int y; }; struct B{ int y; int x; }; void func (A){ } void func (B){ } int main() { func({.y=1,.x=1}); } For some reason both clang and gcc consider this code ambiguous even though it is known that order in designated initializer must match the order ...
The rule is in [over.ics.list]/2: If the initializer list is a designated-initializer-list, a conversion is only possible if the parameter has an aggregate type that can be initialized from the initializer list according to the rules for aggregate initialization ([dcl.init.aggr]), in which case the implicit conversion...
67,745,060
67,745,563
Segmentation fault when passing array of pointers to function
I am currently working on a homeworking question and I have been trying to figure out why I keep getting a segmentation fault (core dump). I have narrowed it down to accessing an array within a function. The goal of the program is to store words from a book in a separate chaining hash table. And we can't use STL. The a...
Thanks to both @AlanBirtles, @user4581301, and @tadman for the answers that they provided. It turns out that I had not initialized the nodes within the array to anything, so a simple for loop going through the hashTable array and setting everything to nullptr, along with the suggestions from the aforementioned users fi...
67,745,103
67,745,197
How to pass variadic function parameters to another function in C++ (specifically std::format)?
I'm trying to write a logger that can take arguments the same way that printf does with formatting supported. I'm planning to just call std::format on the input to my logger, but I need to forward the variadic args to std::format. How can I do that? What I want it too look like: void log(const std::string& msg) { std...
You don't want the C-style ... parameter. You want a variadic template: template <typename T, typename ...P> void log(T &&format, P &&... params) { std::string msg = fmt::format(std::forward<T>(format), std::forward<P>(params)...); std::cout << msg << '\n'; } Notice forwarding references for the parameter, pac...
67,745,117
67,748,661
Using std::experimental::filesystem with g++ 9.3.0
I'm using VS2015 as my main developing tool and to use std::filesystem there I need to write something like this: namespace fs = std::experimental::filesystem; Now I need to compile this code using g++ 9.3.0 and, of course, get an error about "experimental" part. Is there a way to keep this oldy thing in my code and co...
I would use the version of C++ standard in combination with a pre-processor directive to distinguish between them as it the filesystem library has been officially introduced in C++17 #if __cplusplus >= 201703L #include <filesystem> namespace fs = std::filesystem; #else #include <experimental/filesystem> namespa...
67,746,273
67,753,323
Shared library symbol lookup template instantiation
I'm using a shared library utility that looks up symbols from a shared library (on non-windows platforms using GetProcAddress). This works for normal functions. However, I need a function that is a template instantiation in a namespace. I have confirmed using nm -gDC lib.so that the library contains the symbol and spel...
I have confirmed using nm -gDC lib.so that the library contains the symbol and spelled it exactly the same in my lookup attempt but it can't be found. As Igor Tandetnik correctly commented, the name the library actually exports is the C++ mangled name, and not rosidl_typesupport_cpp::get_service_type_support_handle<e...
67,746,351
67,928,560
Why CreateFileMappingA and CreateFileA uses different return values on error?
Both CreateFileMappingA and CreateFileA returns HANDLE type, but CreateFileMappingA returns NULL on error, and CreateFileA returns INVALID_HANDLE_VALUE instead. I'm wondering why the API is designed like that, why won't those APIs both use NULL or INVALID_HANDLE_VALUE?
As explained by Raymond Chen in Why are HANDLE return values so inconsistent?: Why are the return values so inconsistent? The reasons, as you may suspect, are historical. The values were chosen to be compatible with 16-bit Windows
67,746,381
67,746,417
What is the following command "typedef mpc_val_t*(*mpc_apply_t)(mpc_val_t*);"
Can someone provide an explanation of the following command? typedef mpc_val_t*(*mpc_apply_t)(mpc_val_t*);
This is a type definition for mpc_apply_t, defining it as a pointer to a function accepting a pointer to a value of type mpc_val_t, and returning a pointer to a value of type mpc_val_t. The type mpc_val_t is defined elsewhere.
67,746,832
67,746,898
How does a struct pointer differentiate between the use of the same pointer?
This is an example from geeks for geeks. The last example is root->left->left = new Node(4); I was wondering how the left node retains its old value, and is able to connect to a new value using the same struct variable. Is each time the "new Node()" being called its creating another block of memory or what? I am confu...
root->left = new Node(2); and root->left->left = new Node(4); both create new Node objects in memory so you're question Is each time the "new Node()" being called its creating another block of memory or what? is somewhat accurate. Initially, root is a Node object with a data value of 1 and a left value of NULL. It's...
67,747,029
67,747,078
Not sure why I can't convert from string to int?
string typeVisa (string str); int main(){ string credit_card; string type; getline(cin, credit_card); type = typeVisa(credit_card); } string typeVisa (string str){ int digit1; int digit2; digit1 = atoi(str[0]); digit2 = atoi(str[1]); // code continues and...
If you want to convert each digit separately, you write something like below //Instead of this: digit1 = atoi(str[0]); digit2 = atoi(str[1]); //use this: digit1 = (int)str[0] - '0'; digit2 = (int)str[1] - '0'; PS: you might need add validation for passed string is numeric.
67,747,489
67,747,518
What would declaring a pointer with the "new" operator within a while loop do to my computer?
So I recently got into learning C++ and I was really intrigued by memory allocation, garbage collection, heap, stack, etc... I wrote this program, and I was wondering what it would do to my computer? Would it crash because my RAM would get filled up? Would it run slower? Would it stop before it fills up too much ram? I...
first thing you will face with is memory leak. but your programme will continue to allocate memory from heap and will face with memory leak but OS will stop your programme. there is concept in OS named OOM. in this concept if some programme continue to allocate memory and cause some important part of system goes down O...
67,747,499
67,747,584
How to Fix "End of File Expected" JSON Settings VS Code?
{ "workbench.colorTheme": "Default Dark+" } { } "name": "C++ Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/a.out", "stopAtEntry": false, "customLaunchSetupCommands": [ { "text": "target-run", "description": "run target", "ignoreFailures": false } ...
What you have posted is not valid json. You've got several typos including: An empty empty set of curly braces {} on line 7, followed by several key value attribute pairs not enclosed in curly braces. This might be closer to what you want: { "workbench.colorTheme": "Default Dark+", "name": "C++ Launch", "type"...
67,747,715
67,753,054
How to represent the elements of the Galois filed GF(2^8) and perform arithmetic in NTL library
I am new to NTL library for its GF2X, GF2E, GF2EX, etc. Now, I want to perform multiplication on the Galois field GF(2^8). The problem is as following: Rijndael (standardised as AES) uses the characteristic 2 finite field with 256 elements, which can also be called the Galois field GF(2^8). It employs the following r...
Again, I don't know NTL, and I'm running Visual Studio 2015 on Windows 7. I've downloaded what I need, but have to build a library with all the supplied source files which will take a while to figure out. However, based on another answer, this should get you started. First, initialize the reducing polynomial for GF(256...
67,748,038
67,748,175
Splitting an Unsigned Long in C++
I have an hexadecimal number 0x5ED3710573047010 which I want to split in two parts equally.Should I convert it into a string and split the string then convert the two strings back to an Int and store it in two separate variables? or there is some easy and quick way to do it using some kind of bit shifting or maths?
You could use masking and bit operations. unsigned int first_half = (my_long & 0xffffffff00000000) >> 32; unsigned int second_half = my_long & 0x00000000ffffffff;
67,748,817
67,748,883
mpz_set_str outputting 0 after assigning it to a number
It seems very odd that my code doesn't work, I am trying to take input from a user, and assign it to a mpz_t for a later calculation, however, just doing a simple test does not give me the expected result. mpz_t n; mpz_init(n); const char* num = "25.5"; mpz_set_str(n, num, 10); mpz_out_str(stdout, 10, n); printf("\n");...
mpz_t is an integer. "25.5" is not an integer. That's why mpz_set_str() fails for "25.5" but not for "25" as you pointed out. mpf_t is a floating point value, you can use mpf_set_str() to set it to "25.5".
67,749,350
67,750,107
C++ : How can I parallelize an n-ary operation on n ranges?
A binary operation in two ranges can be parallelized in this way: #include <cassert> #include <algorithm> #include <vector> #include <execution> std::vector<int> add(const std::vector<int>& A, const std::vector<int>& B) { assert(A.size() == B.size()); std::vector<int> C; C.reserve(A.size()); std::trans...
If you have a nested for loop, and want to convert that to using STL algorithms, then generally the trick is to nest STL algorithms. If you wanted to sum each row, then the for loop would look like: for (auto row: Rs) { int sum = 0; for (auto col: row) sum += R; res.push_back(sum); } And then the c...
67,749,456
67,749,623
The loop exits only after one of the iterator has reached the end. What is wrong here?
I have a simple for loop in c++ int makeAnagram(string a, string b) { int deletionCnt = 0; sort(a.begin(), a.end()); sort(b.begin(), b.end()); string::iterator itrA = a.begin(); string::iterator itrB = b.begin(); for (itrA; (itrA != a.end() && itrB != b.end()); itrA++) { if (*itrA < *itrB) { ...
Your code is functioning properly. The condition for loop termination is itrA != a.end() && itrB != b.end(). If either iterator has reached its end, the and clause will return false and the loop will terminate. If you want the loop to terminate when both iterators are at their end, you could use a condition like !(itrA...
67,749,478
67,749,686
Does a std::vector<std::unique_ptr<T>> with each individual unique_ptr vector item cache-line aligned make sense in order to avoid false sharing?
Assuming such vector is std::vector<T, boost::alignment::aligned_allocator<T, 64>> would be read/write accessed by several cores concurrently and having it allocated on a per-core basis (i.e. vector index 0 used by the CPU core 0 only, 1 by the core 1, and so on), if one wants to avoid false-sharing, the underlying T h...
If you want to be able to modify the pointer, then yes, you should ensure the pointers themselves are aligned. However, if the pointers are never changed while your parallel code is running, then they don't have to (it's fine to share read-only data among threads even if they share cache lines). But then you have to ma...
67,749,670
67,751,952
How does static_cast<type&&>(x) convert l valued r-value reference to x value type what is the internal logic?
I read std::move() does the same thing*
[expr.static.cast]/1 The result of the expression static_cast<T>(v) is the result of converting the expression v to type T. If T is an lvalue reference type or an rvalue reference to function type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a ...
67,749,677
67,749,828
return in functions with std::async
I have a function that should always return A[0][1]. But I use std::async and gcc says: test_fibonacci_method/1/main.cpp:147:1: warning: control reaches end of non-void function [-Wreturn-type] Integer Fib_iterative_n_Matrix(const unsigned& n) { if (n < 2) return n; // Fib(0):=0 and Fib(1):=1 std::array<std::...
OK, I understand now that the if is unnecessary. And a.get() is also to much, because the result of the lambda is not used a.wait() is better. Integer Fib_iterative_n_Matrix(const unsigned& n) { if (n < 2) return n; // Fib(0):=0 and Fib(1):=1 std::array<std::array<Integer,2>,2> A = {1,0,0,1}, FIB = {1,1,1,0}; ...
67,749,834
67,749,969
Why isn't std::vector::at a const function?
I'm trying to implement std::vector but I encountered the question. According to C++ reference, std::vector::at is like: reference at (size_type n); const_reference at (size_type n) const; My question is: Why don't I use reference at (size_type n) const;? Thank you for any help or criticism! Update: Thanks! I'm...
Think about the issue that a ref at (size_type n) const; could cause. First of all, you need to understand why const_reference at (size_type n) const; exists. In a const std::vector, once it is initialized, it or its elements are not supposed to be changed (because it is, after all, const). The normal reference at (siz...
67,749,999
67,750,376
How can i detect if a point is in a polygon with Boost Within
I'm trying to detect every coordinates possible for my polygon. (it's not everytime a triangle, it's for that).But when i'm trying to check every x & y possible, my program is not working at all. I'm using https://www.boost.org/doc/libs/1_62_0/libs/geometry/doc/html/geometry/reference/algorithms/within/within_2.html He...
Geometry of polygon is not valid. Model polygon reference Template parameter(s) bool Closed Default true You can check if a geometry is valid by boost::geometry::is_valid, for your polygon it returns false. You may add the last point: "POLYGON((375 200,700 900,1100 190,375 200))" or call boost::geometry::correct(poly...
67,750,230
67,750,344
How can I change build tools for projects in VS Code?
I want to build a C++ code but it errors. When I check the error message it's related with .NET. I have C# extensions but this isn't C# and I want to change this to g++ for C++ projects. I have g++ installed and added to path however I don't know how can I configure it to build with that for C++ codes. Edit: I marked t...
One option (probably not the one you want to) is to build it from integrated terminal. You can download c/c++ extension along with the cmake tools extension to have buttons for build/run configuration.
67,750,652
67,750,782
Constructor - Copying Const Reference VS Moving Copied Value
I couldn't find the answer so I'm asking it here. What's the difference between THIS: class Foo { public: Foo(std::string string) : m_String(std::move(string)) {} private: std::string m_String; } And THAT: class Bar { public: Bar(const std::string& string) : m_String(string) {} private: ...
Don't use strings but a type where you can observe copying and moving: #include <iostream> struct test { test() { std::cout << "constructor\n"; } test(const test&) { std::cout << "copy\n";} test(test&&) { std::cout << "move\n"; } }; class Foo { public: Foo(test t) : t(std::move(t)) {} private: ...
67,750,985
67,751,641
Getting the length of an array of undetermined size at compile time
I was just messing around with Compiler Explorer a bit... I was asking myself why there is no lenth() function in C++ to determine the size of an array at compile time, because in my opinion it should be easy to write. But apparently it's not that easy. My idea was something like this: #include <iostream> using namesp...
There is std::size(a) which does exactly the same thing as your length(a), so it's not that bad of an idea. As others have said, the function call will be removed if you enable optimizations. Also you can do std::extent_v<decltype(a)>, which should compile to nothing even without optimizations.
67,751,020
67,751,204
Is ther a way to define global constants of a certain class inside this class namespace in C++?
Imagine I have a C++ struct called Color struct Color { float r,g,b; }; and a function that accepts a Color object and does something with it: void func(const Color & color) {...} Usually, I call this function with Color objects constructed on the fly: func(Color{0.1,0.2,0.3}); But there are certain colors that ...
struct Color { float r, g, b; static const Color red; }; constexpr Color Color::red{1.0,0.0,0.0};
67,751,042
67,751,162
fatal error: string: No such file or directory #include <string>
NB, C++ beginner here, but I have reasonable experience coding in other languages (and significantly less sophisticated development environments). I am working in visual studio using visual micro to work on an arduino project. The details of the project are not important, as, at this point, I am encountering the error ...
so, the standard library is provided by the compiler. For the most popular ones, like gcc, clang, or msvc, the provided library is 99% standard compliant. But some micro controller compilers might not have STL support. Check the Arduino STL support for your compiler. And as far as I know, there's an official Arduino ID...
67,751,784
67,755,682
How to do in-place sorting a list according to a given index in C++
I have a large list of objects(struct). They have been sorted and the index have been saved in another list. How to do in-place sort according to the index? For example, FOO A[5] =[a5,a4,a8,a1,a3] int idx[5] = [3,0,4,1,2] expected results: A[5] = [a1,a5,a3,a4,a8] As the list A is very large, an in-place sorting met...
What you are looking for is called "applying a permutation" and is considered a solved problem (lucky you). Raymond has an interesting discussion about it on his blog with an in-place solution given https://devblogs.microsoft.com/oldnewthing/20170102-00/?p=95095 I've taken the liberty to adjust his solution for arrays....
67,751,906
67,752,004
Where is `class vector` implemented in libcxx?
I would like to find the implementation of class vector in libcxx. However, in the header file vector of libcxx, https://github.com/llvm/llvm-project/blob/main/libcxx/include/vector , there is only class vector defined in comment region, instead of in source region. Where is class vector really defined?
It's right there, around line 472: template <class _Tp, class _Allocator /* = allocator<_Tp> */> class _LIBCPP_TEMPLATE_VIS vector : private __vector_base<_Tp, _Allocator> { . . .
67,751,925
67,751,967
Understanding constexpr functions with templates [C++]
I am trying to learn about constexpr functions in C++. I am unable to understand what is the problem with the first function definition. All the variables, as far as I think, should be available at compile time. I am using Catch2, as the testing library. sqrtfunc.hpp #include <stdexcept> #include <numeric> template <c...
You're calling std::numeric_limits<T>::max_exponent, but it's a variable, not a function.
67,752,055
67,752,127
C++ garbage collection when array is dynamically created without 'new'
I just stumbled upon the fact that we can dynamically create arrays without 'new' (Dynamic array without new (C++)). For example, this is possible: cout<<"enter length: "; cin>>length; int a[length]; My question is: since we didn't use 'new' to dynamically allocate the memory, should we (or can we) use 'delete' in or...
In C++, there is no garbage collection. We need to delete all the items that were allocated on the heap. In your code, when you create an array without new, you don't allocate any space on the heap, you just use limited stack. You should avoid the new keyword if it isn't necessary, but if you need to use it, don't forg...
67,752,336
67,752,829
VS error from std::filesystem::u8path(const char8_t*)
In this simple C++20 program #define _SILENCE_CXX20_U8PATH_DEPRECATION_WARNING //suppress VS warning #include <filesystem> int main() { auto p = std::filesystem::u8path(u8"a"); } I get the error from Visual Studio 2019 16.10.0 in stdcpplatest mode: 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\V...
The ability for u8path to take char8_t was a relatively late addition to the C++20 standard. The error in question cites N4810, which was a draft that contains char8_t (as well as overloads for filesystem::path constructors), but the draft was written before u8path was changed to take char8_t strings. So VS simply has ...
67,752,995
67,756,965
The real purpose of C++20 keys_view and values_view?
C++20 introduced ranges::elements_view, which accepts a view of tuple-like values, and issues a view with a value-type of the Nth element of the adapted view's value-type, where N is the non-type template parameter. In [range.elements.view], the synopsis of ranges::elements_view is defined as: template<input_­range V, ...
The missing pair issue in the example is just a bug with the example; I submitted an editorial pull request. The bigger problem is with keys_view and values_view's definitions. An LWG issue has been submitted for which I have provided a proposed resolution. The basic issue here is that template <class R> using keys_vie...
67,753,044
67,753,257
Including <thread> results in the following compile error: 'fabsl': is not a member of '`global namespace'
For the long time, standard libraries were giving me headache by throwing compilation errors simply by including them. For the long time, I've gone around it by reimplementing the parts that I needed, or with some #define for cstdio. Now I need to include the library, and I don't really see any ways around it. Yet aga...
I had created a Math.h header file. Renaming it fixed the problem. It appears to be a good idea to avoid using file names from the C++ standard library, who would've said it.
67,753,048
67,753,179
Default parameter in function to a reference in c++ unordered_map
I am a JS dev and to implement this function header,I do : function gridTraveler(m,n,memo={}) Here,I know that the object would be passed by reference in JS. So in C++,I decided to do: int gridTraveler(int m,int n,std::unordered_map<int,int>& memo = {}) But I get an error : "initial reference to a non const must be a...
What you meant can probably be achieved by a two-arg overload that takes care of the unordered map lifetime. int gridTraveler(int m,int n,std::unordered_map<int,int>& memo) { //your implementation here } int gridTraveler(int m, int n) { std::unordered_map<int,int> memo = {}; return gridTraveler(m, n, memo)...
67,753,741
67,753,936
How do I properly implement "operator()" with "if constexpr" so that it works with std::generate?
I was trying to write a class that will fill a container with random numbers with the type that the container has: template<typename random_type> class rand_helper { private: std::mt19937 random_engine; std::uniform_int_distribution<int> int_dist; std::uniform_real_distribution<double> real_dist; public: ...
Your code just doesn't compile, regardless of the if constexpr. The reason you may not be getting a compilation error with just the template class is that, well, it's a template, so no actual instance of anything gets compiled. If you add: template class rand_helper<int>; which forces an instantiation for a random_typ...
67,754,260
71,239,140
How can I make emacs compile my c++ code and run it in a new window?
Is there a way I can make emacs compile and run my code in an external console window with the command M-x compile (what I mean by external console window is that I want it to run my code in a new console window like it does when I run my C++ code in visual studio). I want emacs to automatically open up a new console w...
Normally with Emacs, when you want some obscure (i.e. some simple, or special to your use case) automation, you just write a command, which does what you want. Here is such an example. Following Elisp code calls a function and-run, when compilation is finished (through using hook compilation-finish-functions). (defun a...
67,754,693
67,755,891
Asio Bad File Descriptor only on some systems
Recently I wrote a Discord-Bot in C++ with the sleepy-discord bot library. Now, the problem here is that when I run the bot it shows me the following errors: [2021-05-29 18:30:29] [info] Error getting remote endpoint: asio.system:9 (Bad file descriptor) [2021-05-29 18:30:29] [error] handle_connect error: Timer Expired ...
The error triggers when you so s.remote_endpoint on a socket that is not connected/no longer connected. It would happen e.g. when you try to print the endpoint with the socket after an IO error. The usual way to work around that is to store a copy of the remote endpoint as soon as a connection is established, so you do...
67,755,040
67,755,177
What does the (long)someFunction output?
What do these values represent or come from in the following code? 4196598 1 Why does the following code output this above: #include <iostream> using namespace std; void someFunction() { cout << "someFunction" << endl; } int main() { cout << long(someFunction) << endl; cout << someFunction << endl; ...
It's actually the location of the function (ie. the location for the instructions to be jumped to), casting it to long, gave us the number, which will likely change during multiple invocations. Debugging the same code in gdb, you can get the location in hex, like this - When you convert the hex number to a decimal num...
67,756,408
67,756,541
Copy a binary tree in a vector
I am trying to copy a binary tree in a c++ vector and i am having a kind of error that I cant find where it is generated. This i in the header file (.h) struct NyjePeme { int Key; NyjePeme *left = NULL; NyjePeme *right = NULL; }; class PemeKerkimi { private: NyjePeme *root; public: PemeKerkimi(); ~PemeKe...
You should pass vector in copyTreeinVector function by-reference. Instead of writing void copyTreeinVector(NyjePeme *T, vector<int> v) You should have written void copyTreeinVector(NyjePeme *T, vector<int>& v) Here are some additional links related to the issue. What's the difference between passing by reference vs. ...
67,756,429
67,756,633
Keyboard print UID MFRC522 Arduino Leonardo
I want to print the UID of a card as an HID with the Arduino Leonardo. Here is the code that I have void loop() { if ( mfrc522.PICC_IsNewCardPresent()) { // Select one of the cards if ( mfrc522.PICC_ReadCardSerial()) { // Dump debug info about the card; PICC_HaltA() is automatically called mfrc52...
I believe that the isse you are facing is that you are trying to print a MFRC522::Uid which is a HEX number such as 00 00 00 00 while the keyboard.print() only accepts char, int or string according to: Arduino.cc. I found the following code snippet here. I believe it might resolve your issue. It should write: "Card UID...
67,756,436
67,757,082
expected primary-expression before ‘...’, c++ compile error
There are quite a few posts on SO with similar titles, but they seem to be triggered by various syntactic errors and I didn't see a consistent pattern yet.. using namespace std; class A { public: A(int a_) : a(a_) {} int a; }; int main() { A x{3}; A y{0}; if ((y=x).a) cout << y.a << endl;...
Am I wrong to assume A z = x is an assignment expression Yes, you are wrong. There is no assignment going on here. The = in this statement represents initialization, not assignment. The statement A z = x; defines the variable z, where z is constructed from x. The copy constructor is used here, not copy assignment. It...
67,756,530
67,756,585
Best substitute for goto in C++ as beginner for use in text-based RPG
I am very new to C++ and have decided to start with a basic text based RPG. I have been using this site as a reference; https://levelskip.com/classic/Make-a-Text-Based-Game#gid=ci026bcb5e50052568&pid=make-a-text-based-game-MTc0NDU2NjE2MjQ1MDc3MzUy system("cls"); int choiceOne_Path; cout << "# What would you like to do?...
Best substitute for goto retry: // accept input if (/* input predicate */) { // ... } else { // ... goto retry; } That's what we in the trade call a "loop". Any flavor of loop structure is fine for this example, but this is a rare case where do-while is nice. A direct transformation: do { // accept i...
67,756,555
67,756,702
Can std::transform() be made exception-ignorant?
This is probably an AB mistake on my part. While reading my dataset usually some files are NOT a part of it. I want to be robust against that - to just ignore them, simply log the omission. But I am in love with exceptions thus Spectrum read_csv( const fs:path & dataset ); throws. I want to keep it that way because the...
This is not something you should be using exceptions for. If it's expected that read_csv() will fail as part of the normal execution of the code (e.g. because the file is missing) and the algorithm should proceed regardless, then exceptions are not the correct mechanism to employ here. By long-standing convention, C++ ...
67,756,737
67,757,516
How to convert opencv Matx to Mat
I'm looking to convert a cv::Matx44d to a cv::Mat of type double and size rows = cols = 4 I've seen this answer that talks about the reverse: how to convert cv::Mat to cv::Matx33f Thank you
There's a Mat ctor that does this: template<typename _Tp , int m, int n> cv::Mat::Mat(const Matx< _Tp, m, n > & mtx, bool copyData = true)
67,756,882
67,766,680
Unreal Engine 4 ray tracing doesn't seem to ignore actor when called through blueprints
So I've been making a game in Unreal Engine 4 and I've been trying to use a combination of C++ and Blueprints. It's been going fairly smoothly, but I was doing some refactoring and decided to move a function in my gun class into the blueprint instead. The function as seen below takes a reference to the player which it ...
Well, it turns out for some reason the length variable in the ShootRay function was overflowing in the Blueprint but not in the C++ code. Removing a few zeros fixed the problem...
67,757,010
67,757,109
How does template argument deduction for f(T&()) happen?
I was reading the standard, and couldn't figure out how the following code compiles. template <class T> void f(T&()) {} double d = 0; double& g() { return d; } int main() { f(g); } [temp.deduct.type]/8 provides a list of cases where the deduction occurs: A template type argument T, a template template argument ...
This is covered in temp.deduct.type#11 These forms can be used in the same way as T is for further composition of types. It might be clearer if you write your template with a different typename than T, e.g. template <class U> void f(U&()) {} so now you can see that U&() is of the form T(), where U& is a variant of T...
67,757,150
67,758,721
What's wrong with 'template< unsigned N, unsigned M> int compare(char p1 [N], char p2 [M])'
while I came across this snippet in <<C++ Primer>> template< unsigned N, unsigned M> int compare(const char(&p1)[N], const char (&p2)[M] { return strcmp(p1, p2); } compare("hi", "mom") sure it worked very well then i thought what if if remove const and & ? so i wrote this template< unsigned N, unsigned M> int comp...
Neither in C nor in C++ there exists a straight-forward manner to pass a C-style array by value (see e.g. here). A C-style array - if not wrapped by a class or struct - is actually only passed as a pointer. This also leads to problems with template deduction as a pass by value decays to a simple pointer and therefore t...
67,757,224
67,757,230
Is using "this->variable" slower than using just "variable"
so if i have a class class newclass { int length; int breadth; public: int area() { return this->length * this->breadth; } int area2() { return length * bredth; } }; which of the two methods will be faster area 1 or area 2, which should be used?
The compiler will treat those as identical. Use this->variable instead of variable if it helps the reader better read the code.
67,757,388
67,757,604
C++ temporary object references
Assuming MyClass has an implicit constructor that takes an int as an argument, why is there a difference between MyClass being explicitly constructed vs. implicitly done so in terms of when the temporary gets destroyed? In one case it results in a dangling reference while in another it does not. template <typename T> v...
std::tuple has a templated constructor taking arbitrary types (overload (3) here). So, in the first case int is passed to tuple constructor, a temporary MyClass is constructed there, then destroyed when that constructor returns and before f is called. In the second case, the MyClass temporary is constructed in main, an...
67,757,507
67,757,669
How to generate 2,598,960 hands (efficient way) for poker game
The total number of poker hands (i.e. five cards for each hand) from a 52 deck is computed by using the choose method nPk (i.e. nPk = n!/(n-k)!*k!) which is 2,598,960 possible hands. What I would like to do is to generate all possible cases(i.e. 2,598,960 hands). The only way I think of is to randomly generate a hand a...
A better method would be to give all cards a numeric index and then write a recursive function to iterate over all existing combinations instead of guessing and checking. Let's imagine you have a deck with 5 cards and only 3 in the hand, this will be your result. 1,2,3 1,2,4 1,2,5 1,3,4 1,3,5 1,4,5 2,3,4 2,3,5 2,4,5 3,...
67,757,687
67,777,601
How to use QOpenGLBuffer:: PixelUnpackBuffer
I can't figure it out how to properly write and read from a QOpenGLBuffer:: PixelUnpackBuffer. What is the proper setup before writing into a PBO? QOpenGLBuffer::write will not work using with a simple QImage.bits(), or glReadPixels() to pass the FBO render into the PBO. It has to be a specific type of data? How do yo...
You have some misunderstandings, and most of these are not related to Qt's abstraction classes, but to how these objects work in the GL itself: // The next block is basically what I understood how to setup a PBO using // Qt's OpenGL wrapper. QOpenGLBuffer *pubo = new QOpenGLBuffer(QOpenGLBuffer::PixelUnpackBuffer); pu...
67,757,750
67,758,274
Is it possible to force a class to be instantiated by singleton-only
When I code with C++11, I usually use the design pattern Singleton. Here is how I design my Singleton: template<typename T> class Singleton { private: Singleton() = default; ~Singleton() = default; public: static T * GetInstance() { static T t; return &t; } Singleton(const Singleton ...
You can use CRTP pattern to achieve this template <class T> class Singleton { public: Singleton& operator = (const Singleton&) = delete; Singleton& operator = (Singleton&&) = delete; static T& get_instance() { if(!instance) instance = new T_Instance; return *instance; }...
67,757,936
67,757,977
Printing birthdates using maps and they end up as Octals
If I create a map for names and birthdays. When i enter birthdates that end in 0 it changes it the number to an octal. how do i print out the birthday ie 010525 == 4437 so when i call it -> second it will print 010525 #include <stdio.h> #include <iterator> #include <string> #include <map> #include <iostream> using na...
There are 2 ways to fix this problem: (1) The first way is to enter the birthday without the leading 0 as follow: birth["Chicken"] = 10525; birth["Dragon"] = 10266; Then use setfill() and setw() to fill the leading 0. Please note that the code that uses std:setw() and std::setfill() will compile only with new C++ com...
67,758,279
67,769,852
Xor Equality (codechef may 21 challenge )I am getting wrong results for some values like n=4589 any help is appreciated :)
/*For a given N, find the number of ways to choose an integer x from the range [0,2N−1] such that x⊕(x+1)=(x+2)⊕(x+3), where ⊕ denotes the bitwise XOR operator. Since the number of valid x can be large, output it modulo 109+7.*/ #include <iostream> using namespace std; #define ll long long const ll N = 1e5; //us...
In practice, the solution is simply a power of two: answer = 2^{n-1}. For efficiency, this implies that it is better to first calculate all solutions iteratively: powerof2[n] = (2 * powerof2[n-1]) % p #include <iostream> constexpr int N = 1e5; //user can input n up to 1e5 unsigned long long arr[N]; constexpr un...
67,758,322
67,758,342
How can I tell if a method modifies the class?
I am writing C++ code and I have a class with a number of member methods. For example, print() and act(); the former does not modify the internals of the class (i.e., the variable i) while the latter does. class Example { int i; void act() { i++; }; void print() { }; This is obvious in this case, but for ...
Is there a way of explicitly denoting that a method is non-modifying? Yes. Mark it as const, eg: void print() const; This will mark the this pointer inside the method's body as pointing at a const object (ie const Example *this). Any attempt to modify that object via that this pointer will cause a compiler error.
67,759,015
67,760,064
Does both NULL and nullptr point to same address or NULL points to nowhere? (I have seen in many places that nullptr points to zero address)
Does both NULL and nullptr point to same address or NULL points to nowhere? (I have seen in many places that nullptr points to zero address where memory is inaccessible)
It might be useful to clear up some terminology. A pointer points to an object. The value of a pointer is an address value. There is a special address value for pointers that do not point to an object. We call such pointers "null pointers". When you assign the NULL or nullptr values to a pointer, it becomes a null poin...
67,759,422
67,760,004
how to make an iterator class a member of a container class c++
I have an container class (myvector) and an iterator class (const_myiterator) I want to initialize an iterator like this auto myit = myvector<int>::const_myiterator{myvec.cbegin()}; As I can do with std::vector class auto it = std::vector<int>::const_iterator{vec.cbegin()}; But I don't know how to implement this
I am very sorry for I asked this question without trying to solve the problem myself. Thanks all who said me about a nested classes. I heard about them before but never used yet and therefore didn't remember them. The answer was given in comments by @Some programmer dude "You define classes inside classes just like you...
67,759,920
67,771,292
Win32 - Button images appear in wrong order in toolbar
I am creating a simple Paint application using win32 api (in visual studio). I have created a toolbar and added a bitmap for 10 toolbar images (TBbuttons.bmp - size: 160x16 pixel - 4bpp indexed format) as below: However the button images do not appear in the correct order as shown above and, moreover, some images have...
I tried to create a sample and used the bitmap. It does have some weird behavior. After I built the project for the first time, it did produce the problem you said. But after I rebuilt, the problem disappeared: I think the bitmap was not loaded correctly during the build process, maybe you can try to rebuild the proje...
67,760,167
67,760,258
Multiple return statements
I am currently reading "A tour of C++" from Bjarne Stroustup, and I saw the following example: bool accept() { cout << "Do you want to proceed (y or n)?\n"; // write question char answer = 0; // initialize to a value that will not appear on input cin >> answer; ...
No, you're not entirely making things up, and no there is no recommendation of such that I know of. Snippet According to your recommendation: Int accept() { Int result=0; cout << "Do you want to proceed (y or n)?\n"; // write question char answer = 0; // initialize to...
67,760,647
67,760,763
Void fucntions not passing parameters c++
So I have a void function that is going to randomly generte a structure: This is the structure: struct przeciwnik{ string nazwa; int HP; int DMGmax; }; And the function: void przeciwniklos(przeciwnik przeciwnik1) { przeciwnik1.HP=rand()%51 + 100; przeciwnik1.DMGmax=rand()%1 + 25; cout << "HP przeciwnika: "...
in this code you are passing variable to function by value then function make copy of your function and do all works then since it's passed by value it has side effect you should return then assign to struct or make by reference. return value: przeciwnik przeciwniklos(przeciwnik przeciwnik1) { przeciwnik1.HP=rand()%5...
67,760,678
67,760,698
Why is const ignored at "the outermost level of the parameter type"?
I read a textbook and met this paragraph: Nontype template parameters are declared much like variables, but they cannot have nontype specifiers like static, mutable, and so forth. They can have const and volatile qualifiers, but if such a qualifier appears at the outermost level of the parameter type, it is simply ign...
Value template arguments can only be compile-time constants. It's not possible to use variables or other run-time data. So const isn't needed, it's understood that the value must already be a constant.
67,760,717
67,761,728
Default comparison operator gives wrong result when constexpr
I was testing the new feature of C++20 to automatically generate comparison operators and I found a weird case when the default operator appears to give a wrong result. It happens only with gcc and only if the operator is declared as constexpr. The following code: #include <iostream> struct Foo { int foo; cons...
Yes, the code as written ought to work, so this is a GCC bug. The default operator== is expected to do an equality comparison of all the subobjects, not just the member subobjects. You can see from the assembly output that GCC 11.1 produces the same comparison operator code for Bar as it would for a struct with no subo...
67,760,775
67,763,667
How can I create an overload for this method?
I have a class with a method that looks like this: class Foo { public: template<typename T> void pushItem(std::string name, T& item) { //Adds item } }; #define pushItem(...) pushItem(#__VA_ARGS__, __VA_ARGS__) This allows me to write: int i = 5; fooObject.pushItem(i); Instead of: int i = 5; fo...
You could simply rename the macro (and remove the variadic portion, as it is not needed). class Foo { public: template<typename T> void pushItem(std::string name, T& item) { //Adds item } }; #define pushValue(p) pushItem(#p, p) int i = 5; fooObject.pushValue(i); int reallyLongVariableName = 5...
67,760,869
67,760,948
no matching function for call to 'regex_match'
Can anyone tell me why function regex_match is not working. It is always giving error saying [cquery] no matching function for call to 'regex_match'. I am familiar with regex library of python but I was trying whether this works for cpp. #include <iostream> #include <string> #include <regex> using namespace std; int ...
so you are tring to pass char as input to regex_match my guess is that you want to match substring so in order to achieve this you should change line to this: regex_match(str.substr(i, str.size() - 1),r2) below line pass first parameter as char which is wrong: regex_match(str[i],r2)
67,761,005
67,761,033
identifier 'sort' is undefined c++
#include <cstdlib> #include <iostream> #include <limits> #include <sstream> #include <numeric> #include <ctime> #include <cmath> #include <vector> #include <cstdlib> using namespace std; vector<int> randVect(int amount, int min, int max); int main(int argc, char** argv) { vector<int> values = randVect(10, 1, 50); ...
you should include header #include <algorithm> sort algorithm defined there.
67,761,307
67,762,182
Is gl_FragDepth equal gl_FragCoord.z when msaa enable?
I know gl_FragDepth will take the value of gl_FragCoord.z from opengl wiki. https://www.khronos.org/opengl/wiki/Fragment_Shader/Defined_Outputs But I have a problem. If I enable MSAA and write gl_FragDepth = gl_FragCoord.z in fragment shader, the display will not work fine. You can see a black line on the white triangl...
Your two triangles intersect. Specifically, the grey triangle has an edge which can generate depth values equal to the depth values of the white triangle. As such, it is entirely possible for a particular sample from the grey triangle at that intersection to generate a depth value that is equal to the depth value of th...
67,761,376
67,761,759
The createdefaultsubobject function does not work for UWidgetComponent[UE4.26.2]
When creating an object of type UWidgetComponent in the constructor, it throws a compilation error. How to solve this problem? changed different variations of the PROPERTY macro didn't help also tried to use the New Object function to create an object also didn't help //.h #include "CoreMinimal.h" #include "GameFramewo...
The function is in different module and you didn't add dependency of that module in build script (*.build.cs file) pic.jpg
67,761,517
67,761,583
How can I assign all objects in a vector in one line? OOP C++
There is class called Player and has std::vectorstd::shared_ptr<Card> library vector. In the int main part, I created objects called Soldier, Pegasus, Guard. I wanna pass this object into a vector in one line. How can I do that? Basically, I wanna create a player1 deck of card vector and pass the objects into that vect...
#include<iostream> class Card{ }; class Creature : public Card { private: std::string name; int a, b, c; bool d, e; char f; public: Creature(std::string name, int a, int b, int c, bool d, bool e, char f) : Card(), name(name), a(a), b(b), c(c), d(d), e(e), f(f) {}; }; class Player{ private: ...
67,761,690
67,761,782
Deduce return type of a function on derived class automatically on base class
I would like to achieve something like following on c++14, basically derived class can have different type of return type (e.g int, double, string, etc) class Base { public: virtual auto value() = 0; // I know this won't compile }; class Derived1 : public Base { public: double value() override { return 1....
This is not possible, fundamentally, in C++. C++ does not work this way, for the following simple reason. Let's just pretend that this works somehow. Consider the following simple function: void my_function(Base *p) { auto value=p->value(); } Now, ask yourself: what is value's type, here? You may not be aware of t...
67,761,785
67,761,825
How to convert string array to const char **?
I was think something like: const char * res[cnt]; int i = 0; for (auto mystring : strings) { const char * str = mystring.c_str(); res[i++] = str; } //then pass res as const char ** But it occurred to me that 'str' is a local variable, the address stored in res could be invalid? What is the right way to do so?...
The problem has nothing to do with str, which will be destroyed after iteration, but this doens't mean the char array pointed by it will be destroyed too. The problem is mystring is declared as by-copy, it'll be destroyed after iteration, then the char arrays returned by c_str get destroyed too. Pointers assigned into ...
67,762,481
67,762,577
C++ How to make a function overload that accepts class functions as argument
I'm using ALGLIB to run a LBFGS minimization of a given function. To do so I need to use the following statement: alglib::minlbfgsoptimize(state, FunctionToOptimizeHere) Here is one declaration of alglib::minlbfgsoptimize provided in the ALGLIB package: void minlbfgsoptimize(minlbfgsstate &state, void (*grad)(const re...
Luckily, your library provides a way to pass context to the callback. You need an intermediate non-member or static member function (sometimes known as a "trampoline"). Something along these lines: class MyClass { void DoActualWork(const alglib::real_1d_array& x, ...); static void Trampoline(const alglib::real_1d_a...
67,762,939
67,763,040
Referencing multi-dimensional arrays in C++
int a[3][2] = {{3, 6}, {8, 4}, {7, 1}}; cout << *a[1] << *(*a + 1); This is my first question here, so please excuse me if I break any rules. How does the code work? It would be great if someone explained how referencing in multi-dimensional arrays work. The output to the code is 86.
Remember pointers and arrays are easily intermingled in C++ as that's something it inherits from C. As such a[n] and *(a + n) are effectively the same, just two different ways of expressing the same thing, though arguably the a[n] notation is much simpler and should be used for clarity. The 2D version is a[n][m] which ...
67,763,118
67,763,234
Default initialization of member variables or add more constructors? Best practice for creating classes?
Following a tutorial on learncpp.com which discusses declaring member variables outside of constructors. However in previous lessons the author mentions that minimizing the amount of constructors is optimal and can be done by using default values in the parameters of a constructor. This is confusing to me because sudde...
You can rewrite your constructors to not have any default parameters by adding some constructors std::string m_color{ "black" }; double m_radius{10.}; // specify default value here, exactly like color public: Ball() = default; // add a default constructor Ball(double radius) // keep the constructor taking a...
67,763,202
67,763,315
Problem using std::binary_search and std::vector
When I try this #include <bits/stdc++.h> using namespace std; vector <short> g; int main(){ g.push_back(3); g.push_back(2); cout<<binary_search(g.begin(), g.end(), 2); } The output is 0. However, cplusplus.com said that std::binary_search will return: true if an element equivalent to val is found, and fal...
Problem is that your vector is not sorted before applying binary search. Apply std::sort(start_iterator, end_iterator); before calling binary_search function; P.S. the algorithm of binary_search returns true or false.
67,763,398
67,763,588
C++: gcc/g++ compiler error logf is not a member of std
I have written a C++ file which contains a function which uses std::logf(). It contains this line float xx = std::logf(x) - 1.0f; The compiler gives me the following error: math_functions.cpp: In function ‘int fclamp_log_to_int(float, int, int)’: math_functions.cpp:49:21: error: ‘logf’ is not a member of ‘std’; did yo...
Is this a gcc problem? Yes. And it is reported. To be fair, it was somewhat unclear whether std::logf was required to exist due to an editorial mistake which caused a contradiction in the standard that was fixed in C++17. You can work around it by using std::log(float) instead. Another workaround is to use ::logf, al...