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
66,471,569
66,471,704
C++: Weird negative integer output, most likely due to an error in the loop, but I can't seem to notice it
I'm writing a program which is supposed to randomly generate numbers, and then allocate them into specific ranges, depending on the number This is the function which takes care of that: void rangiranje(int arr[30], int &rang1do2k, int &rang2do3k, int &rang3do4k, int &rang4do5k) { for (int i = 0; i < 30; i++) { if (...
You have to initialize rang1do2k, rang2do3k etc. with 0 value before your loop. Then, perhaps you don't go into any other if else than this with range 4000-4999, so all other counter will have 0 values. int rang1do2k = 0;
66,473,052
66,490,155
How can I read spdlog output in a google test
I am on the latest commit of spdlog (there is an issue regarding std output, apparently resolved), and am switching my output from std::cout to spdlog. My google tests redirect std::cout so I can check the output of stub functions: class MyTest : public testing::Test { protected: void SetUp() override {...
As I've mentioned in the comments, I had thought spdlog output to std::cout due to an earlier issue, but in fact that was related to stdout.. (facepalm) This is nice and easy, it turns out! By using an ostream_sink, the output can be sent to a specified ostream; I set a logger up in my test SetUp() function as follows ...
66,473,482
66,475,406
Boost asio deadline timer completing immediately (C++)
The code below prints "connected" to the console immediately, as opposed to after 10s. Why is this? Is it to do with the way I'm passing my print callback? void print(const boost::system::error_code& e) { std::cout << "connected!" << std::endl; } class WebSocketSession { public: WebSocketSession(asio::io_context ...
As mentioned in the comments, deadline_timer is destroyed too soon because it's a local variable, thus canceling the I/O operation. If we add some error handling, we will see the actual error reported: void print(const boost::system::error_code& e) { if (e.failed()) std::cout << "error: " << e.message() << ...
66,473,558
66,473,582
Understanding OpenGL glPushMatrix and glPopMatrix
I'm new to OpenGL and trying to render two objects, but only one of them should rotate. I learned from here that I can use glPushMatrix and glPopMatrix to apply the roration on only one object, but mine does not work. Here are my codes: void renderObjs() { //glPushMatrix(); drawPyramid(0, 0.7, 0, 0.289, 0, 0.16...
The matrix transformation operations like glRotatef, specify a matrix and multiply the current matrix by the new matrix. glPushMatrix pushes the current matrix onto the matrix stack. glPopMatrix pops a matrix from the matrix stack and sets the current matrix through the popped matrix. The unit of the angle of glRotate ...
66,473,648
66,474,010
Get proper term of person life using gmtime()
I'm trying to calculate exact age of person using difference between now and the date of birth. I'm getting difference in seconds, which, I suppose is correct value. Then i'd like to convert seconds into struct tm, using gmtime(). But it is giving me a tm_year on 70 bigger than it must be, and tm_mday on 1 bigger than...
It is translating "unix epoch time", which is seconds since 1970, to a date. It is not converting seconds to an amount of days/months/years. There is fundamentally no such conversion. 30 days can be less than or more than a month. 365 days can be a year, or 1 day less than a year. 24 times 60 times 60 seconds can b...
66,474,433
66,474,517
Force initialization to 0 when inserting into a std::map
I have a std::map<std::string,std::size_t> of keys mapping counters. When I increment a counter, I don't know if it already exists. If yes, it is incremented. If not, it is set to 1. This is easy to do: std::map<std::string,std::size_t> counters; //... auto c_it = counters.find(key); if(c_it == counters.end()) counte...
But this generates undefined behavior because std::size_t() is called when the counter doesn't exist in the map, and there is no guarantee that std::size_t() initializes to 0. This assumption is incorrect. Quote from cppreference: If an insertion is performed, the mapped value is value-initialized (default-construct...
66,475,237
66,475,270
Why does the post increment operator not increment the actual value of stored at an integer pointer?
I have the following code : #include<iostream> #define LOG(x) std::cout << x << std::endl; void Increment(int* a) { *a++; } int main() { int a = 8; int& ref = a; ref = 2; Increment(&a); LOG(a); } On running the executable, however, the output is 2 and not 3. I understand that *(pointer) gives t...
By the rules of operator precedence, your expression is interpreted as void Increment(int* a) { *(a++); } i.e. you increment a pointer, not it's value. You need to add parantheses: void Increment(int* a) { (*a)++; }
66,475,868
66,475,971
UserWarning: torchaudio C++ extension is not available
can someone please help me out with this UserWarning in torchaudio? ErrorMessage: C:\Users\anaconda3\lib\site-packages\torchaudio\extension\extension.py:14: UserWarning: torchaudio C++ extension is not available. warnings.warn('torchaudio C++ extension is not available.') Thank's in advance!
https://pytorch.org/audio/stable/backend.html says like this: Availability "sox" and "sox_io" backends require C++ extension module, which is included in Linux/macOS binary distributions. These backends are not available on Windows. So you have a wrong operating system or backend selected. Depends point of view :)
66,476,531
66,476,626
Why does sizeof operator on an array give incorrect result?
This is my code. #include <iostream> #include<sstream> using namespace std; int main() { ostringstream outStr; const char* strArray[]= {"Hi","How" ,"Howhuw","bdeuvc"}; int n; cout << sizeof(strArray); } Why am I getting the output 32? Can someone please explain this to me? I know I'm having an array of...
Sizeof returns the size in bytes. char x = 'a'; cout << sizeof(x); // this would be 1 This means that the space taken by the array of characters is their count * 1 byte int on most modern machines is 32 bit (4 bytes) If you had, let's say int array[] = { 1, 2, 3, 4, 5 } and you wanted to get the count of its elements ...
66,476,604
66,477,280
C++: Checking if the order of parentheses and brackets from a string is correct using stacks
I have to create a function using pop() and push() to check if the order of the parentheses and brackets is correct, for exemple "( ( [ [ ] ] ) )" is correct, but "( ( ( [ ] ] ) )" is not. My idea was to make a loop and for each iteration get a char from the string and check if its an opening (bracket or parentheses) t...
There are two problems in your code: you are doing pop for opening and closing brackets and plan was to do it only for closing brackets you didn't take into account possibility that stack can be empty during iteration. For example: ()) will lead to undefined behavior even if fix from other answer will be applied. If ...
66,476,606
66,476,680
Apply same method to many arguments using templates
I'm trying to create a template function that allows me to apply the same method to different objects, while aiming to minimize the number of lines. Here is more or less what I'm trying to do: #include<iostream> #include<map> #include<set> #include<vector> #include<list> using namespace std; template<typename ...Args...
With a fold expression (since C++17): template<typename ...Args> void clear_all(Args&... args) { (args.clear(), ...); } The important difference between this and your recursive solution is not the number of lines, but the fact that this does not rely on recursion. If you call clear_all(a,b,c,d) then one function ...
66,477,134
66,477,454
Question regard to this recursion function
A code to find a factorial of an input n: #include <iostream> using namespace std; long long factorial(int num) { if (num == 0) { return 1; } else { return num * factorial(num-1); } } int main() { int num; cin >> num; cout << factorial(num) << endl; } My questions are: H...
Recursive functions work exactly like non-recursive functions - there is no "loop" and nothing gets decremented. Perhaps the substitution method could help. Consider factorial(2). If we replace num with 2 in the function's body we get if (2 == 0) { return 1; } else { return 2 * factorial(2-1); } In order to ca...
66,477,209
66,477,349
Using possibility to move constant reference
void foo (const std::string& str) { std::string local = std::move(str); } I'm really confused that this is allowed. Am I missing something and in some cases it can be used? Like if I know that it's safe to move this string, should I still use this construction, or is it something that is allowed by the compiler but...
It is allowed in a sense that this code is syntactically correct. std::move is nothing but a glorified cast, which takes type of the argument into account when casting. If your argument type is const &, the object is casted to the same const &&, and when you call std::string local = std::move(str); you end up calling ...
66,477,521
66,477,633
va_arg begins by the second parameter on mac (clang++)
the code TextureMeta(string tex_, int args_, const char* ...) { va_list vl; va_start(vl, args_); for (int i = 0; i < args_; i++) { string img_(va_arg(vl, char*)); cout << img_ << endl; images.push_back(img_); } va_end(vl); } on MSVC it works fine but on MacOS the generat...
TextureMeta(string tex_, int args_, const char* ...) This is short for TextureMeta(string tex_, int args_, const char*, ...) It means that you have 3 regular arguments before the ellipse. What you want is: TextureMeta(string tex_, int args_, ...) Live
66,478,305
66,478,513
pointer array returns negative values
I am trying to calculate the arithmetic mean of the digits of a number from a number array. I'm trying to use dynamic memory allocation and pointers. I can't think of anything faster or better. void media_cifrelor(int *p, int &x) { int *w = new int[x]; for (int i = 0; i < x; i++) { int k = 0; ...
You are not initializing the elements of the allocated w array, so each starts off with an arbitrary/random value. To fix this, set each of the *(w + i) elements to zero before you start accumulating the sums of the digits: void media_cifrelor(int *p, int &x) { int *w = new int[x]; // Note: this memory is NOT zero-...
66,478,377
66,478,972
What is VS code's default documentation formatting
I have seen this doc formatting comment in a library I added to one of my workspaces, and I see it uses something close to doxygen, and it works great off the shelf with VS code, I didn't install doxygen or any other doc generator plug in /**********************************************************************/ /*! ...
Visual Studio and Visual Studio Code recognize Doxygen comment formatting. /**, /*! as well as ///-style comments are supported. There are also extensions that can generate doxygen comments.
66,478,960
66,479,219
Declaration after use
The draft C++20 standard N4861 sect. 6.5.1(7) reads: A name used in the definition of a class X outside of a complete-class context of X shall be declared ... before its use in class X or be a member of a base class of X.... So why does the following compile? #include <iostream> struct X { X(const int i_) : i(...
The key part to the paragraph you are quoting is outside of a complete-class context Inside a member function body, you are in a complete-class context. This means the rule does not apply. The full definition for a complete-class contect can be found in [class.mem.general]/7: A complete-class context of a class (te...
66,478,991
66,479,079
How to use std::remove_pointer with void*?
I am using std::unique_ptr in this way: template <typename Pointer, auto deleter> using my_unique_ptr = std::unique_ptr<std::remove_pointer<Pointer>, std::integral_constant<decltype(deleter), deleter>>; It seems to work when Pointer = void*, but when trying to use reset on such a my_unique_ptr, I am getting this error...
Your my_unique_ptr<void*> does not contain void*. It contains a std::remove_pointer<void*>*. Shouldn't std::remove_pointer<void*>* automatically mean void*? The std::remove_pointer type is not magic. It's a type like any other. Here's a possible implementation: template<typename T> struct remove_pointer { using t...
66,479,542
66,484,248
How to filter out nodes using libxml2
Given an XML document and an XPath expression, I want to create a new document which has all of the nodes of the original document with the exception of the nodes selected by the XPath expression, effectively giving the result of a subtract filter. My idea was to use the xmlXpathEvalExpression() function, and for each ...
As mentioned in the comments, the node pointers returned from evaluating an XPath expression point directly to the nodes in the original document.[1] So you can simply call xmlUnlinkNode on each node in the returned node set to remove it from the document. Then, in a second step, call xmlFreeNode on each node to free t...
66,480,011
66,480,440
QIcon working with qrc file but not with file system path
I tried to set the icon of my QMainWindow object using a .qrc file: window->setWindowIcon(QIcon(":Logo.png")); with a .qrc file like: <!DOCTYPE RCC><RCC version="1.0"> <qresource> <file>Logo.png</file> </qresource> and it worked, no problem. But when I tried to use actual file path it did not work. window->setWin...
By using qrc the image is stored in the application's executable and also loaded from there. If you don't use the resource system, the image is searched relative to the current working directory. In most cases the working directory is the directory of the executable. You have to copy the image in the same folder of the...
66,480,311
66,480,565
Segmentation fault when importing a C++ shared object in Python
I have the following shared object: MyLib.cpp #include <iostream> class MyClass { public: MyClass(){} void function() { std::cout << "hello" << std::endl; //var = 10; } private: int var; }; extern "C" { MyClass* create() { return new MyClass(); } void func(MyClass* myclass) { myclass->func...
The pointers are not the same: extern "C" { MyClass* create() { MyClass* myclass = new MyClass(); std::cerr << "Returning: " << myclass << "\n"; return myclass; } void func(MyClass* myclass) { std::cerr << "Calling: " << myclass << "\n"; myclass->function(...
66,480,367
66,490,181
Is using explicit return type in one translation unit and deduced return type in another allowed?
My question is similar to this one, but subtly different. Suppose I have two translation units, exec.cpp and lib.cpp, as followed: // exec.cpp int foo(); int main() { return foo(); } and // lib.cpp auto foo() { return 42; } Is it legal to compile and link them together? Or is it ill-formed NDR? Note: both ...
All standard references below refers to N4861: March 2020 post-Prague working draft/C++20 DIS.. From [basic.link]/11 [emphasis mine]: After all adjustments of types (during which typedefs are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be ide...
66,480,571
66,480,752
Can you put an if statement in a constructor in c++ to set up an object in a particular way?
I have a class that will take in 4 parameters when an object is created for it. These are: a character, and 3 integers. However, depending on what the character is, the object needs to be set up in a different way. e.g. if the character is 'T' then set all object parameters to 0 except for those given, but if the chara...
You can use a discriminating token to distinguish which constructor you want to invoke. Since, otherwise, the parameters are all of the same times in the example case. #include <iostream> class Foo { public: enum B_token{ B }; enum T_token{ T }; Foo(B_token, int, int, int); Foo(T_token, int, int, int)...
66,480,781
66,481,102
Which keyword will we use to exit EOF form c++ code?
I wrote c++ code in the codeblocks IDE. I use EOF but don't no which keyword i will use to exit form my code. Here is my code: int main() { int a, b; while ( scanf("%d%d",&a,&b)!=EOF) { printf ( "%d\n", a^b); } }
If you are using windows CTRL + C is the code for EOF() as Enter/Return key would add a newline only
66,480,832
66,482,489
Square matrix in c ++
I did the above code to calculate the matrix of a square matrix but it does not work, can someone explain the error to me please #include <iostream> using namespace std; int main() { int M[3][3]={{2, 4, -6}, {1, 5, 3}, {1, 3, 2}}; int n, mult; n=3; cout << "Matrix: " << endl; for (int i = 0; i < n;...
In this code, I replaced int by double, even if that, for this particular matrix, it would work with int. The main problem was that the output of the result was broken, 3 loops when two only are needed. Note that you don't check that the Gauss pivot M[i][i] is not null. The code should be completed to handle this case....
66,480,854
66,481,007
reasoning for set behaviour
In one of our university projects we are working on a benchmarking project. What we essentially do is generate a random no. and then insert it into a std::set (RBTree) and then delete it. We do this for a specific time interval. Essentially this is what the code looks like auto randomNo = std::random_device{}(); //Mea...
There are several things that go wrong here: You only measure one insertion or erasure. You should try to measure how long it takes to perform a hundred thousand entries and take the average. You don't perform any warm-up. The set operation might operate with a cold CPU cache, the next memory allocation might not be s...
66,481,425
66,481,729
Why is std::make_unique necessary to initialize member std::unique array, and how to work around for C++11?
In the following code, why is std::make_unique necessary to initialize Foo::up_? Specifically, why doesn't initializing Foo::up_ with new Bar(...) -- as in the commented-out code -- work? #include <iostream> #include <memory> enum E { Y = 0, Z = 1, NUM_E }; class Bar { public: // Functions Bar( const int& i, ...
1. The constructor unique_ptr( pointer p ) is marked explicit, which prevents instances of unique_ptr from being constructed implicitly in array list initialization. 2. std::make_unique is available since C++14. In C++11 a possible solution to both points is to construct an instance explicitly e.g. std::unique_ptr<Bar>...
66,481,482
66,504,224
Getting Overflow and TLE issues in this Atcoder question
I am solving this question: D-Base n (https://atcoder.jp/contests/abc192/tasks/abc192_d) It states that: Given are a string X consisting of 0 through 9, and an integer M . Let d be the greatest digit in X . How many different integers not greater than M can be obtained by choosing an integer n not less than d + 1 and s...
ll convert(string x, ll base, ll m){ ll ans=0; ll p=0; ll cur=1; for(int i=x.size()-1;i>=0;i--){ if(cur<0 || ans<0) return m+1; ans+=(ll)(x[i]-'0')*cur; cur*=base; if(ans>m) return m+1; } return ans; } void solve(){ ll i, j, m; stri...
66,481,936
66,484,459
Using variadic template arguments for arbitrary number of classes
I have a situation where I need a class FaceProp that maintains/holds other classes for actual face types. These could be any types of faces like boundary faces, solid faces, internal faces etc etc. I wanted to implement FaceProp using the variadic parameter pack feature in C++, but I am not sure how this can be achiev...
An example of how to do this using std::tuple as suggested in the comments. I showed it with and without std::unique_ptr. template <typename... FaceTypes> class FaceProp { FaceProp() { m_tuple = {FaceTypes()...}; m_uniqueTuples = {std::make_unique<FaceTypes>()...}; } private: std::tuple<FaceTypes....
66,482,010
66,486,976
Using functor in lambda
I'm getting hung up on some syntax for working with functors and lambdas in C++. I define functors as: class paint : public OpCode { public: using OpCode::OpCode; void operator()(std::int_fast32_t d) override { if (character_context->is_black()) { character_context->bitmap.add_blackline(cha...
Thanks to Remy Lebeau's directions, I have managed to figure out what I needed to do: I had to add const to the declarations of my operator functions, e.g., int_fast32_t operator()() const override { return file_context->read1(); } in an Argument implementation, with the abstract base class defining the method as ...
66,482,387
66,482,482
How can one update a class member/value from a function in c++
I have a class representing a player. Separated into a header and a source like this. #include "player.h" player :: player(std::string name,int money,int position,int pcode) : name(name), money(money), position(position), pcode(pcode) {} void player::setPlayer(std::string name,int money,int position,int...
Giving a class member function's parameters the same name(s) as class data members is, IMHO, poor practice (although I see it a lot, here on Stack Overflow). Consider your setName function: void player::setName(std::string name){ name = name; } The code in this function doesn't change anything in the class instanc...
66,482,526
66,482,612
Race condition stat and mkdir
I am working fixing on some coverity issues and i am confused about how to solve toctou for stat a directory and make a directory. //////////////////////////////////// // Make sure storage dir exists. If // not, create it. if( stat( dir, &statBuff ) != -1 ) { if( S_ISDIR( statBuff.st_mode ) ) { if( (dir...
Just do mkdir(). If the directory already exists, EEXIST will tell you. Accept either zero or this return-code to indicate that you have, one way or the other, now accomplished your objective. "Race conditions" cease to be an issue since mkdir() has taken care of that for you.
66,482,882
66,483,682
What are reasons for -march=native to be detrimental
I'm writing a C++ program that shall solve PDEs and algebraic equations on networks. The Eigen library shoulders the biggest part of the work by solving many sparse linear systems with LU decomposition. As performance is always nice I played around with options for that. I'm using g++ -O3 -DNDEBUG -flto -fno-fat-lto-ob...
There are plenty of reasons why a code can be slower with -march=native, although this is quite exceptional. That being said, in your specific context, one possible scenario is the use of slower SIMD instructions, or more precisely different SIMD instructions finally making the program slower. Indeed, GCC vectorize loo...
66,483,145
66,483,588
C++ variadic templates pack into std::array and unpack
I want to pack variables in an array and then unpack using an interface like this int x; float y; double z; auto data = PackArray(x, y, z); // serializes without padding ... int x; float y; double z; UnpackArray(data, x, y, z); // copies data from the array to x, y, z I tried template<class... T> constexpr size_t Su...
Here's my go at it: #include <array> #include <cstddef> #include <cstdio> #include <cstring> #include <memory> #include <type_traits> template <class... T> [[nodiscard]] auto PackArray(T&&... args) { static_assert( (std::is_trivially_copyable_v<std::remove_reference_t<T>> && ...), "Packing requires trivi...
66,483,308
66,484,026
Using member class template specialization in the class
Is there a standard complying way of using member class template specialization in the same class? struct S { template<typename T> struct Data; // Explicit (AKA full) template specialization is not allowed here. template<> struct Data<char> {}; template<> struct Data<int> {}; Data<char> d1; Dat...
Is there a standard complying way of using member class template specialization in the same class? Yes: use a conforming C++17 compiler. C++17 directly states: An explicit specialization may be declared in any scope in which the corresponding primary template may be defined However, C++14 says: An explicit special...
66,483,950
66,484,096
Iterator throwing an error when converting to string*
Consider the following piece of code, where: list<string> elements bool SearchElement(const string& product) { for (list<string>::iterator it = elements.begin(); it != elements.end();i++) { string& element = *it; if ( element == product) { return true; } } return false; } I want t...
An iterator acts like a pointer, but it is not a pointer. It refers to a value, but it is not itself a pointer. You can get a pointer, though: string* pelement = &*it; Note that although & and * are inverse operations on regular pointers, they are not so in general, and many types (specifically, iterators) override * ...
66,484,211
66,484,328
Variadic argument recursion without passing in instances of arguments
For some reason I can't seem to get this operation to work with C++11. template<typename T> int value(){ return 1;} template<typename T1> constexpr int SumCpp11(){ return value<T1>(); } template<typename T1, typename... T> constexpr int SumCpp11(){ return value<T1>() + SumCpp11<T...>(); } int main(int argc, cha...
As the error message says, when you reach the base case, i.e. with 1 template parameter, the compiler can't choose between the overloads of SumCpp11. The first overload says it has 1 parameter, and the second overload says it has 1 or more parameters. The rules for overloading don't allow for the first one to be chosen...
66,484,391
66,484,568
How to get the entire content of a variable in the debug watch window of visual studio
If i right click and copy i only get half text: - text 0x00000000000f20d0 L"_BinRun.IMAGE_DOS_HEADER := \"\t\tWORD e_magic;\n\t\tWORD e_cblp;\n\t\tWORD e_cp;\n\t\tWORD e_crlc;\n\t\tWORD e_cparhdr;\n\t\tWORD e_minalloc;\n\t\tWORD e_maxalloc;\n\t\tWORD e_ss;\n\t\tWORD e_sp;\n\t\tWORD e_c... ...
You can't. The string is too long to display directly in the debugger watch window. Use the String Visualizer by clicking the magnifying glass to the right of the variable. That's what it's for and then copy it from there: (Emphasis mine) While you are debugging in Visual Studio, you can view strings with the built-in...
66,484,876
66,484,975
Comparison of Strings in C++ not working -- Palindrome
Any idea why this doesn't work...i tried level as an input string and it says it's not a palindrome when it is... I am sure both str and reverse are exactly the same, Can someone point me to where b. Write a program that reads a word from the user and announces to the user if it is a palindrome or not. Your program ...
Your strings are not of the same length. Check this for yourself using str.length() and reverse.length(). The issue is that your for loop that iterates through str starts at too high a number. str.length is 3 but str[3] is the forth spot in the string str. You need to start at str.lentgh - 1 since array/string inde...
66,485,018
66,485,155
C++ While loop scoping issue
I recently started learning C++, and I'm currently trying build a tool that I recently built in python. My issue is that I can't figure out how I can make the length of the list of words global for example: #include <iostream> #include <fstream> #include <string> int main(int argc, char* argv[]) { .... fst...
string words[] = {tp}; creates an array with one element in it, the whole line. The name words implies that you instead want to store the individual words. The scope is also wrong if you want to use it after the loop is done. You need to declare it before the loop. Use a std::vector<std::string> to store the words. It ...
66,485,368
66,485,399
Why doesn't this function of my class work?
I have been trying to figure this out for now 4 hours. And I just can't find it, I give up. I have to create a class where I store the digits of large numbers in a vector. And I also have to create functions for them. One of them is for multiplying. I know this isn't how you multiply a large number, this is just a test...
Neither the constructor nor mul() are resizing the target vector at all. So, because the vector is empty, the loop inside the constructor is a no-op, and the loop inside mul() has undefined behavior for accessing elements out-of-bounds. Try something more like this: class largeNum{ public: std::vector<int> ...
66,485,626
66,485,823
How to create an array with Object that has private copy constructor
I have a struct that have some member and a Object that have private copy constructor, How can I create an array that include this object. For example: I have an Object: class Image { ... private: Image(const Image&); Image& operator=(const Image&); u8* pixel; int width; int height }...
You'll have to define the move ctor and move assignment operator on the Image class since the default implementations would be deleted because you provided a user declared copy ctor and copy assignment operator. You should then be able to use the vector with no issue. class Image { public: Image( int height, int wi...
66,486,387
66,486,516
Passing a subclass in a method that expects parent abstract class C++?
I'm working on an assignment with the following (simplified) structure. class A { public: virtual void method; } class B : public A { some variables; public: void method; } class C { public: void method1(A *a); } I have a C instance and B instance and try to call c.method1(b), where b is my instance of class B...
You cannot convert a B to a A*, but you can convert a B* to a A*. I think you simply forgot this & operator: main() { B b; C c; c.method1(&b); }
66,486,453
66,486,532
Referencing deleted destructor
I have the following code: struct Foo { int type; union { int intValue; double doubleValue; std::wstring stringValue; } value; }; and then in the cpp file I have: std::vector<Foo> row; some_class_object->func( row ); and I got: error C2280: 'void *Foo::__delDtor(unsigned int)':...
The union contains a member (std::string) with a non-trivial destructor. This means that the union can't have a defaulted destructor (it wouldn't know which member's destructor to call). So you need to provide a custom destructor. In your case define a union destructor that does nothing and then do the work in the stru...
66,486,874
66,515,897
How to read output of USB type B port into arduino?
I have an Arduino mega 2560 and I was wondering if it was possible to read MIDI data that is outputted from my MIDI keyboard. The USB type b port broke so I removed the port and wanted to know if I could directly connect the PCB contact pads to my Arduino and read the coming out. I could find no documentation on USB ty...
Short answer, no. To do so you need to convert the USB protocol to something that Mega 2560 can understand (ex. SPI, RS232, etc.). You can check USB_Host_Shield and see if this can help you.
66,487,350
66,492,385
How to force conan to build from source, but only if it is not in the cache?
I am using conan in an enterprise environment where the operating system is rather old and has an old version of glibc (2.11). As a result, a lot of the pre-built binaries on conan.io do not end up working in my environment. However, conan doesn't know that and will happily download and install them on my system, resul...
glibc version is an old headache for Conan, because it's not part of settings, thus is not counted as part of package ID. The Conan Docker images are running Ubuntu, some of them are old, others are new. But there is a specific Docker image running CentOS6, which was created because of glibc 2.12 and could help with pa...
66,487,631
66,552,981
curl_multi_wakeup doesn't seem to wakeup the associated curl_multi_poll - Android (but may not be limited to)
Curl version: 7.71.0 with c-ares Background We are building a library that's being integrated into mobile apps. We are targeting both iOS and Android. Curl initialisation happens in a static block inside the library. The iOS version of the library is bundled into a framework, which is loaded at app startup, if i'm not ...
Limitations on network activities for background processes Mobile operating systems such as Android and iOS have a different scheduling strategies for background processes compared to traditional *nix operating systems. The mobile OS tends to starve the background processes in order to preserve the battery time. This i...
66,487,961
66,488,075
check if 2 pointers are null or not
is it safe to check this way if both are nullptr, or there is a better way ? Thank you. #include <iostream> using namespace std; int main() { int *x; int *y; if (not (x or y)) { std::cout<<"both are nullptr"; } return 0; }
First off, you should use the actually operator names(! and ||) to increase readability(it might seem to you like this reduces readability, but once you get ahold of all of the operators, you'll find it easier this way). And yes, this is a valid way to check if both pointer are valid, but it is a bit confusing at first...
66,488,058
66,494,827
Get away with Initialize the char array without putting \0 at the end of string
I am new to c++ language,recently, as I was taught that: we should put '\0' at the end of char array while doing initialization ,for example : char x[6] = "hello"; //OK However,if you do : char x[5] = "hello"; Then this would raise the error : initializer-string for array of chars is too long Everything goes as I e...
The string literal "hello" has six characters, because there's an implied nul terminator. So char x[] = "hello"; defines an array of six char. That's almost always what you want, because the C-style string functions (strlen, strcpy, strcat, etc.) operate on C-style strings, which are, by definition, nul terminated. Bu...
66,488,388
66,488,540
C++ Make asks for a file that doesn't exist
When I try to build/compile my code, I get this error: make: *** No rule to make target '../../Source/GardenCounter.cpp', needed by 'build/intermediate/Debug/GardenCounter_15332182.o'. Stop. The terminal process "/bin/bash '-c', 'make QUIET=0'" terminated with exit code: 2. I don't have a file named GardenCounter.cpp...
Probably it would help to post your Makefile here. Without it, it's hard to know what the specific issue is. But here are some things to try off the top of my head: -Look for the name of that source file in your Makefile. Did you remove it from all the build dependencies there? -Is there a wildcard expression used some...
66,488,461
66,500,755
Finding the largest three-digits number "within" a number
For this question, I need to find the largest three-digit number within a larger number. Sample Test Case 1: 534535 Output: 535 Sample Test Case 2 : 23457888976 Output : 976 I've tried the following code: #include <iostream> using namespace std; int main() { int num; ...
#include <iostream> #include <string> using namespace std; int main() { int i, n; string s; cin >> s; n = (int)s.size(); if(n<3){ /* there are less than 3 digits in the input number Here, you can print the number itself as it will be largest number or print -1 which can state...
66,488,569
66,488,664
Nested list-initialization with non-copyable type does not work
void foo(std::pair<int, std::vector<std::unique_ptr<int>>>&&) {} foo({{}, {}}); The above does not compile with an error message reporting that it attempts to call into the copy constructor of std::vector<std::unique_ptr<int>> (which is deleted). However, the following works void foo(std::vector<std::unique_ptr<int>>...
It seems I have an answer to my own question -- this does not work because the nested list initialization overload only has the following std::pair constructor to match pair( const T1& x, const T2& y ); The other std::pair constructor with two arguments is templated without a default type, so it does not get considere...
66,488,850
66,488,916
How to print the enum value from its index?
I'm very new to CPP programming. I have a enum: emun foo { Apple, Banana, Orange } For example foo::Banana is printing 1, but if I have 1, how to print Banana to the output? It may be a very silly question.
The enum constants names are not known after your program has been compiled. To get the names, you can create an array so you can do the reverse lookup. Example: enum foo { Apple, Banana, Orange }; const char* revfoo[]{ "Apple", "Banana", "Orange" }; std::cout << revfoo[Apple] << '\n'; // Prints "Apple" ...
66,489,021
66,489,040
c++ std:: algorithms with reverse order (end, beg)
I want to use std::copy on a vector but copying the elements in reverse order. Since vector::begin() returns a random access iterator it seems like something that would work. Of course, I could use std::reverse before and after but that would be inefficient.
Class template std::vector provides reverse iterators. So instead of the member functions or stand alone functions begin and end you can use rbegin and rend. Here is a demonstrative program. #include <iostream> #include <vector> #include <iterator> #include <algorithm> int main() { std::vector<int> v = { 1, 2, 3,...
66,489,036
66,490,606
Are C++11+ compilers smart enough to optimize inner "if" statements?
This is best described with code: void foo(vector<vector<int>>& a, vector<vector<int>>& b, bool flag) { vector<vector<int>> c; for (int i ...) { for (int j ...) { int value; if (flag) value = a[i][j] + b[i][j]; else value = a[i...
There is little in the way of optimization in even the newest C++ standard today (2021), e.g. copy elision and return value optimization. This leaves 'compilers' to apply any platform-specific optimizations. The function in the question produces no effect and is thus most likely optimized away completely. But to addres...
66,489,666
66,490,557
Why doesnt private class member hold its value?
The following is a class template that implements a stack using an array: #include <iostream> using namespace std; template <typename T> class stack { public: stack (int priv_size) { T a[priv_size]; top = 0; } stack (const stack &s) { T b[priv_size]; for (top=0; top<s.pr...
Why are the two variables different and why is the one in the second image created in the first place? Because you declared two different variables. Its the same issue as in : struct foo { int x; foo(int a) { int x = a; } }; foos constructor declares a local variable named x which shadows the mem...
66,489,731
66,527,614
Cmake with Swig and go-integration wrapper errors
I'm currently trying to integrate a C++ lib with SWIG which is a wrapper generator for various language (UseSWIG). I want to integrate to golang and to do so, I'm using cmake to build it easily. My cmake is working when I'm building and it generates the wrapper file and the go file for having my go module. But in MSVC,...
Found a way to avoid those errors and the DLL is building fine for SWIG in MSVC: Add those lines at the beginning of your .i file: %begin %{ #define __attribute__(x) %} %include <windows.i>
66,489,935
66,490,099
How do you set a losing condition on a C++ Game?
/I tried creating a Guessing Number Game on C++, I went on ahead and make a program that generates a random number ranging from 1 to 1000, and set a winning condition. that is if the user input the random generated number then they won. but i also want to set a losing condition. for example, the user only has 10 tries ...
Instead of using while(true) you can just use a for loop: #include <string> #include <iostream> #include <cstdlib> #include <ctime> using namespace std; void tips() { std::cout << "Pay attention to what the system inputs.\n"; std::cout << "If Too High, Lower you're number base on your latest guess\n"; std...
66,490,697
66,490,816
Is creating unique_ptr thread safe
std::array<unique_ptr<SomeClass>, 1000> globalArray; void foo(int index) { globalArray[index] = make_unique<SomeClass>(); //or globalArray[index] = std::unique_ptr<SomeClass> p(new SomeClass); ? } considering here that I'm sure about index that are passed to the foo, that they will not repeat and will not exceed g...
Is creating unique_ptr thread safe The creation of std::unique_ptr from the pointer is thread safe. Furthermore, accessing a unique index of an array is thread safe. Although constructors are often thread safe, we cannot know whether the default constructor of SomeClass is safe without knowing its definition. Further...
66,490,778
66,623,735
wxCopyFile; "ERROR 5: Access is denied" even when running with administrator privilages
I'm writing a very simple program which edits an XML file and copies a user specified image to the folder in which the .exe runs. The problem I'm having is with wxCopyFile. When I first ran the program (with debug mode in Visual Studio 2019) I got "error 5: Access denied", so I tried running the .exe from the Debug fol...
From wxCopyFile() documentation it appears that both its arguments must be file names; however, your second argument is a directory. This results in the function trying to create a file where a directory with the same name already exists, resulting into the error. Therefore, you need to provide a full path including th...
66,490,922
66,494,925
Error when make a build of the game in Uneral Engine
When I try to make a build, I'm getting error Cannot open include file: 'Actions/PawnAction.h': No such file or directory But I have this file in Visual Studio
You need to include AIModule in your module dependencies. Source: JamieDale from UE4 Q&A site: Right, so if your game was called "MyGame", then you'd have a file called "MyGame.Build.cs" inside the "Source\MyGame" folder. This file tells the UnrealBuildTool (UBT) what to do when building your game. In there you should...
66,491,079
66,516,905
OpenGL 1 pixel high texture rendering difference Windows/Linux vs OS X
I need help understanding why I need to do a specific change to make my OpenGL project work on OS X (2019 Macbook), while without the change it works perfectly on Windows and Linux, on both ATI and NVIDIA hardware. At some point I'm rendering to a frame buffer that is 1024 pixels wide and 1 pixel high. I need straightf...
OpenGL is not specified as a pixel-exact rendering API, and GPUs and different drivers (even on the same GPU) do not produce identical output with identical inputs. However, the OpenGL specification actually makes hard requirements the implementators must fillfill, and you as user of the API can rely on. In your case, ...
66,491,080
66,499,205
Deduce callback arguments type and use them as return type
I have some function that can take some arguments and callable object(last argument) as callback with results. I want to transform it to a regular call. I tried this approach and it works, but I must specify arguments types every time. Is there a solution that can help me with automatically deducing callback arguments ...
Non sure to understand what do you exactly want but... what about a main call() that receive std::functions template <typename Arg> auto call(std::function<void(std::function<void(Arg)>&&)> const & f) { Arg res; f([&](Arg arg){ res = std::move(arg); }); return res; } plus an auxiliary call() for functi...
66,491,314
66,550,799
Sparse matrix without knowing size
Does Eigen support element insertion into a sparse matrix if the size is not known? I have a stream of data coming in, and I am attempting to store that sparsely, but I don't know the maximum value of the indices (row/column) of the data ahead of time (I can guess, but not guarantee). Looking at Eigen's insert code, i...
The recommendation is still to store the values into a intermediate triplets container and build the sparse matrix at the end. If you don't want to read all the stream... then just read first nnn triplets until your desired condition and then use setFromTriplets() with the partial list of triplets. But, if you still do...
66,491,814
66,492,455
CMake not finding GL/glew.h
I'm using CLion under pop_OS! 20.04 and am currently trying to get CMake to work with GLEW because I want to follow these tutorials to get started with OpenGL. I'm relatively new to C/C++ and completely new to CMake. I installed the libgl1-mesa-dev,libglew-dev,libglfw3,libglfw3-dev packages with apt-get install and the...
Your last try was nearly right. Forget about include_directories and link_libraries commands. All it needs when doing modern CMake is an add_executable(test main.cpp) followed by a target_link_libraries(test PRIVATE GLEW::glew) command. The target GLEW::glew (case matters here) bundles all compile definitions, include ...
66,491,831
66,491,910
Can we iterate through an array passed to a function using for-each loop?
I know we can iterate through an array passed as an argument in this way: // NO ERROR void fun(int *a, int n){ for(int i=0; i<n; i++) cout<<a[i]; } But, is there any way I could iterate through an array using a for-each loop inside a function like this? // ERROR void fun(int *a, int n){ for(auto x:a) ...
A pointer is not an array. If you pass a pointer to the first element of an array to a function then its no longer an array, but a pointer. You can use a range based loop when you pass the array by reference: #include <iostream> template <size_t N> void foo(int (&x)[N]) { for (int i : x) std::cout << i << " "; } ...
66,492,071
66,492,740
subdirectory with 3rd party library gets not compiled
I want to use rpclib from here. I started a new project with main.cpp and CMakeLists.txt and copied the rpclib as a subdirectory into my project: My code is exactly the example from rpclib and looks like this: #include <iostream> #include "rpc/server.h" void foo() { std::cout << "foo was called!" << std::endl; } ...
You're missing a target_link_libraries(RPC_Test PRIVATE rpc) after the definition of the RPC_Test target . rpc here is the name of the library target defined in rpclib's CMakeLists.txt, not just the base name of the resulting binary artifact. When using a target name with target_link_libraries like that CMake will not ...
66,492,445
66,492,660
Assigning length of a string to an integer: C++
Using C++, I want to create a for loop as follows (text is a std::string): for(int i = text.size(); i >= 0; i--) { { Please could somebody help me understand why my complier (Xcode) requires me to initialise i as an unsigned long, and not as integer? I assume the following, but I don't know, and I'd like to develop ...
std::string::size() returns an unsigned integer type (std::size_t). Changing the type of i is easy enough, but introduces another problem. With i being type std::size_t the loop condition is broken; by definition an unsigned type is always going to be >= 0 There are alternatives, the most direct being to modify the ent...
66,492,865
66,492,952
How to associate an operator with a priority value?
I want to implement the Reverse Polish notation. In order to do that, I have to implement a table which stores priority for operators, as such: operator priority ( 0 +, - 1 *, / 2 How do I do that?
Since you have a fixed-number of key-value pairs that are known at compile time, you don't need the dynamic nature and overhead of std::unordered_map. You can use a simple switch statement, which is static and harder to get wrong: int get_priority(char const op) { switch (op) { case '(': return 0; case ...
66,492,975
66,494,134
Parse URL "query" part
In https://www.rfc-editor.org/rfc/rfc7230#section-2.7.1 with reference to https://www.rfc-editor.org/rfc/rfc3986#section-3.4 described uri format. And in particular the "query" part The query component is indicated by the first question mark ("?") character and terminated by a number sign ("#") character or by t...
"?" starts the query part in any URI (not only http(s)). If you need a "?" in the path, you'll need to percent-escape it.
66,493,385
66,493,622
How to remove the second duplicate character in cPP string
I want to remove the second appearance of a character in a string. so far I have made a function that is able to remove the first appearance. For example: I want my function to do CACTUS --func--> CATUS removing the second 'C'. But my function remove the first one CACTUS --func--> ACTUS Can someone suggest something? ...
You could use a counter to count how many times a has been seen in the string and only skip that char if it's the second time it's seen. std::string Remove_char(const std::string& A, const char a) { std::string B; B.reserve(A.size()); unsigned seen = 0; for(char ch : A) { // add all charact...
66,493,835
66,494,989
What is the "correct" way to go from avx/sse masks to avx512 masks?
I have some existing avx/sse masks that I got the old way: auto mask_sse = _mm_cmplt_ps(a, b); auto mask_avx = _mm_cmp_ps(a, b, 17); In some circumstances when mixing old avx code with new avx512 code, I want to convert these old style masks into the new avx512 __mmask4 or __mmask8 types. I tried this: auto mask_avx51...
Use an AVX-512 compare intrinsic to get an AVX-512 mask in the first place (like _mm_cmp_ps_mask); that's going to be significantly more efficient than comparing into a vector and then converting it, unless the compiler optimizes away this inefficiency for you. (Consider using a wrapper library like Agner Fog's VCL to...
66,493,865
66,497,035
Tradeof between CMAKE_BINARY_DIR and PROJECT_BINARY_DIR when setting submodule targets' output directories
I'm working on a library which will be used by another project. The main project uses a couple of libraries linked as git submodules. Inside the library project used as a submodule, I can set the LIBRARY_OUTPUT_DIRECTORY and the ARCHIVE_OUTPUT_DIRECTORY in two different ways. In option A the targets are built and saved...
Unless there is a good reason you shouldn't set the output directory for your targets in the library project at all. If consumers link to the CMake targets provided by the library project then they usually don't even need to know where exactly these libraries will be located, and even if they do they have access to the...
66,493,887
66,494,068
c++ My random gen randomly gens something but it does it in the same order every time u run it
So ive made a MAC Address generator. But the random part is very strange. It randomly generates a number that i use to choose something from an array. But each time you run the exe. It gens the same number. Here is my code #include <random> #include <string> //Mac Addr example -> 82-F5-4D-72-C1-EA //6 two char sets //D...
rand() is a deterministic random number generator . In order to achieve actual pseudo-random results you should first seed it with something like srand(time(NULL)) . If you look around this you will realize that this is a bad approach and you should instead give up rand() altogether , instead use <random> from C++11 . ...
66,493,926
66,494,356
Don't really get the logic of std::atomic::compare_exchange_weak and compare_exchange_strong
I've read https://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange Atomically compares the object representation (until C++20)value representation (since C++20) of *this with that of expected, and if those are bitwise-equal, replaces the former with desired (performs read-modify-write operation). Otherwise, lo...
I will give an example where I did used that, since it is very simple one. I had atomic which describes available size of something. There was a danger of integer overflow, so I had do checking first before subtracting a value. Not exact copy paste of my production code: class LockFreeCuncuretSizeLimit { public: ex...
66,494,163
66,496,953
C++ QueryDosDeviceA() return 0 but COMX is connected
so I'm doing a function to retrieve all the COM serial port names connected to the system using QueryDosDeviceA I tried to use CreatFileA with "\\\\.\\COM6", and it doesn't throw me any errors. But QueryDosDeviceA with "COM6" or "\\\\.\\COM6" Function.cpp std::vector<std::string> SerialPort::_SerialList() { std::ve...
Thanks to @user253751, @JohnnyMopp, @dresscherjm And @RemyLebeau Here is the code that include the solution: std::vector<std::string> SerialPort::_SerialList() { std::vector<std::string> serialList; std::string COMName("COM"), queryName(""); CHAR bufferTragetPath[5000]; std::string tmp; DWORD path_s...
66,494,438
66,495,110
cannot pass deleted lambda function with move?
I have the following lambda expression: auto pPerson = std::make_unique<Person>("Person"); auto personLambda = [=, persPointer = std::move(pPerson)](int x, int y) mutable { //do stuff }; acceptLambda(myVector, personLambda);//compiler error acceptLambda(): template<typename Func> void...
Let's start with a the error message: function "lambda []std::string (int c, int y) mutable->std::string<unnamed>(const lambda []std::string (int x, int y) mutable->std::string &)" (declared implicitly) cannot be referenced -- it is a deleted function That's a mouthful. It's more understandable if you recognize that ...
66,494,576
66,494,760
Why are some letters of an array not turned to uppercase when not initializing my array?
I have noticed that when I don't initialize the array in this code that turns lowercase to uppercase the code only does half of the work (it turns Antoine Copepe -> aNTOiNE_cOPEPE). I was wondering if there were the null reference errors Kevin was talking about in his answer to how much important it is to initialize ar...
You should just get rid of the Arr variable entirely, and conio for that matter. It's using non-standard code. Your three loops can be combined into one using if-else-if statements, which allows your to get rid of the Arr variable easily. void ConvMl_(char Nombre[], int Len){ for(int i=0;i<Len;i++){ if...
66,494,672
66,495,547
Is c++ standard library containers have no implementation?
I'm reimplementing c++ std containers. In "Professional C++ by Marc Gregoire" I read this quote c++ standard specify the interface but not the implementation, of each container Implement means just "template class" code in Container? what is implementation in c++ Standard container library?
The C++ standard specifies functionality. It does not care how that functionality is achieved. This is similar to a coding homework problem. The teacher specifies the functionality required of the student's code, while the student decides how to achieve that. Typically, there is more than one correct answer. Let us lo...
66,494,942
66,495,020
C++ accepts int to be elements in a vector of chars
I am using Clang on a mac. I initialise the vector with string, it raises error as expected std::vector<char> vec{"eqfqa"}; // error: no matching constructor for initialization of 'std::vector<char>' I accidentally initialise the vector with int: std::vector<char> vec{1, 2}; // No errors reported for (auto&& item : v...
The int is convertible to a char (with loss of precision of course), so the code compiles, but the ASCII codes for 1 and 2 are not printable. In your first example, a char const* is not convertible to a char, hence fails to compile.
66,496,085
66,496,453
Function returns value in hex
I made a function to double every other digit of a number, but for some reason it converts the in to hex before returning. I checked, and that hex is accurate to an actual number, but how do I get it to stop returning hex? Here's the code. unsigned long long* Luhn_Algorigthem::double_every_other_value(unsigned long lon...
@TheUndedFish helped solve the problem for me, I ended up just getting rid of the pointer, and used the doubled val variable for it instead without allocating memory to the heap. This is the updated code: unsigned long long int Luhn_Algorigthem::double_every_other_value(unsigned long long int in) { //unsigned long ...
66,496,096
66,496,573
How to Recursively remove adjacent duplicate characters?
It's output look like: Hello =>Helo Problem require: no loop Except for the originally used string methods (size(), substr(...)), no other methods (for example, find(...), erase(...)) can be used. I tried several times, but it usually have weird output. And my idea is that it will be made up from the back. Here is m...
Try this void removeAdj(string& strIn, int pos=0) { int len = strIn.size(); if (pos == len - 1) return; if (strIn[pos] == strIn[pos + 1]) strIn = strIn.substr(0, pos) + strIn.substr(pos+1, len-pos-1); else pos++; removeAdj(strIn, pos); }
66,496,158
66,496,378
Correctly using C++20 `[likely]]`/`[[unlikely]]` in `switch` statements
C++20 has handy [[likely]]/[[unlikely]] attributes which guide code generation. For example, you can specify a branch is likely to be taken by: if (b) [[likely]] { /*...*/ } Similarly, it is possible to use these attributes in switch statements . . . somehow? The documentation suggests the following example (slightl...
Both examples are valid, and Clang is exhibiting a bug. The relevant verbiage from the last standard draft for C++20 is [dcl.attr.likelihood] 1 The attribute-tokens likely and unlikely may be applied to labels or statements. Where the relevant grammar productions for statements and labeled statements have an attribut...
66,496,199
66,497,427
How to copy values from a non const vector to a const vector in C++?
I have the following class where I have a private member vectortest which I would like to use as a computation variable for operations within the class member functions. Then, I would copy the computed vector to another vector cvectorin, which is a public member but a constant so that the contents cannot be modified, y...
As mentioned in the comments, a better approach would be to change your API to look something like this: class constVecTest { private: vector<int> vectortest; vector<int> cvectorin; public: constVecTest(vector<int> vin); const vector<int> &get_cvectorin() const { return cvectorin; } vector<int> ...
66,496,375
74,412,242
Improving lock-free linear allocation to be wait-free
Given the following simple lock-free linear allocation algorithm I made: bool allocate(size_type size, size_type& offset) { size_type pos; size_type new_pos; pos = m_pos.load(std::memory_order_acquire); do { new_pos = pos + size; if (new_pos > m_end) return false; ...
Let's say we have 256MB of space. The first thread tries to allocate 257MB of space, which obviously returns false. To handle that, you can store two ints: One atomic, with current_pos One non atomic, with capacity then: // first attempt, atomic load current_pos // to early exit when the allocation would certainly...
66,496,724
66,499,000
Simple QImage animations in Qt
I would like to achieve the following in a simple (not necessarily most efficient and/or elegant way): I want to create a 320x200 QImage that I keep updating with setPixel commands. The QImage should be shown on screen and updated whenever something has changed. The could could for example look like this: QImage image ...
A infinite loop in your application's main thread will block the core application to process any GUI events. The simplest way to perform the operation frequently is to use a QTimer: #include <QTimer> // you can start the timer in your main window constructor MainWindow::MainWindow(QWidget *parent) : QMainWindow(pa...
66,497,698
66,497,884
How can I pass an object's member variable (field) as a reference to a thread safely?
Let's say I start a new thread from a classmethod and pass "this" as a parameter to the lambda of the new thread. If the object is destroyed before the thread uses something from "this", then it's probably undefined behavior. As a simple example: #include <thread> #include <iostream> class Foo { public: Foo() : m...
Forget about member variables or classes. The question then is, how do I make sure that a thread does not use a reference to an object that has been destroyed. Two approaches exist that both effectively ensure that the thread ends before the object is destroyed plus a third one that's more complicated. Extend the obje...
66,498,433
66,498,555
JNI - SIGSEGV signal SIGSEGV: invalid address when in worker thread
I have a JNI call from android, where I send data (bytes, width and height) for image processing. The function works fine when executing from the main android thread. I want to call from another thread, to avoiding blocking UI, but when I do that the JNI throws a memory error. If I call from main thread, works fine. Th...
auto image_data_size = env->GetArrayLength(image_data); jint image_data_buf[image_data_size]; Don't make a C-style array if you don't know the size at compile time. See: Why does C++ allow variable length arrays that aren't dynamically allocated? Use std::vector<jint> image_data_buf(image_data_size) instead.
66,498,579
66,499,012
VS2019: [C6386] Buffer Overrun while to
void Counting_Sort(vector<int>& A) { const int size = A.size(); int max = A[0]; for (int i = 1; i < size; i++) if (max > A[i]) max = A[i]; int* C = new int[max + 1]{ 0 }; for (int i = 0; i < max + 1; i++) C[A[i]] = C[A[i]] + 1; for (int i = 1; i < max + 1; i++) C[i] = C[i] + C[i - 1]; int* B = n...
I notice four separate issues with your sample code: The computation of maximum is incorrect. Your condition should be testing if (A[i] > max) The Counting Sort algorithm's "accumulation step" should be iterating over the input data. That is, the loop should be the following (up to size, not up to max + 1): for (int...
66,498,882
66,499,241
Identify Integers and replace digits with X
So, I am working on a program that replaces every digit entered into cin with an x but if it's something like john17 then don't (so basically, if the word is an integer, replace the digits, else, keep the word as-is). I am struggling to find a solution here. How do I break up the words in the line entered and test whet...
You are not that far off. replace_num_with_x() is creating a stringstream that is not being using anywhere. Change the loop to read individual words from that stream, eg: #include <iostream> #include <string> #include <sstream> using namespace std; string replace_num_with_x(const string &str); int main() { cout ...
66,499,416
66,499,470
What's wrong with my ternary `if` expression?
i understand that the conditional operator ? can be used to simplify the if conditional but i'm really having a hard time with it, is it possible to use it as a loop ? for example in the code here it keeps telling me that i can not use r as a function what exactly am i missing ? #include <iostream> using namespace st...
The ternary operator (?:) can be easier described using a function: #include <iostream> template<typename T> T &ternary(bool a, T &b, T &c) { if (a) return b; else return c; } int main() { // The behavior is not completely equivalent // This example just explains the basic concept of t...
66,499,444
66,533,992
In Visual Studio 2019, linking plain C++ project to Dot Net 5 project builds an invalid executable
Summary: I am using Visual Studio 2019, and trying to create an example that links a plain-old-C++ project to a C++/CLR project that targets .NET 5.0. The solution compiles and builds, but attempting to run it produces an error message saying "not a valid Win32 application." Question: How can I produce an executable...
I discovered that I can get a valid executable if I link to CppShim5.lib instead of CppShim5.obj. Details for how to alter the example in the original question: Add a class to CppShim5 and mark it as exported from the DLL (by using __declspec(dllexport), see also: https://learn.microsoft.com/en-us/cpp/build/exporting-...
66,499,703
66,499,765
Shift matrix columns/rows in all directions c++
I have a 2d vector that looks like this: a b c d f g // actual size is 32 x 32 h i j And I want to shift the rows/columns: d f g h i j b c a c a b h i j <-- up a b c <-- down f g d <-- left g d f <-- right a b c d f g i j h j h i In python I can ac...
There is std::rotate() that can do this for you. To rotate the contents of each row: vector<vector<string>> matrix{{"a","b","c"}, {"d","e","f"}, {"g","h","i"}}; for (auto &row: matrix) { std::rotate(row.begin(), row.begin() + 1, row.end()); } To rotate the contents of the columns, you just rotate the outer vector...
66,499,755
66,975,480
Suitable IPC between a C++ DLL (local hooks) and C# application
Whats the best inter-process communication for a C++ DLL that's injected into a third-party process and a C# application? Here's the current situation: // This gets executed within the target process memory region LRESULT CALLBACK HookProc(int code, WPARAM wParam, LPARAM lParam) { if (code > 0) { auto c...
I ended up creating an invisible dummy window to serve as a central point for receiving messages through SendMessage calls from the DLL.
66,499,990
66,500,028
C++ : redefinition of 'class FiguraPlaska'
i have a problem with my exercise. If I add Trojkat.h it doesnt work. If I comment it, then it works. I have no idea why it doesn't work. I'm 80% sure that everything is fine and something is buggy... anyway hopes that someone can help me FiguraPlaska.h #include <iostream> class FiguraPlaska { protected: virtual v...
You should put similar include blocks in FiguraPlaska.h too. #ifndef FIGURA_H #define FIGURA_H class FiguraPlaska .... #endif Why? Because when you actually compile with your current code, you include the same class twice. e.g. take a source file that does #include "prostokat.h" #include "trojkat.h" then after unw...
66,500,102
66,501,135
How to print the content of a string as "sting literal source"
Suppose s is a b c const std::string s = std::cout << R"( s )" << std::endl; How to std::cout the content of the string in raw literal? I mean the cout return the value in this format: "a\nb\nc". I need to transform a very large text into a std::string. I cant use fileread as i need to define its value insid...
You can load this text file into a std::string like this: Store the text in your file, e.g. mystring.txt, as a raw string literal in the format R"(raw_characters)": R"(Run.M128A XmmRegisters[16]; BYTE Reserved4[96];", Run.CONTEXT64 := " DWORD64 P1Home; DWORD64 P2Home; ... )" #include the fil...
66,500,560
66,501,324
C++ game engine scripting can't load variables
So I'm programming scripting for my game engine and everything seems to work but if any variables are involved it crashes in random ways. I get the script by checking the folder in which my scripts are contained. I then get all the dll files in that folder and register them into the ScriptManager. Then in the NativeCom...
So I fixed it. I had no idea how to do any of this DLL linking so I found this amazing article here: https://www.gamasutra.com/blogs/ZacHills/20170406/295378/Scripting_with_C.php. I then followed along and then one thing that I did differently was instead of storing the createScript(); function itself I stored a pointe...
66,501,017
66,501,223
Can you copy Derived Class objects from one std::vector<std::unique_ptr<BaseClass>> to another std::vector<std::unique_ptr<BaseClass>>?
I have two vectors. I register derived classes in one vector, then want to make copies and copy them over to the other vector. I am trying to do this to avoid base class slicing, but be able to have "templates" of classes that I use to spawn new objects that I can mutate from those. How do I clone an object pointed t...
How do I clone an object pointed to by unique_ptr and have a new unique_ptr that I can store in a vector? C++ has no facility to handle this automatically, you have to implement it manually in each derived class, eg: #include <iostream> #include <memory> #include <vector> class BaseClass { virtual void doSomethi...
66,501,157
66,501,376
How to specify the c++ version in gradle?
I just started to learn Gradle. I don't know how to set the language standard. I use gradle + CLion.
For many C++ compilers, the language standard to which it adheres is set by using a std compiler option. For example, to set the standard to C++ 20 when using a Microsoft compiler, use its compiler option /std=c++20 (on non-Windows systems, such a compiler option may appear as -std=c++20). I'm not very familiar with se...
66,501,271
66,501,299
Are all non-member function pointers the same size in C++
In the C programming language, we are given the guarantee that a function pointer may legally be converted to a function pointer of a different type and back without loss of data: Section 6.3.2.3, paragraph 8: A pointer to a function of one type may be converted to a pointer to a function of another type and back agai...
Yes, quoting from expr.reinterpret.cast/6: A function pointer can be explicitly converted to a function pointer of a different type. [Note 5: The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined ([expr.cal...