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
72,406,895
72,464,880
How to build cv2 binding
I have followed the opencv doc for creating my own bindings. I run the file gen2.py which generated some header files: ./ ../ pyopencv_generated_enums.h pyopencv_generated_funcs.h pyopencv_generated_include.h pyopencv_generated_modules_content.h pyopencv_generated_modules.h pyopencv_generated_types_content.h pyopencv_g...
There's not much documentation on how to create a bind (at least I only found this, which is very helpful but doesn't have all the information). First, your module must use the following tree structure (I did everything with cmake): . src └── modules └── your_module ├── CMakeLists.txt ├── include ...
72,407,954
72,408,126
why doesn't GCC place a statically-initialized C++ class object into .data
here are two similar declarations of an object type in C++: struct Obj { int x; }; struct ObjC { int x; ObjC(int x) : x(x) {}; }; Obj obj1 = {100} ObjC obj2(200); using a recent version of gcc (riscv64-unknown-elf-toolchain-10.2.0-2020.12.8) i find that the variable obj1 is correctly placed in the .data ...
Not marking the constuctor with constexpr seems to prevent optimizations here. The following type seems to get initialized properly, see godbolt: struct ObjC2 { int x; constexpr ObjC2(int x) : x(x) { } }; ObjC2 obj3(300);
72,408,158
72,408,348
when passing std::allocator<type>::pointer to my own wrap_iter i'm getting **type instead of *type
I'm trying to create a vector class and my own wrap_iter class here is my vector.hpp #ifndef VECTOR_HPP #define VECTOR_HPP namespace ft { template <class _Iter> struct iterator_traits { }; template <class T> struct iterator_traits<T*> { typedef T* pointer; }; template <class...
The problem is that your overloaded operator* returns an int*(for T=int*) by reference but the actual argument ptr[this->index] that you're returning is of type int and thus the compiler gives the error: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive] 41 | return (ptr[this->index]); |...
72,408,180
72,408,217
What is the benefit of using static thread_local with std::mt19937?
I have seen several usages of std::mt19937 like following: #include <random> size_t get_rand() { static thread_local std::mt19937 generator(time(0)); std::uniform_int_distribution<int> distribution(0, 10); return distribution(generator); } I want to find out what benefits comes from using static thread_lo...
If it wasn't thread_local, then calling get_rand from multiple threads would cause a data race and therefore undefined behavior. Although the static initialization is always safe, even with multiple threads calling it, the call to the generator in distribution(generator), which modifies the generator's internal state, ...
72,408,660
72,408,743
tbb::parallel_for passing ‘const value_type’ as ‘this’ argument discards qualifiers
Started learning TBB recently. I'm trying to implement compressed sparse row multiplication (datatype std::complex<int>) in parallel using TBB. Here is my code : struct CSR { std::vector<std::complex<int>> values; std::vector<int> row_ptr={0}; std::vector<int> cols_index; int rows; int cols; int...
You capture by-value which makes result const (since a lambda isn't mutable by default). Since you also aim to return result, I suggest that you capture by-reference instead: tbb::parallel_for(0, A.rows,[&](int i){ // ^
72,409,091
72,412,791
Define a static constexpr member of same type of a template class
A similar question of non-templated class For a template class, template <typename T> struct Test { T data; static const Test constant; }; it's fine when defining a static constexpr member variable of specialized type: template <> inline constexpr Test<int> Test<int>::constant {42}; https://godbolt.org/z/o4c...
I think GCC is correct in accepting the given example. This is because the static data member named constant is an ordinary data member variable(although it is still considered a templated entity). And since constant is an ordinary data member variable, dcl.constexpr#1.sentence-1 is applicable to it: The constexpr spe...
72,409,129
72,410,933
Overload operator+ to increase IP addresses on boost::asio::ip
I would like to do math operations with IP addresses from boost::asio. Specifically I need to increment and/or add a given integer on an existing address to ease IP list generation in a software that I'm writing. As today I'm using custom classes to handle IP addresses and networks, but I would like to move to boost::a...
To technically work you need the overload: // This is morally wrong auto operator+(const address_v4& address, std::size_t value) { return add(address, value); } That's because the left-hand operand is address_v4, not size_t. Live demo However, please don't do this. See e.g. What are the basic rules and idioms for ...
72,409,198
72,409,414
How to get item from list by giving index number?
I'm making program that will read text file and place each word in list named content and I have problem I don't know how to get words from that list in python it is 'content[index_number]'. thanks in advance! //importing// #include <iostream> #include <sstream> #include <list> #include <fstream> using namespace std;...
Python lists are arrays and allow random access. So do the same in C++ and put your words in std::vector<std::string> content and you have content[i] just like in python, although content.at(i) is safer so use that.
72,409,376
72,409,648
Please help me find what case am I missing
This is the question: In a far away Galaxy of Tilky Way, there was a planet Tarth where the sport of Tompetitive Toding was very popular. According to legends, there lived a setter known to give advanced string manipulation problems disguised as cakewalk problems. thef, the king of thefland loved the letter 't'. And n...
There is no need to insert the letter 't' to determine that two strings can coincide. It is enough to write the if statement #include <iterator> #include <algorithm> //... auto win = []( const auto &s1, const auto &s2 ) { return ( std::size( s1 ) == std::size( s2 ) ) && ( std::equal( std::next( std::be...
72,409,685
72,420,618
WSAPoll vs Overlapped WSARecv Performance?
I'm creating a server that must handle 1000+ clients, the method I'm currently using is: One thread will use WSAAccept to handle incoming connections, it has a threads pool of which each thread will handle multiple clients at a time using WSAPoll. For example, if a Client has just connected, the Server will find a poll...
OVERLAPPED I/O scales remarkably well - scaling down/scaling up/scaling out. My tooling uses AcceptEx with OVERLAPPED I/O + Nt Threadpool. And it scales well to hundreds of thousands of connections. https://github.com/Microsoft/ctsTraffic
72,410,052
72,412,243
Given a template class (A) and a parameter pack of types (T1, T2...), convert to a tuple like A<T1>, A<T2>, A<T3>
How do you implement this: template <class A, class ... T> struct wrapper { template <int depth> A<depth>& get(); // returns a reference to the Nth item wrapped in A; }; e.g. wrapper<vector, int, double, string> example; int x=example.get<0>[7]; // return the vector of `int` at position 0 and call operato...
You need template-template parameter. std::tuple might help too: template <template <typename, typename...> class C, typename... Ts> struct wrapper { template <std::size_t I> std::tuple_element_t<I, std::tuple<C<Ts>...>>& get() { return std::get<I>(data); } std::tuple<C<Ts>...> data; }; //...
72,410,259
72,411,494
Add up those fractions that have a common denominator
I have a file with fractions. I have to write fractions from it into a structure. Then I need to create a dynamic data structure in order to add those fractions that have a common denominator, but I should not use dynamic arrays. Can you please help me with the fraction addition part? (the link contains a photo of the ...
If you build it up from the bottom and use constructors and operators it can turn into this: #include <string> #include <iostream> #include <cassert> struct Fraction { // construct a Fraction from whole number or n, d constexpr Fraction(int n, int d=1) noexcept : numerator(n), denominator(d) { } // add ot...
72,410,262
72,431,707
Incremental ListView with ScrollBar
I want to implement a ListView that loads new content when is scrolled (it will have over 2000 elements) with a scrollbar. This is what I have: <ListView Width="500" MaxHeight="400" IsItemClickEnabled = "False" SelectionMode ="None" IncrementalLoadingThreshold="5" IncrementalLoadingTrigger="Edge" S...
The problem was with a fixed with. After removing it, the scrollbar is visible.
72,410,364
72,410,472
Reversing an array by recursively splitting the array in C++
string recursion(int arr[], int arrSize) { if(arrSize == 1){ return to_string(arr[0]); } string letterLeft, letterRight, letterFull; //logic1: Normal Recursion //letterFull = to_string(a[n-1]) + " " + recursion(a, n-1); //logic2: D&C ------------------------------------------------------ < letterLeft += recursio...
It is unclear why there are used objects of the type std::string. To reverse an array of objects of the type char there is no need to use the class sdt::string. This is just inefficient. The function can look the following way void recursion( char arr[], size_t arrSize ) { if ( not ( arrSize < 2 ) ) { s...
72,410,480
72,410,697
How to get the padding position of a long double value in C++?
The number of bits for the mantissa, exponent and sign of a long double value can be detected in the following way (supposing iec559): template <typename T> constexpr uint32_t bitsInExponent() { static_assert(std::numeric_limits<T>::is_iec559); return std::ceil(std::log2(std::numeric_limits<T>::max_exponent-st...
The authoritative answer can only come from reading the ABI for your implementation. However, if your long double is 80-bit extended precision, then you are almost certainly on x86, since AFAIK it's the only major architecture with hardware support for that format. In that case, unless you have a very unusual compiler...
72,410,860
72,411,364
Do I need to call async_shutdown on beast::ssl_stream<beast::tcp_stream> when experience issues?
https://www.boost.org/doc/libs/1_72_0/libs/beast/example/http/client/async-ssl/http_client_async_ssl.cpp std::unique_ptr<tcp::resolver> resolver_{nullptr}; std::unique_ptr<beast::ssl_stream<beast::tcp_stream>> stream_{nullptr}; void address_failure() { // without calling stream_.async_shutdown // resolver_ = st...
You can start from scratch, but it's good practice to try and do a graceful shutdown if possible. Note that, conversely, some servers might forego clean shutdown. This often leads to short reads (stream_truncated) or, in some situations, sockets in the LINGERING state. It's something that some servers do get away with,...
72,410,931
72,410,978
How to handle "warn_unused_result [-Wunused-result]"?
I am new to C++ and am getting a compiler warning that I am not sure how to address. When I compile INBAND1->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); with c++ calc_emissions.cpp -o calc_emissions.exe -lgdal I get the warning /usr/local/app/emissions/cpp_util/calc_gross_emissions_generic...
how to handle this warning? Handle the error CPLErr errcode = INBAND1->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); if (errcode != 0) { std::err << "och no rasterIO failed!\n"; std::exit(1); } how to silence the compiler? Put (void) in front of the line. (void)INBAND1->RasterIO...
72,411,051
72,412,404
Compiling mutiple c++ files with vscode on mac
I'm fairly new to c++ and programming in general and was watching the free tutorial on the freecodecamp.org youtube channel and when I got up to the point where I used multiple c++ files, I got multiple compiler errors with g++ and clang. Here is main.cpp #include <iostream> #include "compare.h" int main(){ in...
You could build multiple cpp file in VScode by shortcut . Create a build task by following the documentation Update the tasks.json to support build multiple cpp file: { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ ...
72,411,169
72,411,243
the output is throwing large numbers
the question is: Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams. Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won...
you are getting bigger numbers because on this line for(int i=0;i<n;i++){ cin>>arr[n]; } You are changing the value on arr[n] (that doesn't exist because you array goes from 0 to n-1). Basically you are not changing any value inside the array so its using trash values that were stored on the memory. The fix to not...
72,411,265
72,411,873
If atomic_compare_exchange isn't atomic on its own thread, how can it implement a lock?
If I have std::atomic<uint64_t> guard; // ... if (std::atomic_compare_exchange_strong( &guard, &kExpected, kValue, std::memory_order_acquire, std::memory_order_relaxed)) { int foo = *non_atomic_thing; // ... } I know that the read of non_atomic_thing can't be re-ordered before the read of guard. ...
The C++ standard is a little vague on this point. But what they probably intended, and what happens in practice on many implementations, is that your non-atomic read can be reordered before the write. See For purposes of ordering, is atomic read-modify-write one operation or two?. However, for the usual locking idio...
72,411,491
72,411,517
Global int alternative
i have an int linked list, and a function called filter which receives a list and a condition function. The filter function goes through the nodes in the list and if the condition is true, it adds it to a new list. I've created this so that it filters the list through a number i choose to be divided by while the progra...
You would create a a filter class that has a normal (non-static) member that stores your int and has the filter method you also have.
72,411,692
72,411,887
How do i write inside of a txt file with c++
I have been trying to insert the hardware id inside of a file called hardwareid2.txt, this is where the hardware id that i am extracting should be inserted, however it doesn't seem to be doing that and im not sure why, All the code seems to be doing is creating the file but not writing inside of the file. could someone...
In the original code HW_PROFILE_INFO hwProfileInfo; std::string hwid = hwProfileInfo.szHwProfileGuid; The call to GetCurrentHwProfile that will load the system profile into hwProfileInfo is conspicuously absent between the definition of hwProfileInfo and its usage to initialize hwid. That means hwProfileInfo; is sitti...
72,412,173
72,417,633
Unexpected invalid padding error with RSA_private_encrypt() and RSA_public_decrypt()
I'm trying to encrypt with private key and decrypt with public key, with RSA_PKCS1_PADDING as padding. The encryption works fine, but when I do the decryption I got an invalid padding error: processed 9 of 256 bytes, RSA_public_decrypt() error:0407008A:rsa routines:RSA_padding_check_PKCS1_type_1:invalid padding Anyone...
The problem is caused by the while loop in decrypt_stdout(). To me the sense of this loop is not clear. Instead of the loop it should be quite analogous to encrypt_stdout(): output_len = RSA_public_decrypt(input_len, input, output, rsa, padding); if (output_len == -1) { fprintf(stderr, "RSA_public_decrypt() %s\n", ...
72,412,754
72,412,814
creating minheap for structure in c++
#include <vector> #include <algorithm> struct doc { double rank; explicit doc(double r) : rank(r) {} }; struct doc_rank_greater_than { bool operator()(doc const& a, doc const& b) const { return a.rank > b.rank; } }; int main() { std::vector<doc> docvec; docvec.push_back( doc(4) ); ...
As suggested by the documentation of std::make_heap, the function constructs a max heap by default. Reversing the comparison function makes it construct a min heap instead.
72,412,802
72,412,857
C++ Constructor setting all values to zero
struct AnimationData { struct Frame { int x1, y1, x2, y2; float dt; // seconds Frame() : x1(0), y1(0), x2(1), y2(1), dt(1) {} } * frames; int frame_count; std::string name; AnimationData(int fc, std::string n) : frame_count(fc), name(n) { frames = new Frame...
Why Does it turn everything to zero except for the one I set? Because the default constructor Frame::Frame() will initialize x1, y1 to 0 and x2, y2, dt to 1 when you wrote: frames = new Frame[fc]; //default ctor will initialize x1, y1 to 0 and x2, y2, dt to 1 That is, the 10 Frame objects that will be allocated on t...
72,412,824
72,412,887
Errors after updating to GCC 12
I have a project where I'm using the datetimepp library and it has been working fine. However I recently did a pacman -Syu and updated gcc. I then compiled the project (which had been compiling properly before that) and compiled it. I got multiple errors complaining "default argument redefinition" datetimepp/datetime.h...
Default arguments can only be specified at either declaration or definition but in your case you've specified them at both places. void foo(int x = 10); void foo(int x = 10){} // error. redefinition of default arg void foo(int x){} foo(); // ok. default arg is 10 So you should remove them from either declaration or de...
72,412,840
72,413,183
Should we prefer Qt's private slots over public slots?
Qt "private slots:" what is this? AFAIK @Andrew's answer to the question above addresses the point. And @borges mentions the important detail When the method is called via signal/slot mechanism, the access specifiers are ignored. But slots are also "normal" methods. When you call them using the traditional way, the ac...
Slots are a part of your class interface and thus should be public. Private slots are possible with the old connection syntax only due to the peculiarities of how the metasystem works. So they are a byproduct not some first-class citizens to support in the long run. You also can't use the new connection syntax (which i...
72,412,938
72,413,006
Conditionally enable member function depending on template parameter
I'm struggling to get the below code to compile. I want to enable foo function for class A only when N=3. #include <iostream> template <size_t N> class A { public: template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr> int foo(int a); }; template<size_t N> template <size_t n = N, std::enable_if_t<(n == 3...
Whenever you separate a function's declaration and definition, whether it is a template function or not, default argument values can only be in the declaration, not in the definition. So, simply remove the default values from foo's definition, eg: #include <iostream> template <size_t N> class A { public: template ...
72,413,153
72,432,091
Area-based CGAL smoothing turned off but smoothing not performed
I more or less copied this CGAL example, mainly except that instead of PMP::smooth_mesh(mesh, PMP::parameters::number_of_iterations(nb_iterations) .use_safety_constraints(false) .edge_is_constrained_map(eif)); I set the area-based smoo...
There is no way to disable it. This excessive verbosity was a bug and it has been fixed recently in the following pull request: https://github.com/CGAL/cgal/pull/6502. It will be part of the upcoming release CGAL 5.5; you can apply the patch locally until then.
72,413,180
72,413,683
openGL rectangle rendering triangle instead?
So i'm trying to render a rectangle in openGL using index buffers however instead i'm getting a triangle with one vertex at the origin (even though no vertex in my rectangle is suppsoed to go at the origin). void Renderer::drawRect(int x,int y,int width, int height) { //(Ignoring method arguments for debugging...
What is the stride argument of glVertexAttribPointer? stride specifies the byte offset between consecutive generic vertex attributes. In your case it should be 0 or 12 (3*sizeof(float)) but if you look at your images it seems to be 24 because the triangle has the 1st (200, 300) and 3rd (600, 100) vertices and one more ...
72,413,387
72,413,738
how to level-traverse while using `fs::filesystem` in c++
By using fs::filesystem I can pre-order traverse Like below code for (const auto& file : fs::recursive_directory_iterator(paths)) cout << file.path() << endl; And, I found that recursive_directory_iterator only supports for pre-order. Then How Can I use "level-order traversal" in c++? I think I have to use ...
In loop you can push paths into std::vector after that loop sort this vector by '/' character count in paths.
72,413,454
72,413,771
Dynamic allocation/deallocation of array of pointers
Via stackoverflow threads like this one, I discovered that you could use an array of pointers to manage a 2D array. In the past I used to use pointer to pointer to store 2D arrays, but now I have a requirement to store my data in contiguous memory, so pointer to pointer format doesn't work anymore. A raw 2D array is an...
One way is to use a 1D contiguous array and implement the 2D index to 1D index mapping instead: #include <iostream> #include <cassert> using namespace std; template<typename DataType, unsigned numRows, unsigned numCols> class Container2D { public: Container2D() { m_data = new DataType[numRows * numCols]; }...
72,413,858
72,429,097
#include <ranges>, but no namespace 'ranges' found
I want to use std::ranges:views::filter, but VS2019 failed to find std::ranges even #include <ranges>. I'll show you this problem with test project. I've created 'Console App' project on Visual Studio 2019 community, and set up C++ Language Standard to ISO C++20 Standard (/std:c++20). Now the problem : if I type #incl...
C++20 Standard Library features are available in Visual Studio 2022 version 17.2 and Visual Studio 2019 version 16.11.14. devblog link I update Visual Studio 2019 from 16.11.9 to 16.11.15, then <ranges> works.
72,414,022
72,414,092
C++ - response is int%
I decide 2D Dinamic Coding on C++, i'm decide task about count of ways to bottom-right field in table, and my program return %. Why? Program: #include <iostream> using namespace std; int main() { int n, m; cin >> n >> m; int arr[n][m]; for (int i = 0; i < n; i++) arr[i][0] = 1; for (int ...
Your program has undefined behavior for any other sizes than n = 1 and m = 1 because you leave the non-standard VLA (variable length array) arr's positions outside arr[0][0] uninitialized and later read from those positions. If you want to continue using these non-standard VLA:s, you need to initialize them after const...
72,414,928
72,417,171
Pointer not inheriting base class methods
I just started learning polymorphism and am stuck with smth. I have a base class Object, and a derived class Ball. I would like to achieve polymorphism and use Ball methods on an Object pointer as such: Object *ball = new Ball(P, dPdt, s, Forces); cout << ball->getP() << " position\n" << ball->getdPdt() << " speed\n";...
C++ is a statically typed language. If the static type of an expression is Object, then it can do whatever an Object can do (and nothing else). If it's a Ball, then it can do whatever a Ball can do. You want it to be an Object but be able to do what Ball can do. You cannot have both, you need to decide one way or anoth...
72,414,979
72,415,073
Is there a function that can jump over outside of a function?
Is there a function like example: goto that can jump over functions? Lets say I have this code : #include <iostream> void function1() { //dothis1 //dothis2 //jump to other function } int main() { std::cout<<"a"; //go to here (jump) std::cout<<"b"; }
You can just call the another function to which you want to jump to as shown below. In the below program we call function1 from inside main and when function1 finishes the control will be automatically returned to the calling function main. Then from inside function1 we call dothis1 and dothis2 and when dothis1 and dot...
72,415,115
72,415,152
Is there a canonical way to handle explicit conversion between two externally-defined classes?
I'm using two external libraries which define classes with identical contents (let's say Armadillo's Arma::vec and Eigen's Eigen::VectorXd). I would like to be able to convert between these classes as cleanly as possible. If I had defined either class, it would be trivial to include a constructor or conversion operator...
Is it possible to write a function or operator to allow the syntax A a=A(b)? No, it is not possible. The two classes involved define what conversions are possible and you can't change a class definition after it has been defined. You will need to use a function as in your given example, although I would avoid repeati...
72,415,177
72,415,707
C++ type complementation in vscode extensions
I am learning C++ on docker using the template project at https://github.com/cpp-best-practices/gui_starter_template in C++. I have the following code, where name: and text:are not originally written code, but it is completed so that I can see which type it is. It is not a problem because it disappears when it is execu...
I think the inlay hints is a built-in feature now. And VS Code introduced some new values to control how inlay hints behaves since v 1.67 : Editor › Inlay Hints: Enabled value: on - Inlay hints are enabled. off - Inlay hints are disabled. onUnlessPressed - Inlay hints shown and hidden with Ctrl+Alt. offUnlessPressed -...
72,415,211
72,415,511
How to get IntPtr of c# unsafe struct to free its memory initialized in c++ dll
Please, advise me on how to free memory from the created unsafe C# struct(s) using some standard C# toolset or how get I get the IntPtr of those objects to use the default provided custom C++ library? The problem details (UPD): I create the C# unsafe struct and pass it to C++ dll that I can't change TH_ExtractBimTempl...
You don’t need to call TH_FreeMemory. Your structure doesn’t have any pointers inside. In C++, the Mint field should be std::array<uint32_t, MAX_MINUTIAE_SIZE> or an equivalent. Your template local variable is on the stack, it does not use any heap memory, and the stack memory will be freed automatically just before th...
72,415,239
72,415,591
How do I store the compile-time dynamically allocated memory so that it can be used in run-time?
Say, I have a constexpr variable that contains all primes less than 216. constexpr auto primes = [] { constexpr int N = 1 << 16; std::array<int, 6542> ret; bool not_prime[N] = {}; int prime_cnt = 0; for (int i = 2; i < N; i++) { if (!not_prime[i]) { ret[prime_cnt++] = i; ...
Create a lambda that makes a vector, and use another lambda to create an array #include <array> #include <vector> #include <algorithm> constexpr auto primes_num_vector = [] { constexpr int N = 1 << 16; std::vector<int> ret; bool not_prime[N] = {}; for (int i = 2; i < N; i++) { if (!not_prime[i]) { re...
72,415,546
72,415,682
How to fix: double free or corruption (out) Aborted (core dumped) in C++
I've recently been working on a C++ project of mine, and I ran into a problem with the executable: std::string commanddata; std::string input; std::string cmdname; int commandlength = 0; if (commandlength == 0){}else{} // This is so that G++ doesn't complain that I have got a variable and never used...
Thanks very much to @Soonts, who fixed my problem! Another issue, commanddata.erase( input.begin() is obviously wrong, a container can’t erase ranges inside other unrelated containers. A correct usage is something.erase(something.begin(), .. You can clearly tell I'm a noob at this :)
72,415,733
72,416,045
How to know if sub directory exist in c++?
I want to stack directory until directory hits max-depth. Therefore, I tried to use fs::filesystem. At first, I approach by depth() like for (auto itr = fs::recursive_directory_iterator(fs::current_path()/path); itr != fs::recursive_directory_iterator(); itr++) { (itr.depth() == ???) ...
Try this snippet to find max-depth in the current directory: int max_depth = 0; // use as first pass for(auto itr = filesystem::recursive_directory_iterator(filesystem::current_path()); itr != filesystem::recursive_directory_iterator(); itr++) { if (is_directory(itr->path())) { i...
72,415,909
72,416,302
issue while writing and reading array of objects C++
facing an issue while writing and reading array of objects, when I put and write data of array object [0] and object 1, it puts object [0] data in object 1 as well, I think their many other issues with code, if anyone can guide me, I would be really grateful. #include<iostream> #include<fstream> using namespace std; c...
Rough implementation of index plus object. #include<iostream> #include<fstream> using namespace std; class A { private: int num; public: void putdata(){ cout<<"Enter Num: "; cin>>num; this->num=num; } void getdata(){ cout<<"The num...
72,415,949
72,415,984
Variable resetting problem in a list of objects
Today I was writing some SDL C++ program, with squares called particles. My problem is that, for some reason, variable y in instances of class Particle is always resetting to the value passed into the constructor after incrementing it by 1. I'm storing objects in a list. That's a method called every frame: void everyFr...
These lines: for(Particle x:particles){ x.everyFrame(); } are not modifying the particles list. This is because Particle x:particles is creating a copy of each element before calling x.everyFrame(). You need to change it to: for(Particle & x:particles){ // NOTE: added & x.everyFrame(); } Taking a refernce to t...
72,415,982
72,418,210
dynamically allocated struct array for open hash table
I am trying to implement a simple open hash in c++ for the sake of learning. I am getting very confused about the interaction of functions with array pointers, and I am at the end of my wits. The code: struct node{ int data; node* next; node* prev; bool state; node(){ prev = next = NULL; ...
You can simplify this by making the Hashtable an array of pointers to Node. A nullptr then means the slot is empty and you don't have empty and full nodes. Also Nodes only need a next pointer and usually new entries are added to the beginning of the buckets instead of the end (allows duplicate entries to "replace" olde...
72,415,993
72,418,674
The definition of lock-free
There are three different types of "lock-free" algorithms. The definitions given in Concurrency in Action are: Obstruction-Free: If all other threads are paused, then any given thread will complete its operation in a bounded number of steps. Lock-Free: If multiple threads are operating on a data structure, then after ...
Your quote from Concurrency in Action is taken out of context. In fact, what the book actually says is: 7.1 Definitions and consequences Algorithms and data structures that use mutexes, condition variables, and futures to synchronize the data are called blocking data structures and algorithms. Data structures and algo...
72,416,188
72,416,388
Finding heaviest path (biggest sum of weights) of an undirected weighted graph? Bellman Ford --
There's a matrix, each of its cell contains an integer value (both positive and negative). You're given an initial position in the matrix, now you have to find a path that the sum of all the cells you've crossed is the biggest. You can go up, down, right, left and only cross a cell once. My solution is using Bellman F...
"Let's replace all the values by their opposite number" Not sure what you mean by an opposite number. Anyway, that is incorrect. If you have negative weights, then the usual solution is to add the absolute value of the most negative weight to EVERY weight. Why Bellman-Ford? Dijkstra should be sufficient for this prob...
72,416,354
72,416,476
Make difference between copy and direct initialization
Create an “UnusualClass” class in which direct and copy initialization produce different effects throughout. In particular, the attempt of direct or copy initialization should produce on the screen the print "Direct initialization" or "Copy initialization" #include <iostream> class UnusualClass{ public: UnusualCl...
I believe it's impossible in general, but if you only want to support the two ways of initialization you listed, there are hacky solutions. You need two constructors, one explicit and the other non-explicit. As you were already told in comments, operator= won't help you, since both lines perform initialization and not...
72,416,401
72,416,995
Printing A Circular Linked List
I am doing an Assignment which is about Creating and Printing a Circular Linked List. Here is my Code: #include <iostream> #include <conio.h> using namespace std; class node { public: int data; node *next; node() : data(0), next(NULL) {} }; class list { private: node *first; node *last; public: list() : fi...
You can call a deletelist method before displaying next added elements as follows: void deleteList() { node* current = first; node* next = NULL; while (current != NULL) { next = current->next; delete(current); current = next; } first = NULL; }
72,416,421
72,416,488
Having trouble making a map with different types
I want to make a map that has string keys that have string values and with the second data type being string keys with a list value. I tried following the solutions mentioned under this thread: Store multiple types as values in C++ dictionary? but I keep on getting these errors. Any help is appreciated, I've been at th...
std::map<std::variant<std::string, std::list<std::string>>, std::variant<std::string, std::string>> Is a map with (string or list keys) and (string or string) of values. Having variant with duplicate types is allowed but unnecessary and it will complicate things. You want std::map<std::string,std::variant<std::string, ...
72,417,046
72,419,193
C++ error: intrinsic function was not declared in scope
I want to compile code that uses the intrinsic function _mm256_undefined_si256() (returns a vector of 8 packed double word integers). Here is the reduced snipped of the affected function from the header file: // test.hpp #include "immintrin.h" namespace { inline __m256i foo(__m256i a, __m256i b) { __m256i ...
Your code works in GCC4.9 and newer (https://godbolt.org/z/bajMsKvK9). GCC4.9 was released in April 2014, close to a decade ago, and the most recent release of GCC4.8.5 was in June 2015. So it's about time to upgrade your compiler! GCC4.8 was missing that intrinsic, and didn't even know about -march=sandybridge (let ...
72,417,186
72,418,527
How can I know if directory have children directories in c++?
I want to check if directory have a child directory. I thought I can find by ++operator But it didn't work. for (auto itr = fs::recursive_directory_iterator(fs::current_path() / path); itr != fs::recursive_directory_iterator(); itr++) { if (!(* itr++).exists()) ...
A (recursive_)directory_iterator gives you access to a list of child items, both files and directories. It is up to you to differentiate between files and directories, eg: bool has_child_directory(const fs::path &dir) { for (auto itr = fs::directory_iterator(dir); itr != fs::directory_iterator(); ++itr) { ...
72,417,198
72,417,258
Get number of active class instances
I need to get a number of created and the number of active class instances. #include <iostream> #include <stdexcept> class Set { double value; int created = 0; int active = 0; public: Set(); Set(double num); static int NumberOfCreated(); static int NumberOfActive(); }; Set::Set() : value(0) {} Set::Set(do...
you have multiple problems, here is how it can be done, check comments: #include <iostream> #include <stdexcept> class Set { double value; static int created; // you need single variable for all instances, this is why static static int active; public: Set(); Set(double num); ~Set() { --active; // des...
72,417,491
72,459,851
My c++ program crashes instantly when using SFML/Audio.hpp (Building works)
I am using the following c++ compiler MinGW-W64-builds-4.3.4 on Windows 10 with the following SFML library SFML-2.5.1-windows-gcc-7.3.0-mingw-32-bit and CLion 2021.2 Build #CL-212.4746.93 My CMakeLists.txt looks like this: cmake_minimum_required(VERSION 3.20) project(SFML_Audio_Error) set(CMAKE_CXX_STANDARD 14) a...
So I solved the issue. Thanks to the help of Retired Ninja. I put the openal32.dll file into the same directory as the executable (.exe) this resolved the issue and i can play sound now. Thanks again all of you. :) Picture of the working Directory with the .dll
72,417,624
72,417,775
Sorting a map by values - keys
I'm writing a code that counts the number of occurrences of each word in a file, and print out these words in order of number of occurrences. After each word, it prints its number of occurrences. Words occurring the same number of times in the file are listed in alphabetical order. I don't know how to modify that code ...
A solution using std::map to perform the sorting. Readability may be further improved by replacing std::pair<string, int> with a struct with a meaningful name. #include <fstream> #include <iostream> #include <map> #include <string> #include <utility> using std::cout; using std::ifstream; using std::map; using std::pai...
72,417,631
72,418,141
Infix to Postfix Converter in C++ gives no output
I made a function infixToPostfix() which converts an infix expression to a postfix expression. But my program generates no output on running. Please point out the errors in my program. Code: #include <iostream> #include <cstring> #include <stack> #include <cstdlib> using namespace std; int isOperator(char x) { ret...
Your code is exceeding the time limit because it is stuck in the infinite loop. You have not updated the i variable- which is the index of the infix array in the else part of the loop i.e when infix[i] is an operator. i.e. in this part of the code else { if (!lobby.empty()) { ...
72,417,657
72,417,764
Freetype Exception thrown: read access violation. face was nullptr
''' FT_Face face = nullptr;; FT_GlyphSlot g = face->glyph; FT_Library ft; if (FT_Init_FreeType(&ft)) std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl; if (FT_New_Face(ft, "fonts/arial.ttf", 0, &face)) std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl; FT_Set_Pixel...
The problem(mentioned error) is that somewhere in your program you're dereferencing face when it is nullptr which leads to undefined behavior. To solve this add a check to see if face is nullptr or not before dereferencing it as shown below: //go inside the if block only if face is not nullptr if(face !=nullptr) { ...
72,417,985
72,418,043
Segment fault upon calling method of class
I was able to safely call builder, but builder2 exits with a segment fault. The compiler does not output any warnings. I would like to know the cause of the segment fault. This code is a builder pattern to compose html. ul and li are collected with emplace_back and finally str() is called to build the parts and return ...
You dynamically create a std::unique_ptr object holding the builder with HtmlElement::build("ul"). This std::unique_ptr object gets destroyed at the end of the full expression which means the object builder2 points to is destroyed and dereferencing it is undefined behaviour resulting in the crash you observed. I recomm...
72,418,001
72,418,121
if/else statement with arrays is failing
So the code is really simple, its just a main(), but there is something wrong in the if/else statement in the while cycle and I dont't know what it is, I thought this is how it supposed to work, but clearly its not. The code is creating a 11-element array, but the 0th element of the array is typed in by the user. So fo...
Indexing starts with zero, so if you create an array with a size of N last index always will be N-1. In your case, the index of the last element is 10. if (input <= numbers[10] && input >= numbers[0]) // accurate
72,418,169
72,418,202
Creating a sub-namespace with the name of another namespace
I want to do something like this: namespace someModule { int someInt = 4; } namespace test::someModule { void f() { someModule::someInt = 2; } } But it looks like the compiler searches for someInt in test::someModule and not in someModule. I could create test as test::someModule_, but it looks...
you can always refer to the global namespace using :: as prefix, i.e., ::someModule::someInt = 2; Note that the fact you're having multiple identically named namespaces is probably pretty confusing! Unless you have a very good architectural reason that you explained why proposing to add such to a project I'm maintaini...
72,418,578
72,421,662
Why is a 1 being printed at the end of BFS?
Here's a simple Breadth First Search on an undirected graph. The question is to find whether or not a path exists between a source and a destination node. The code works, but I don't understand why a 1 is being printed at the very end. Program: #include <iostream> #include <unordered_map> #include <vector> #include <qu...
The first comment on this question sums it up - I overlooked the fact that I am printing a bool (cout << BFS(umap, 'j', 'm');), so a 1 is expected in this case where a path is found (the value is true).
72,418,756
72,418,832
How to skip (not output) tokens in Boost Spirit?
I'm new to Boost Spirit. I haven't been able to find examples for some simple things. For example, suppose I have an even number of space-delimited integers. (That matches *(qi::int_ >> qi::int_). So far so good.) I'd like to save just the even ones to a std::vector<int>. I've tried a variety of things like *(qi::int_ ...
You're looking for qi::omit[]: *(qi::int_ >> qi::omit[qi::int_]) Note you can also implicitly omit things by declaring a rule without attribute-type (which make it bind to qi::unused_type for silent compatibility). Also note that if you're making an adhoc, sloppy grammar to scan for certain "landmarks" in a larger bod...
72,419,442
72,419,482
creating a project on mingw under windows
I am creating a project using mingw under windows. When run on another PC (without wingw in PATH, respectively), get errors, missing: libwinpthread-1.dll, libgcc_s_seh-1.dll, libstdc++-6.dll. How can I build the project so that everything starts up normally?
A C++ program needs runtime libraries to run. They're usually not part of the program itself! So you'd need to ship these libraries alongside with your program (which is what most software does). You can, for many things, however, also use "static linking", which means that the parts of the libraries used by your progr...
72,419,514
72,423,554
deferred selection of types during compile-time
Is there a standard way for me to select a type at compile-time in c++20 when the type depends on compile-time information available later in the function, i.e. the type is "deferred" because of intermediate compile-time dependencies. For example something like this which depends on the auto keyword but does not compil...
auto variable can only infer its type from the initialization expression in C++. If you don't want to explicitly specify its type, you can extract the initialization into a separate function which returns the necessary value (type is auto) and initialize with this function's call. In particular, the extracted function ...
72,419,746
72,420,148
How do I check that a particular template parameter is the same
I have a class with three template parameters: template<typename A, typename B, typename C> class Unit; Then I have a concept representing this class and all its specialization: template <typename T> struct is_unit : std::false_type {}; template<typename A, typename B, typename C> struct is_unit<Unit<A, B, C>> : std:...
This is probably what you want template<typename A, typename B, typename C> class Unit; template<typename U, typename A> constexpr bool unit_first_type = false; template<typename A, typename B, typename C> constexpr bool unit_first_type<Unit<A, B, C>, A> = true; template<typename U, typename A> concept UnitFirstType...
72,420,355
72,420,530
CMake undefined reference to `pthread_create` in Github Action Ubuntu image
When I was using Github Action CI, I found that no matter what method I used to link, there was no way to link pthread_create But this error only appears in the Ubuntu environment, Windows, macOS are no problem I tried: Not Working set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_packa...
If you read the build log carefully /usr/bin/ld: CMakeFiles/GenerateAudioModelTest.dir/__/src/GenerateAudioModel.cpp.o: in function `GenerateAudioModel::GenerateModelFromFile()': GenerateAudioModel.cpp:(.text+0x27aa): undefined reference to `pthread_create' You notice the error has happened while linking the target Ge...
72,420,382
72,420,417
Issue filling a 2d array of chars in c++
I was writing a program that involves a two dimensional array of values, and I was planning on printing them to terminal with ANSI escape codes. To test my code to for printing values with ANSI escape codes, I filled the array with a gradient. However, when I tried this, only the top row had the gradient. I have no ide...
The issue was hiding in plain sight. I forgot to initialize my iterators to 0 in some of my for loops. for (char i; i < 64; i++) forgot to set initial value to 0, the same for J loop – Iłya Bursov
72,420,933
72,422,071
creating a vector with user defined class and int In instantiation of ‘struct std::_Vector_base....no type named ‘value_type’ in ‘class MyClass’
I am creating a simple class #include <iostream> #include <vector> #include <algorithm> using namespace std; class MyClass { int p; public: MyClass( int q ) { p = q; } }; but when I try to create this vector vector<int, MyClass> vec1(1); my code breaks and throws this exception vector<int,MyClass> vec...
how to print p if I am using pair in vector as u shown You can iterate through the pair elements of the vector and print the data member p as shown below: class MyClass { public: int p; public: MyClass( int q ):p(q) { } }; int main() { std::vector<std::pair<int, MyClass>> vec1{{1, M...
72,421,352
72,422,723
How to restrict generic class method template parameter to certain types?
I have checked out std::enable_if to conditionally compile a member function However it doesn't work for me. I need to restrict T of a class method to some types. template<typename T = typename enable_if_t< is_same_v<T, long> || is_same_v<T, int> || is_same_v<T, double> || is_same_v<T, float> || is_same_v<T, s...
Despite what the other answers say, the member function doesn't need to (and shouldn't) be a template, assuming you use requires. That's only necessary when you use the classical SFINAE. #include <cstddef> #include <iostream> #include <memory> #include <type_traits> template <typename T, typename ...P> concept one_of ...
72,421,374
72,421,509
match against template template type parameter
Say I would like to type-match any container with a specific member (a constraint) - but also bind type variables to both the container and the member. For example let T and U be the template type variables corresponding to class and member Someclass.member. Is this possible? Let's simplify things by templating the con...
The caller's template list should be template <typename T> struct S1 { T a; int b; }; void cb(auto*); template<template<typename...> typename Temp, typename U> void caller(Temp<U>*, void (*)(U*)); int main() { S1<int> a; caller(&a, cb); S1<double> b; caller(&b, cb); } Demo
72,421,646
72,422,815
Unqualified name lookup
This is from the standard (C++20) - unqualified name lookup 6.5.2. Can anyone please explain what's going on here ? Note: this is not ADL. I am specifically looking for an elucidation of this brief sentence: "In some cases a name followed by < is treated as a template-name even though name lookup did not find a templat...
In f<N::A>(N::A()), the < can either be a less-than operator or start a template argument list. To disambiguate, compilers need to see whether f (the name before <) names a template. Note that it's impossible to perform ADL at this point, because when compilers see <, they do not even know whether there are arguments. ...
72,421,916
72,422,480
Having trouble setting background of an event with its ID | WxWidgets
I believe I've done something similar in wxPython where I've changed an event by grabbing the Id or object and setting the object's background from there. In WxWidgets I seem to be having trouble though, I keep on getting errors like operator -> or ->* applied to "int" instead of to a pointer type. I'd like to be able...
The problem is that EventId is an int and thus the operator -> cannot be used with it. You can try out the following that uses GetEventOjbect: wxObject *obj = event.GetEventObject(); ((myPanel *) obj)->SetBackgroundColour(wxColour(217, 217, 217, 19)); //^^^^^^^----------------------------->use your own type here
72,422,048
72,422,086
How can I call the specialized template overloaded function from the main template one?
I have a method inside a templated class that creates a hash of a variable. I have specialized its template to int, double and std::string like this template<> class Hash<int> { public: unsigned long operator()(const int& d) const noexcept { return d * d; } }; template<> class Hash<double> { public...
If I understood correctly, your operator() needs a Hash instance to call its specialized operator() auto operator()(const Data& d) const noexcept { // .... std::string s = ""; return Hash<std::string>{}.operator()(s); // ^^^^^^^^^^^^^^^^^^^ // OR simply // return Hash<std::string>{}(s); ...
72,422,112
72,422,146
parameter difference between C++ and Python
C++ #include <iostream> using namespace std; void doSomething(int y) { cout << y << " "<< & y << endl; } int main() { int x(0); cout << x << " " << & x << endl; doSomething(x); return 0; } Python def doSomething(y): print(y, id(y)) x = 0 print(x, id(x)) doSom...
i don't understand why variable's address isn't changed in Python while variable's address is changed in C++. Because in python, we pass an object reference instead of the actual object. While in your C++ program we're passing x by value. This means the function doSomething has a separate copy of the argument that wa...
72,422,474
72,422,563
Creating multiple randomly named files on a desktop doesn't work with C++
This program should create 10 randomly named files with unicode string names on a desktop but it only creates just 1. I tried using delete[] statements at the end of the createfiles function to deallocate the memory for output, file and desktop but it still doesn't work. Am I doing something wrong? #include "shlobj_cor...
If the function call time(NULL) is executed several times in the same second (which is probably happening in your case), then it will return the same value every time. This means that you are seeding the random number generator with the same value every time you attempt to generate a random string. As a consequence, ra...
72,422,602
72,423,267
How to get if User pressed Enter wxWidgets
I want to get the Input from a field wxTextCtrl* upperOnly = new wxTextCtrl(this, wxID_ANY, wxT("Test"),wxPoint(5,260), wxSize(630,30)); and this i want every Time the user Pressed Enter
Use wxTE_PROCESS_ENTER when creating the control, i.e. wxTextCtrl* upperOnly = new wxTextCtrl(this, wxID_ANY, wxT("Test"),wxPoint(5,260), wxSize(630,30), wxTE_PROCESS_ENTER); Then catch wxEVT_TEXT_ENTER and do your validation in its event handler, i.e. upperOnly->Bind(wxEVT_TEXT_ENTER, [](wxCommandEvent&) { //...
72,422,738
72,422,802
Difference Between "struct Obj* obj" and "Obj* obj"
struct Element{ Element() {} int data = NULL; struct Element* right, *left; }; or struct Element{ Element() {} int data = NULL; Element* right, *left; }; I was working with binary trees and I was looking up on an example. In the example, Element* right was struct Element* right. What are the d...
In C++, defining a class also defines a type with the same name so using struct Element or just Element means the same thing. // The typedef below is not needed in C++ but in C to not have to use "struct Element": typedef struct Element Element; struct Element { Element* prev; Element* next; }; You rarely have...
72,423,058
72,423,276
Memory leak in the implementation of the matrix multiplication operation
Memory leak in the implementation of the matrix multiplication operation: template <typename T> class Matrix { private: T *data = nullptr; size_t rows; size_t cols; Here is the multiplication operation itself: Matrix<T> operator*(const Matrix<T> &other) { Matrix<...
Your result.data is not initialized to 0 but you apply a += operation to it. You must either initialize your Matrix::data member to zero in the Matrix main constructor function, or initialize it preliminary in your multiplication loop. for (size_t i = 0; i < rows; i++) { for (size_t j = 0;...
72,423,103
72,423,553
Is there a way I can run c++ functions inside Java without using SWIG?
I want to create a wrapper for c++ so I can run code that I wrote in Java. Is there a way to achieve this without using SWIG?
As far as I know, JNI is the only way to run foreign language code inside Java app. Other solutions like SWIG are just JNI wrappers. If you have only 1-2 functions to call from Java code, SWIG may be an overkill. Try reading SWIG documentation: https://www.swig.org/Doc1.3/Java.html#java_overview Summarizing you can use...
72,423,148
72,423,171
C++ pass an array to a function without knowing its type
I want to make a function that takes an array as an argument with ANY type and returns its length like the following example: unsigned int getLength(array) { return sizeof(array) / sizeof(array[0]) } I don't know if it's possible to even possible to pass an array without knowing its type, I hope I explained my ques...
You can use templates as shown below. In particular, we can make use of template nontype parameter N to represent the length of the passed array and template type parameter T to represent the type of the element inside the array. template<typename T, std::size_t N> //--------------------------v--------------->type of e...
72,423,418
72,423,621
How do I tell CMake to link the C standard library, not the C++ one?
I have a simple C++ file, but I do not want to use the C++ standard library, just the C one. Can this be done using CMake? Basically disabling access to the c++ headers, and only allowing linking to the C standard.
You can use target_compile_options(yourprog PRIVATE -nostdinc++) for clang and GCC based toolchains and /X with the path to its STL headers with msvc
72,423,513
72,424,844
Multi-threaded C++ code slower with more physical cores? (threaded C++ mex function)
I am running multi-threaded C++ code on different machines right now. I am using it within a Matlab mex function, so the overall program is run from MatLab. I used the code in this link here, only changed what is done in "main_loop" to fit to my task. The code is running perfectly fine on two of my computers and it is ...
TL;DR: NUMA effects combined with false-sharing are very likely to produce the observed effect only on the 2-socket system. Low-level profiling information to confirm/disprove the hypothesis. Multi-processors systems are subject to NUMA effect. Non-uniform memory access platforms are composed of NUMA nodes which have ...
72,423,582
72,424,096
Forward declarations and incomplete types in C++ modules
I have been experimenting with C++20 modules, and there seems to be something different with the usual hpp/cpp approach. The following doesn't compile (I'm using the latest preview of MSVC). foo.ixx export module foo; import std.memory; export struct Bar; export struct Foo { std::unique_ptr<Bar> ptr; }; bar.ixx e...
Modules own the declarations placed into them. And if a module owns a declaration, all other declarations must also be part of the same module. Bar was declared to be in foo. Therefore, any other declarations of it (and a definition is a declaration) must also be within foo. They don't have to be in the same file, but ...
72,423,613
72,427,875
gdb: how to learn which shared library loaded a shared library in question
I need to get the list of shared libraries used by an app in runtime. Most of them can be listed by ldd, but some can be seen only with gdb -p <pid> and by running the gdb command info sharedlib. It would really help, if I could learn in some way: for a chosen library (in the list, output by info sharedlib), which libr...
Is there any way to learn it in gdb or in some other way? There are a few ways. You can run the program with env LD_DEBUG=files /path/to/exe. This will produce output similar to: LD_DEBUG=files /bin/date 76042: 76042: file=libc.so.6 [0]; needed by /bin/date [0] It is the needed by part that you most ...
72,424,353
72,424,404
Why does it not display the final product?
I want to write a program on where the user gets asked a quiz and then they get assigned on one of the Harry Potter houses, but in the end the output for the house doesn't show. I am using c++ for this project and I also using Visual Studio Code as my IDE. I want to be able to put the alternatives and when the user inp...
When you write "but in the end the output for the house doesn't show", do you mean the other text does show, but specifically not the house name? Or does none of the text show. In the former case, you might want to give the variable MaxPoints an initial value, because currently its value is undefined: int MaxPoints = -...
72,424,888
72,425,649
Bouncing Ball Collision -SFML
I'm making a simple simulation of a ball bouncing. I already implemented gravity, but I don't know how to handle for collisions (make the ball change direction). I tried reverting the velocity, but that didn't work. // random start velocity float v = 2.f; // force float f = 0.f + (v*t) + (1/2.f)*G*t; std::cout << f <...
//collision happened if ((ball.getPosition().y + ball.getRadius()) > 400.f){ // revert the velocity v = -v; } This can result in the ball bouncing up and down, and falling through. You need: //collision happened if ((ball.getPosition().y + ball.getRadius()) > 400.f){ // make sure the velocity is downwards...
72,425,106
72,425,143
Print front and back from an array c++
how can i print from array once from back and once from front c++? for examble: char c[] = { 'A','B','C','D' }; for (int i = 0; i < size(arr); i++) { cout << c[i]; } the output will be ABCD but the output that i want should be ADBC print one from front and one from end c[0],c[3],c[1],c[2]
You can use. Here we iterate for only half number of times the size of the array. Note that this assumes you have even number of elements in the array. int main() { char c[] = { 'A','B','C','D','E' }; std::size_t len = std::size(c); //---------------------v------------->divide by 2 so that we iterate only h...
72,425,275
72,425,360
how to solve this question when a day is set to the first day of the month and decremented, it should become the last day of the previous month?
This is my first time trying such question .It has been so difficult for me to solve this question as I wasn't able to attend my classes when this was taught due to some reasons.Can anyone help me how do I use decrement operators as I have no idea where and how to add such operators to get the desirable output. I am al...
You can basically do the same thing with the increment operator but do it backwards. The C++ operator for decrement is --variable so the code would look as follows Date operator--(){ --day; --year; --month; if(day <= 0) { day += 31; } if (month<=0) { month += 12; } ...
72,425,404
72,435,709
Still unsure about signed integer overflow in C++
In the following code I tested which form of overflow results in UB and causes therefore an hard error in a constexpr context: #include <cstdint> #include <limits> using T = int8_t; int main() { constexpr bool b = []{ T x = std::numeric_limits<T>::max(); ++x; // GCC: UB, Clang: no UB // ...
[expr.pre.incr]/1 The expression ++x is equivalent to x+=1. [expr.ass]/6 The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. But x = x + 1 is not UB (integer promotion and narrowing integer conversion), so the original is well-formed. Therefore, ...
72,425,473
72,425,702
(MSVC) When implementing template method of template class outside of the class, C2244: Unable to match function definition to an existing declaration
Running into an issue with some code that compiles on GCC and Clang, but not MSVC (VS2022). Seems similar to this, but that was several years ago and this issue is specifically caused by the use of derived_from_specialization_of in the method template, so I'm not sure if it's the same issue. I'm wondering what the reas...
what the reason for this is, and if the issue is with my code or MSVC. This seems to be a bug in MSVC. You've correctly provided the out-of-class definition for the member function template Foo<>. Using auto and trailing return type doesn't seem to solve the issue in msvc. You can file a bug report for this.
72,426,064
73,679,518
Fast copying between random addresses
I'm developing an application which needs to perform a massive copying data byte-by-byte from one addresses to another addresses. Now'm using for loop in multithread. Size of arrays can be from 100k elements to 2M elements. It works relatively fast, but not enough. Is there a faster way to perform this task? std::vecto...
I moved entire project on GPU, using GLSL. Arrays are replaced with 2D samplers. Even low-end Intel UHD can handle high resolutions at high framerate.
72,426,626
72,426,818
Trouble creating an SFML Window
When trying to create an SFML window, sf::VideoMode(800, 600) gives a constructor not viable error. Source code: #include <SFML/Window.hpp> int main() { sf::Window window(sf::VideoMode(800, 600), "Pong"); return 0; } Error log: Consolidate compiler generated dependencies of target pong-cpp [ 50%] Building CX...
Is this just the new way? Yes, they have made some changes. Here are the changes from the source file: This: VideoMode(unsigned int modeWidth, unsigned int modeHeight, unsigned int modeBitsPerPixel = 32); is now this: explicit VideoMode(const Vector2u& modeSize, unsigned int modeBitsPerPixel = 32); Take a look at i...
72,427,124
72,464,185
double quotes problems in Qstring
QProcess p; QString aa = "tasklist /FI 'IMAGENAME x32dbg.exe' /FO LIST | findstr 'PID:'"; aa.replace(0x27,0x22); qInfo() << aa; p.start(aa.toStdString().c_str()); p.waitForFinished(); qInfo() << "Output:" << p.readAllStandardOutput() << "Error:" << p.readAllStandardError(); // returned error <ERROR: Invalid argument/o...
bool isRunning(const QString &process) { QProcess tasklist; tasklist.start( "tasklist", QStringList() << "/NH" << "/FO" << "CSV" << "/FI" << QString("IMAGENAME eq %1").arg(process)); tasklist.waitForFinished(); QString output = tasklist.readAllStandard...
72,427,210
72,427,269
no match for ‘operator[]’ (operand types are ‘QJsonDocument’
I built a quick server using QT Creator on Windows, everything worked perfectly, I tried running The same code on my other Machine(Ubuntu) and I get errors, specially, in this line: QString max_colorbar = doc["colorbar"].toString(); The error I am getting is: no match for ‘operator[]’ (operand types are ‘QJsonDocument...
It's because const QJsonValue QJsonDocument::operator[](const QString &key) const function was introduced in Qt5.10 and you ran in on Qt5.9.5. You could change your code from QString max_colorbar = doc["colorbar"].toString(); to as follows which builds on Qt5.9.5 too QString max_colorbar = doc.object().value("colorbar...
72,427,260
72,427,275
Access variable from one file from multiple files without copy
I'm trying to declare a variable in a header file Declarations.h which will be accessed from multiple files... like in C# it's a public static uint variableXXX then you can access it from everywhere. Declarations.h: #pragma once #ifndef CLIENT_CONST_H #define CLIENT_CONST_H static DWORD LocalPlayerPointer, LocalPlayer...
In the header file put extern DWORD battle_int; in one C++ file put the definition DWORD battle_int = 0; dont put 'static' thats specifically means 'private to this file'
72,427,424
72,427,714
Boost Spirit x3 - parser doesn't recognize end of line
I am trying to parse an .obj file, but i can't figure out how to make x3 stop at the end of a line. My code looks like this: #include <iostream> #include <boost/config/warning_disable.hpp> #include <boost/spirit/home/x3.hpp> #include <boost/spirit/home/support/iterators/istream_iterator.hpp> #include <boost/spirit/in...
Like the commenter said. This is why you enable warnings: <source>:33:43: warning: multi-character character constant [-Wmultichar] 33 | *( char_('#') >> *(~char_('\r\n'))[printText] >> eol) | ^~~~~~ Next up, simplify-time: https://compiler-explorer.co...
72,427,693
72,428,424
convert struct to unsigned char through overloaded operator << and >> (see update)
I have this struct with 2 attributes (one char and one int, for a memory usage of 3 bytes: struct Node { char data; int frequency; } I try overload the operators << and >> for this struct, for being able to read and write this struct from and into a file using fstream . For the operator << I got: friend std:...
how much space this returns to the output (3 bytes, as expected? - 1 from the char and 2 from the int?) No. You are converting the values to std::strings, so they have variable lengths depending on the particular values (ie, "123" takes up a different length than "1234567890"). What you describe applies to the binary...
72,427,809
72,427,891
How to define compile time ternary literal in C++?
In Chapter 19 of the 4th edition of the C++ Programming Language book, there is an example of defining a ternary number literal using a template technique, but the example does not compile. I tried to fix it in the way it looks right to me, but it still does not compile. #include <cstdint> #include <iostream> using na...
Currently, when tail only has 1 character (when called with the last digit '0' of your user defined literal), it could call either overload of base3 template <char c> constexpr uint64_t base3() // With c as '0' template <char c, char... tail> constexpr uint64_t base3() // With c as '0' and tail as an empty parameter ...
72,428,029
72,428,097
Default argument for template not working
I have a chain of nested templated using declarations. It looks something like this: template <typename A, typename B, typename C, typename D> class Foo { public: Foo() : value{0} {}; template <typename AC, typename BC, typename CC, typename DC> Foo(const Foo<AC, BC, CC, DC>& rhs) : value{rhs.value} {} ...
The issue is that Bif isn't a type, it's a templated type. You're getting away with it when you declare bifDefault because of CTAD, but it doesn't apply when you call convertTo (you're not passing a non-type template parameter). The code compiles as expected when replaced with bifLong.convertTo<Bif<>>().
72,428,165
72,428,203
Redefinition and fail to use ifned/def/endif
I'm trying to make a program that follows the following UML diagram I've divided each class into its respective header and cpp. However, while doing some tests on it I found plenty of messages of redefinition so I tried using ifndef, def and endif however as you can see in this image (my commission worker header) it s...
You include the header file for the Employee Class by using the preprocessor directive #include "HEADERNAME.h/hpp" In your case: #include "Employee.h", if your header file is called like that. You used so called "Include/Header guards" which are used to prevent multiple header inclusions. Those should be put in the res...