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
73,430,966
73,432,583
How to conditionally enable console without opening separate console window
I'd like to create a windows application that, under normal conditions, does not have any connected terminal, but may have one in some conditions. I tried two different routes. Option A, creating a normal console application, and conditionally calling FreeConsole(): int main() { if (someCondition) { HANDLE ...
Impossible. AttachConsole does not work 100% because cmd.exe actually checks if the process it is about to start is a GUI app or not, and alters its behavior. The only way to make it work is to have two programs; myapp.com and myapp.exe. %PathExt% lists .com before .exe so you can make a console .exe and rename it .com...
73,431,360
73,431,411
How to dynamically reference to different non-copyable/non-moveable object without using raw pointer?
I am catching up c++17/20 recently. A while ago, I read a blog post from modrencpp: no new new. I found out that raw pointer is not recommanded and should be avoid in the future. edit: add explaination of what I try to accomplish. As an exercise, I start to modernize our project's code and replace raw pointer by using ...
The recommended approach for how to solve this problem would be to use a smart pointer, like unique_ptr, to solve this problem. You can't return by-value, as you have found, and raw pointers don't convey proper ownership. The approach you attempted with unique_ptr is mostly correct in terms of what would be ideal -- on...
73,431,435
73,433,728
How to convert nanoseconds to ptime in boost C++
Say I have a nanoseconds, 1614601874317571123. This represents the nanoseconds from epoch (1970-01-01). That is "2021-03-01T12:31:14.317571123" in ISO format I want to convert it to boost::posix_time::ptime. I know I could define a function like, #include <boost/date_time/posix_time/posix_time.hpp> #define BOOST_D...
You already have the "correct" solution (although the code shown is incorrect, the define MUST precede any headers that may include Boost Datetime stuff). Also note that return pt::ptime(gr::date(1970, 1, 1)) + pt::time_duration(0, 0, 0, nanos); should probably just be return pt::ptime({1970, 1, 1}, pt::time_duration(...
73,431,467
73,436,618
Making a special constructor inaccessible to users but accessible to std::construct_at
My code needs a special constructor that std::construct_at can use. This works fine if it's public but then it can be accessed by users of the class. If it is private, std::construct_at fails. Here's the minimal code: #include <memory> #include <iostream> class Vec { public: int* const p{}; const int len{}; ...
But it seems odd that std::construct_at can use it since INNER is defined in the private segment. Is std::construct_ats use of INNER legit? std::construct_at by itself only use public interface. it is legit. passkey idiom has some caveat though, and you are misusing it. private forbids to use the name explicitly, but...
73,432,708
73,438,317
How to make a widget blink in Qt with a delay of one second?
I want to show and hide a widget with an interval of one second. My code is like: if(ui->widget->isVisible()) ui->widget->hide(); else ui->widget->show(); I need a one-second gap between showing and hiding my widget. I also want this to be repeated so that the widget starts blinking.
With QTimer it should be posible: QTimer *timer = new QTimer(this); constexpr int i = 1000; // 1s timer->setInterval(i); connect(timer, &QTimer::timeout, this, [this]{ if (isVisible()) hide(); else show(); }); timer->start();
73,432,751
73,432,993
wrong output in vscode and codeblocks
This code snippet is supposed to return the reverse of the given integer and in the Sololearn compiler it works but in VSCode and Code::Blocks the output is different. For 543 it returns -93835951 in VSCode and 694653940 in Code::Blocks. Does anybody know why? #include <iostream> using namespace std; int main() { ...
Here is the working version with a bit of refactoring but still keeping it very similar to your snippet: #include <iostream> int main( ) { std::cout << "Enter a number: "; int num { }; std::cin >> num; int sum { }; while ( num > 0 ) { const int remainder { num % 10 }; sum = s...
73,432,871
73,746,303
Not declared in the scope error, C++ sfml
The compiler error says that "mango" was not declared in the scope. I don't understand why. Mango is a sprite defined in another function in another cpp file. all im trying to do is load a sprite on the screen. I'm sure it's a silly error, I apologize in advance. I'm new to C++. main.cpp: #include "test.h" #include <S...
Just a quick introduction to scopes in c++. There are a few different ways scoping can work, depending on the type of variable you're using but in general most variables have an automatic scope which means they are created and destroyed automatically. The rules of thumb are: Any two functions are not correlated with e...
73,433,132
73,433,364
using Membrane keypad to answer math prob. Arduino
I am trying my first project in Arduino. I am trying to use my Membrane Switch Module to answer simple math prob. like 1+1. in general, I am trying to make my Arduino do the following: ask for an answer to 1+1 if the answer is correct turn the light on for 30 sec else blink 3 times and ask again... the result for my co...
See the documentation: https://playground.arduino.cc/Code/Keypad/ getKey returns the currently pressed key, as you wait 10 seconds between calls to getKey it's likely that you'll miss your key presses unless you hold the key down. You should use waitForKey instead.
73,433,381
73,436,511
Is it valid to use void* rather than any pointer type if we always static_cast<> it?
Lets assume that we have following code: struct VeryComplexStruct { // a very complex struct void test() {} }; void foo(VeryComplexStruct **ptr) { // do something } int main() { VeryComplexStruct *p = nullptr; foo(&p); p->test(); } I wonder if the code is still valid by C++ standard if we just use void*...
reinterpret_cast<VeryComplexStruct **>(&p) There is no guarantee that the alignment requirements of void* and VeryComplexStruct* are compatible. If they are not and &p is not suitably aligned for a VeryComplexStruct*, then the value resulting from this cast will be unspecified and using it in basically any way will ca...
73,433,646
73,434,010
std:bitset c++ external initialization
I want to wrap or cast a std:bitset over a given constant data arrary or to formulate it differently, initialize a bitset with foreign data. The user knows the index of the bit which he can check then via bitset.test(i). Data is big, so it must be efficient. (Machine bitorder does not matter, we can store it in the rig...
Unfortunately std::bitset does not have suitable design for what you want. It is not designed an aggregate (like std::array is) so aggregate initialiation is impossible (and also copying bits into it with std::memcpy is undefined behavior). It can take only one unsigned long long in constexpr constructor. The operator ...
73,433,917
73,433,935
glGetUniformLocation returning -1 on OpenGL 4.6
I'm writing a small "engine", and the time has finally come to implement transformations. However, when I try to glGetUniformLocation, it return -1. Here is my rendering method: void GFXRenderer::submit(EntityBase* _entity, GPUProgram _program) { if(_entity->mesh.has_value()) { mat4 mod_mat(1.0); ...
See glGetUniformLocation. The uniform location must be requested from the linked program object, not from the (vertex) shader object: int transform = glGetUniformLocation(_program.vsh.id, "transform"); int transform = glGetUniformLocation(_program.id, "transform");
73,434,121
73,916,018
Why default operator delete[] can't deallocate the memory allocated by default operator new?
Due to unspecified overhead, it is illegal to deallocate with delete-expression that does not match the form of the new-expression. However, default operator new and operator delete isn't the same. operator new[]: [new.delete#array-4] Default behavior: Returns operator new(size), or operator new(size, alignment), resp...
This inconsistent behavior is an issue, see LWG3789. EDIT: However, the status of the issue has been set to Tentatively NAD: "No reason to carve out an exception covering a case on something which can’t be observed by the program (whether the allocation operators are replaced). This just makes things more complicated ...
73,434,558
73,438,801
Legality of using delete-expression on a pointer to an object of class type with a trivial destructor/scalar type whose lifetime has ended
Is the following code legal? struct S {}; int main() { S* p = new S; p->~S(); delete p; } The standard rules at [basic.life#6]: Before the lifetime of an object has started but after the storage which the object will occupy has been allocated24 or, after the lifetime of an object has ended and before the ...
It seems that there is a wording defect. Either your code is intended to be legal, or it's not. If it is intended to be legal, then [basic.life]/6.2 should have an exception for a trivial destructor. If it's not intended to be legal, then the words "with a non-trivial destructor" should be struck from [basic.life]/6.1 ...
73,434,740
73,435,408
Create std::variant from another with a sub set of the types
Seen some other questions about this but they so not seem to be answered correctly or there is no answer at all. I have a instance of a std::variant and I want to create another instance with a sub set of the types in the first one as I know the original is not that type. For exmaple... std::varaint<int, const char*, b...
@appleapple already provided an answer. However, if constexpr(requires {std::variant<Ts...>{v};}) This can easily triggers implicit conversion, so the below code will work without throwing any exceptions: std::varaint<int, const char*, bool> var1 = false; auto var2 = cast_variant<int>(var1); // convert `false` to int ...
73,435,368
73,443,097
C++ syntactic sugar for two phase look-up
I am trying to provide an API where an user can statically inherit from a base class and use its methods. The issue is that the class is templated with typename T and the methods are templated with typename U, such that the use of the methods is really cumbersome (I think, for an API). As far as I understood this is in...
The problem is indeed caused by the compiler's need to resolve foo before deciding that foo< isn't calling operator< on the expression foo. Adding template means that the compiler knows foo< is the start of a template argument list. As the author of base, there's nothing you can do about that. That's the whole point o...
73,435,592
73,435,842
Finding all Strings in an array
I tried solving this all day but I cannot find an adequate solution. I want to print all words of an input char array, but if I type in an empty space at the start or at the end of the array my result is wrong. Does somebody know how to fix this or does somebody have an understandable solution for me? Thank you! Using ...
You're looking for word by checking if there's space followed by any other character. Try checking for letters if(inputnames[z] >= 'a' && inputnames[z] <= 'z') || (inputnames[z] >= 'A' && inputnames[z] <= 'Z') and if the following character is not a letter.
73,436,481
73,436,578
Troubles with std::set.insert c++
I have a set of a custom class and when I'm trying to insert an object of that class, the terminal gives me an error: #ifndef EMPLOYEE_HH #define EMPLOYEE_HH #include <string> #include <iostream> #include <set> #include <iterator> using namespace std ; class Employee { public: // Constructor Employee(const char*...
Your set accepts a pointer to an Employee, but you are trying to insert the object itself. What you can do is void addSubordinate(Employee& empl){ _subs.insert(&empl); // This will store the address to the object } or accept a pointer itself void addSubordinate(Employee* empl){ _subs.insert(empl); }
73,436,932
73,438,827
Does IFNDR take precedence over diagnosable rule violations?
[intro.compliance.general]/2 specifies how a compiler should handle a program given to it. In particular it has two points dealing with ill-formed programs. (2.2) requires the compiler to issue at least one diagnostic for a violation of a diagnosable rule. (2.3) states that there are no requirements imposed on the comp...
Section 2.3 is clear – "this document places no requirement on implementations". Not "this document except for 2.2", but "this document". If an IFNDR situation exists, then the implementation is free to do anything. Necessary Overriding 2.2 is necessary. Hypothetically, an IFNDR situation could throw compilation off-tr...
73,437,029
73,437,125
How to get first element of typelist in C++-11
I am following C++ templates the complete guide and trying to get the first element from a typelist. The following compiles: #include <bits/stdc++.h> using namespace std; template <typename... Elements> class Typelist; using SignedIntegralTypes = Typelist<signed char, short, int, long, long long>; template ...
Let's deconstruct all the templates, one step at a time. Head<SignedIntegralTypes> Ok, now let's take the definition of what Head is: template <typename List> using Head = typename HeadT<Typelist<List>>::Type; Since SignedIntegralTypes is the template parameter, that's what List becomes here. So this becomes: typenam...
73,437,193
73,441,479
How to fix memcpy.asm error when assigning a value to an std::string through a pointer?
I made this code for a Stack struct: #include<iostream> #include<Windows.h> template<uint32_t S> struct Stack { size_t size; byte base[S]; byte* top; // Stack() { top = (byte*)base; size = 0; } ~Stack(){} // template<class T> void alloc(T*& rt) { i...
As the comments note: you need to create a string in order to assign a value to it. C++ has construction and assignment, and the two are fundamentally different. Construction is done via the constructor, and creates an object out of raw memory. Assignment is done via the operator= member function, and like all operator...
73,437,346
73,438,245
Visual Studio comment multiple variables at once?
variables comment method in which a group of variables receive the same comment if the variables declared in a class is for the same task, I don't want to write the same comment for each variable , it make the code dirty. Comment Hover Pop Up declare 5 variables of int type in a row, give a comment description to the f...
What you are asking, is the IntelliSense's task QuickInfo. It shows tooltips, and comments there that are followed by declarations, if the mouse pointer is above their usages. It's not well documented, I could not find more useful info. But I found an reported issue, that complains about not shown comment in a tooltip,...
73,437,450
73,438,901
WinRT DLL in UWP app crashes when using dependencies from VCPKG
I created an SDK using WINRT because it's the most flexible and I can use it outside UWP apps without having to maintain another SDK for native platforms at the same time. I am using VCPKG as my package manager because it's very easy to maintain. The issue is that if I include a dependency like cpr in the SDK and then ...
Apparently this isn't mentioned anywhere in Microsoft documentation but you should copy your dependencies to bin\x64\Debug\AppX or bin\x86\Debug\AppX If you're running 32 bit. You can do this as part of the build process by going to properties > Build Events > Post-Build Event and adding copy commands to the above buil...
73,437,909
73,438,122
extern "C" variables affected by compiler optimization level
Consider this link with the snippet #include <cstdio> namespace X { extern "C" int z; } namespace Y { extern "C" int z; } int X::z = 1; int main() { std::printf("%d -- %d\n", X::z, Y::z); X::z = 2; Y::z = 4; std::printf("%d -- %d\n", X::z, Y::z); X::z = 0; std::printf("%d -- %d\n", X:...
This is a GCC bug. A similar test case has already been reported here. (Although that one could be a bit more subtle than your test case because it also depends on how exactly using namespace lookup works). As you are expecting the standard says that variable declarations with C linkage and the same name declared in di...
73,438,747
73,438,788
C++ const class member function abs()
Intro I'm currently working on a implementation of a 'mathematical' vector, like in MATLAB, since I'd like to learn more about C++. The Vector class has some constructors (including a copy constructor that is shown below), some operators (including a copy operator, shown below) and some methods (only relevant method sh...
This is because your copy constructor cannot accept const reference. In this line Vector<T> result = *this; Copy constructor of Vector<T> is called. But when you mark your member function as const, this is also considered to be pointer to const. And when dereferencing you get const reference to *this, which you try to...
73,438,758
73,438,789
C++ How would I make something like this? For every x numbers above 50, increase y value
double mWeight; double mHeight; double mAge; int mExercise; bool mCorrectExercise = true; cout << "Please type in your age: "; cin >> mAge; cout << "Please type in your weight: "; cin >> mWeight; cout << "Please type in your height: "; cin >> mHeight; cout << "Finally, please select an exercise program that most c...
If you break it down into pieces, it becomes easier to see the solution: float overAge = (mAge > 50) ? (mAge - 50) : 0; float ageMultiplier = 8.5 + 0.2 * overAge; int metricResult = (mWeight * 9) + (mHeight * 9) - (mAge * ageMultiplier); In case you are fairly new to programming in C++, the '?' is called a 'ternary op...
73,438,870
73,438,909
Accessing templatized static constexpr member of templatized class with template parameter
So I've got a templatized class which has a templatized static constexpr bool. The setup boils down to this: #include <type_traits> template <typename T> class A { public: template <typename U> static constexpr bool same = std::is_same_v<T, U>; }; template <typename T> bool test() { return A<T>::same<int>; // e...
The template code is not equivalent to A<int>::same<int>. This will also compile: template <typename T> bool test() { return A<int>::same<int>; } Returning to the erroneous code. The latest GCC 12.1 would produce the hint in the warning: constexpr_value.cpp: In function 'bool test()': constexpr_value.cpp:12:16: warn...
73,439,773
73,440,758
How to determine current build type of visual studio in CMakeList.txt
This is my build command in CMD: cmake --build . --config Debug This Debug can sometimes be Release, or sometimes it is the default. And I have a code in my CMakeList.txt: if(CMAKE_BUILD_TYPE STREQUAL "Debug") target_link_libraries(${PROJECT_NAME} PRIVATE LLUd wstp64i4) else() target_link_libraries(${PROJECT_N...
This is all you should need: find_package(LLU REQUIRED PATH_SUFFIXES LLU) target_link_libraries(MyTarget PRIVATE LLU::LLU) If the above isn't working, you should ask about that error, not your attempted workaround. The code you show is broken on several levels. First, the value of CMAKE_BUILD_TYPE should never be us...
73,439,801
73,439,816
How does the execution occurs in c++?
if(condition1 and condition2){ //body } If condition1 turns out to be false, will c++ compiler check for condition2 or will it directly return false?
What you described is called short-circuit evaluation and C++ does use it: if condition1 is false, condition2 will not be checked.
73,439,922
73,439,981
C++ : Is class type const always a top-level const?
Here are the following code: #include <iostream> using namespace std; class A { public: int *x; }; int main() { int b=100; A a; a.x = &b; const A &m = a; // clause 1 - Is this top-level const? int *r = m.x; // *r has no const yet allowed. Is it due to reference m being top level const? } Any help ...
int const ca = 24; int a = ca; You would expect this to compile right? And indeed it does. Here I initialized a integer with the value 24. You code is the same situation, except that instead of integer you have pointer to integer: m is const so m.x is const. The x is const, i.e. x cannot be modified (via m). In strict...
73,440,392
73,440,488
Initializing a vector with a vector of vector causes segmentation fault in C++
I was revisiting and old project of backtracking that aimed to solve a problem similar to Rat in the Maze and found this chunk of code that for some reason causes a segmentation fault. The isolated line in particular is the one causing the problem. int makeDecision(vector<int> currPos, vector<vector<int> > board, vecto...
If the problem is in this section, it is likely that one of the assumptions about sizes of inputs is not correct. You can put assert calls to check them before doing anything. int makeDecision(vector<int> currPos, vector<vector<int> > board, vector<vector<int> > &visited){ assert(board.size()>0); assert(currPos...
73,440,465
73,440,548
Send IV with cipher text and use it to decrypt cipher text in another function
I have two functions, one for encrypting and another for decrypting. I do not want use static IV, not safe, so I would like to prefix the cipher text with the 16-byte IV so then in the decrypt function I can get the first 16 of the cipher text (the IV used for encrypting originally) and use it to decrypt the text. Ho...
Your concern is correct, it is a must to use different IV's for each encryption. You can first copy IV to cyphertext and put the output after the IV like this: int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) { EVP_CIPHER_CTX *ctx...
73,440,925
73,441,417
How much memory allocated with vector initialized with initializer lists and push_back
If I have these 2 lines of code in C++ vector<int> vec = {3,4,5}; vec.push_back(6); How much memory is allocated in total for the 2 lines and what assumption we need to make? I tried to look these up but can't find the definition for these anywhere.
Looking at llvm's libcxx library as an example, we could speculate that the capacity would be 6 ints in size. vector<int> vec = {3,4,5}; allocates 3 ints on initialization __vallocate(3); template <class _Tp, class _Allocator> inline _LIBCPP_INLINE_VISIBILITY vector<_Tp, _Allocator>::vector(initializer_list<value_type>...
73,443,214
73,447,984
Determining the type of the template parameter method argument
There are many IEnumXXXX type COM interfaces that have a pure virtual method Next, like this: IEnumString : IUnknown { ... virtual HRESULT Next(ULONG, LPOLESTR*, ULONG*) = 0; ... }; IEnumGUID : IUnknown { ... virtual HRESULT Next(ULONG, GUID*, ULONG*) = 0; ... }; Need a template, like this: enum_value_type<IEnumStrin...
Something along these lines: template <typename T> struct ExtractArgType; template <typename C, typename T> struct ExtractArgType<HRESULT (C::*)(ULONG, T*, ULONG*)>{ using type = T; }; template <typename IEnum> struct enum_value_type { using type = typename ExtractArgType<decltype(&IEnum::Next)>::type; }; De...
73,443,378
73,453,797
array transfer constructor function c++
I am trying to learn constructors in c++. I am working on a list that I defined. I managed to get the copy constructor working, but I have problems with the array transfer constructor. Any help will be appreciated. Thanks! The array transfer constructor supposedly should take in an array and a size(int) and output a li...
Main Question With regards to your 'from_array' constructor, you have a temporary List variable that you are not using and is also unnecessary. Second you are assigning the head pointer each time meaning that by the end of the constructor call, head now points to the last element you constructed. Third your list_elemen...
73,443,940
73,444,170
Is it bad to leave events unprotected?
I'm writing some code that includes events which are custom-implemented and class that uses these events and invokes them when something happens(ex. window closes). It looks something like this: // phony.h class Phony { public: Phony(); ~Phony(); // some stuff void i_invoke_click(); ...
What I could suggest coming from a C# background is to use a base class like IObservable for the Events which implements some subscribe method or your approach with operator overloading. Then make the IObservables public by returning a reference that refers to the events themselves: #include <functional> #include <list...
73,443,971
73,444,142
C++ Move constructor for object with std::vector and std::array members
I'm currently implementing a Vector class that is supposed to handle the math. This class has two members std::vector<double> vector_ and std::array<std::size_t, 2> size_. Now I want to write a move constructor Vector(Vector&& other);. I've tried multiple ways, including Vector(Vector&& other) = default;, but none seem...
[...] and set the other's content to their default values? No. When not stated otherwise a moved from object is in a valid, but unspecified state. Setting all elements to some default would be rather wasteful. Further, a std::array does contain the elements. Its not just a pointer to some dynamically allocated elemen...
73,444,061
73,444,148
Passing std::ranges::views as parameters in C++20
I have a method that prints a list of integers (my actual method is a bit more complicated but it is also read-only): void printElements(const std::vector<int> &integersList) { std::for_each(integersList.begin(), integersList.end(), [](const auto& e){ std::cout << e << "\n"; }); } Now suppose I have th...
You can make printElements take any object by making it a function template. This will instantiate it for views as well as vectors. #include <algorithm> #include <iostream> #include <ranges> void printElements(std::ranges::input_range auto&& range) { std::ranges::for_each(range, [](const auto& e) { std::cout << e ...
73,444,110
73,444,204
comparing std::vector to a raw value of the same type give error
I was doing an exercise while I noticed this this code work okay: std::vector<std::string> x = { "st1", "st1" }; std::vector<std::string> y = { "st1", "st1" }; assert(x == y); while this give me error when trying to compile it std::vector<std::string> x = { "st1", "st1" }; assert(x == { "st1", "st1" }); I have no i...
The error should have told you something along the line of "{ "st1", "st1" } has no type". If you want to construct a second vector you need to call the constructor: assert(x == std::vector<std::string>{ "st1", "st1" });
73,444,207
73,444,790
C++: freopen (and I/O) just refuses to work
Today I'm having issues with my code. It appears that I can not get anything from input (whether file or stdin) as well as unable to print (whether from file or stdout). My code can have a lot of issues (well, this is code for a competitive programming problem, don't expect it to be good. It will be straight up horrend...
This isn't an issue with freopen or I/O. Here a = min(a, demsm(n, i.first) / i.second); You are dividing by zero and this results a segmentation error. The reason why the program isn't printing anything is because of the way how these lines work. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); You can read abou...
73,444,527
73,444,820
Get process's thread information in windows OS
I'm new in c++ programming and I'm coding a tool to enumerate information of all process running on windows OS. After researching, googling, I have found a useful library Ntdll.lib and header winternl.h that helping me gathering information about process by using NtQuerySystemInformation() function. Everything work fin...
Starting from your PSYSTEM_PROCESS_INFORMATION p: while (p) { PSYSTEM_THREAD_INFORMATION pt = (PSYSTEM_THREAD_INFORMATION)(p + 1); for (int t = 0; t < p->NumberOfThreads; t++) { std::cout << "Start address of thread " << t << " is " << std::hex << pt->StartAddress << std::dec << std::endl; pt++; // Adds siz...
73,446,020
73,446,182
Equation with abs() gives wrong answer (gcc/g++)
Somehow I get wrong result from equation which involves library function abs(). Here's my code where the issue is present: main.cpp ------------------------------------- #include <iostream> #include <cmath> #include "test999.h" using namespace std; int main() { float n = 11; ak r; r = test(n); prin...
There is std::abs(int) and there is std::abs(float). The former is inherited from C abs(int). In C there is no overload for floating points, it is called fabs (also available as std::fabs). You tripped over using namespace std; obfuscating what function is actually called. Note that you have it in main, but not in the ...
73,446,148
73,446,228
Partial emplate Argument Deducion C++
I have the following code: template <class B, class A> class C { A m_a; public: explicit C(A a) : m_a(a) {} }; int main() { C<int>(16); return 0; } that can not be compiled. My purpose is to automatically deduce class A using the constructor parameter but use manually mentioned class B. Is it poss...
Sure, but only with a helper function. As currently written, C<int> has to be the complete name of a type, which it obviously isn't. The constructor argument isn't considered until after the type of the object is determined. So write template <class B, class A> C<B,A> make_c(A a) { return C<B,A>{a}; } int main() { ...
73,446,842
73,446,927
What does a semicolon after function inside function mean?
I saw an answer for a c++ challenge that had you copy a certain part of a string x times. std::string repeatString(int xTimes) { repeatString;(3); //What's happening here? } He seemed to have solved the challenge with this code and I'm guessing he solved it the wrong way but I'm still unsure what's happening. origi...
repeatString; is an expression that does nothing useful. Same for (3);. Its the same as 3; and does literally nothing. After removing that unnecessary fluff, the function is std::string repeatString(int) { //What's happening here? // - nothing at all } And this, not only does it not repeat a string, but it in...
73,447,085
73,474,435
Qt: Cannot read device, no error provided
I have some code for Qt below that connects two devices via UART if possible. If not possible, it will display an error string. void Hardware::initialisePort(QString portName) //Initialized at balance and controlboard { /*! \brief Method to initialise the com port * */ // setup the port in the ap...
There was a typo. The port was written as "tty01", when it should have been "ttyO1", O for Orange instead of a zero. Thanks to chehrlic for catching it, 0s and Os are a bit too similar in Linux.
73,447,272
73,447,857
Visual C++: cast to function type is illegal, g++ also yields an error
My generated code always used unnecessary many parenthesis simply to make certain, that the C++ code was actually doing what the AST expressed. This is first time I'm getting this compiler error, which I cannot explain -- also before I've used custom types. (define G_ERROR to get an error...) Visual C++ 2019 yields the...
abstractValue<>(undetermined()) Because both abstractValue<> and undetermined are types, there are two interpretations of this without further context: It is a functional-style explicit cast expression creating a prvalue of type abstractValue<> with (undetermined()) its initializer. It is a type-id, namely the type ...
73,447,278
73,447,407
C++ reference calls 'wrong' destructor
Why does below snippet print: Constructing Working on this Constructing working on that Destructing working on that Destructing working on that I would expect "constructing this + that" and "destructing this that". So the idea here is to have to have a reference to a workingItem and then do something in the destructor...
Implement a operator= to get the full picture: #include <iostream> class A { private: std::string str; public: A(const std::string& s) : str(s) { std::cout << "Constructing "<<s<<std::endl; }; ~A() { std::cout << "Destructing "<<str<<std::endl; }; A& operator=(const A& other){ std::cout << "assign...
73,447,342
73,447,737
CMake and GoogleTest weird behaviour with comparison when changing build type from Debug to Release
Context I am writing a function which calculates some exponential value for a timer application. It simply takes 2^x until some threshold maxVal, in which case the threshold should be returned. Also, in all cases, edge cases should be accepted. util.cpp: #include "util.h" #include <iostream> int calculateExponentialBa...
Floating-integral conversions A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value cannot fit into the destination type, the behavior is undefined. - This is it. The behavior is undefined. Any expe...
73,447,593
73,452,569
How to cut a part of a shape with the help of another painted shape above?
On the screen below I have the image with the painted translucent rectangle and with the painted opaque rectangle. My purpose is to cut the area of the opaque rectangle - delete pixels in the translucent rectangle in order to see the initial image. cairo_surface_t *surface = cairo_xlib_surface_create(xdisplay, xroot, ...
Maybe, since cairo's drawings change pixels directly (=not buffered), once you draw something, there remain no underlying original pixels that can be recovered afterwards. If you'd like to hole the rectangle, try the fill rule: CAIRO_FILL_RULE_EVEN_ODD. cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD); // The default...
73,449,114
73,449,198
How to declare and initialize a vector of semaphores in c++?
Say I have n different resources. Let's say n = 5 as an example, but n can be large and optionally an input value. I want to initialize a vector of n binary semaphores. How do I do that? I believe the problem is because the constructor for binary_semaphore or counting_semaphore has been marked explicit. I've tried the ...
Semaphores (along with many other mutex-like types... including mutex) are non-moveable. You cannot put such a type in a vector. This is not about explicit constructors; it's about the lack of a copy or move constructor. Allocating an array of these is made difficult by the lack of a default constructor. You can try to...
73,449,347
73,449,458
Getting the implicitly deleted error when using a struct
I'm getting this error: <source>:48:32: error: use of deleted function 'FPTask_sim::Data_T::Data_T()' 48 | FPTask_sim::Data_T FPTask_sim::_data; | ^~~~~ <source>:40:9: note: 'FPTask_sim::Data_T::Data_T()' is implicitly deleted because the default definition would be ill-formed: ...
If you declare any constructor for a class, then the default constructor (constructor not requiring any argument) will not be declared implicitly. So then there is no constructor to construct e.g. FPTask_sim::_data.ARG_react_02_unused_arg01 when you are trying to initialize it without constructor argument in FPTask_sim...
73,449,896
73,496,990
How to improve performance of writing files in UWP
In the following part of my UWP application, I have a performance bottle-neck of creating a lot of large TIFF files. Is there any way to make it run faster without too many conversions and data copies? Due to platform restrictions, I am not allowed to use fopen (access denied). std::ostringstream output_TIFF_stream; TI...
I haven't found any way to speed up I/O operations in UWP. If you are writing an I/O speed critical application. I recommend using WPF or if you friendly with WRL, then the new Windows APP SDK.
73,450,877
73,450,928
Getting error when overloading << operator
I have a Class called "Vector". It consists of two private fields: std::vector<double> coordinates and int len. Methoddim() returns len. I am overloading operator << like that: friend std::ostream& operator<<(std::ostream& os, Vector& vec ) { std:: cout << "("; for ( int i = 0; i < vec.dim(); i++ ) { ...
A temporary cannot bind to a non-const reference argument. You are missing const in at least two places. Most importantly here: friend std::ostream& operator<<(std::ostream& os, const Vector& vec ) // ^^ And there should a const overload of operator[]
73,451,202
73,452,198
Not able to send a JSON request using libcurl in C++
I am trying to access a GraphQL server with C++ and I am using the libcurl library to make the HTTP Post request. I got started with libcurl after reading the docs and I was testing the requests that were created using a test endpoint at hookbin.com Here is the sample code: int main(int argc, char* argv[]) { CURL* ...
curl_easy_setopt is a C function and can't deal with std::string data and CURLOPT_POSTFIELDS expects char* postdata. Call std::string::c_str() for getting char*. curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());
73,452,194
73,701,494
VCPKG + CMAKE not finding compatible version with requested version ""
I am trying to use VCPKG and CMAKE on a cpp project and am using the CPR library. I have been struggling to figure out what could be the cause of this error, re ran the get-started guide and other tutorials / blogs that are using cpr with vcpkg and is running fine with almost the exact same cmake config. What am I doin...
-DVCPKG_TARGET_TRIPLET:STRING=x64-windows means x64-windows triplet/libraries will be used (->vcvars64) -G "Visual Studio 17 2022" means VS 2022 will be used (defaults to x64) -T host=x86 means VS2022 x86 host tools will be used -> vcvars(32|x86_<?>)? -A win32 means VS2022 will try to build for x86/win32 (overr...
73,452,904
73,453,018
how to convert values of type float and double into binary format and push into vector of type uint8_t?
I want to know how to convert values of float and double into binary format and push into vector of type uint8_t Eg : float x = 23.22; double z = 2.32232; and store them into vector while serializing vector<uint8_t> data. and also convert back into original value while deserializing. Is there any way to do t...
If you just need to push them into vector and pop them (like a stack) you can do this: void push( std::vector<uint8_t> &v, float f ) { auto offs = v.size(); v.resize( offs + sizeof( f ) ); std::memcpy( v.data() + offs, &f, sizeof( f ) ); } float popFloat( std::vector<uint8_t> &v ) { float f = 0; if( v...
73,452,921
73,453,035
I can´t delete a certain node in my linked list
I have the next linked list: #include <iostream> #include <string> #include <cstddef> using namespace std; //Node class class Node { public: string name; string age; Node *next; Node *prev; Node(string name, string age) { this->name = name; this->age = age; this->next =...
Fors starters, free is the wrong way to free a pointer allocated with new. Use delete instead. Also, it's generally best to pass strings as const references. Your deleteNode function looks really complicated. Let me simplify it for you. Tell me what you think of this: void deleteNode(const string& name) { ...
73,453,064
73,453,219
C++ Typecast int pointer to void pointer to char pointer?
Hello im confused by typecasting pointers. I understand that void can hold any type. So if i have an int * with a value inside of it then i make a void * to the int * can i then typecast it to a char? It's quite hard to explain what i mean and the title might be wrong but will this work? And is it safe to do this. I've...
I understand that void can hold any type. You understand it wrong. Pointer does not hold data, it points to it. So integer pointer points to memory with holds integer, float pointer points where float is etc. Void pointer just points to some memory, but it says - I do not know what kind of data is there. Now conversi...
73,453,098
73,453,125
How to convert a raw pointer to unique_ptr?
I have this sample code: std::unique_ptr<Base> some_function() { //I cannot use unique ptr here becuase it will get freed when the function return i guess Derived* derived = new Derived; return static_cast<std::unique_ptr<Base>>(derived); } Is using static_cast here is a good solution? Are there other alte...
I cannot use unique ptr here becuase it will get freed when the function return i guess You can simply return it and the ownership of the raw pointer stored in the smart pointer will be transferred from your local variable to the std::unique_ptr<Base>. std::unique_ptr<Base> some_function() { auto derived = std::m...
73,453,234
73,453,432
Are function scope static constexpr variable static storage duration
First I'll start by saying the question is maybe wrong, as I am not sure what is the issue with the following code. #include <array> #include <cstdint> #include <iostream> template <typename T> struct PixelRGB { T r {}; T g {}; T b {}; }; using PixelRGBui8 = PixelRGB<uint8_t>; template <typename Pixel_T> class ...
Because 16 is int by default in C++ standard, Width is an int variable; then you pass it as a const uint32_t& parameter, so possibly it causes a copy to make a temporary uint32_t variable, and pass it to this const reference. After the function ends, this temporary variable is destructed, so your reference refers to an...
73,453,375
73,453,431
Why is there a difference between the following lines of code? (Recursion based question)
Here's the first part: bool coinChangeFn(vector<int>& coins, int amount, int level, int& result) { if (amount < 0) { cout << "Amount is less than 0!" << endl; return false; } if (amount == 0) { cout << "Amount is 0. Level is " << level << endl; result = min(result, level); ...
You’re seeing the effect of short-circuit evaluation. In C++, since true || anything is true, if the first operand to || is true, then the second argument isn’t evaluated. Therefore, if you write flag = flag || /* recursive call */; and flag is already true, then no call will be made. On the other hand, the bitwise OR...
73,453,622
73,454,047
Store an lvalue or an rvalue in the same object using variants
I am reading a technique that is used to store an lvalue or an rvalue in the Same Object. Please find the description of this here. The overloaded trick is implemented. However when the overload struct is defined , an addition overload constructor is defined, in which the function pointers that are produced when the ...
You are trying to initialize overload via parenthesized initialization, e.g. here: overload( [](Value<T> const& value) -> T const& { return value.value_; }, [](NonConstReference<T> const& value) -> T const& { return value.value_; }, [](ConstReference<T> const& value) -> T const& { return valu...
73,453,867
73,464,478
Error using large Eigen matrix: " OBJECT_ALLOCATED_ON_STACK_IS_TOO_BIG"
I have been using Eigen matrices to test a new code I wrote, and I just ran into this issue for the first time. I just started reading about "Fixed vs. Dynamic size" in Eigen matrices and I thought I was using "dynamic" matrices for large sizes, but when I try using larger number of grids I get the error: static asser...
As people pointed out in the comments, using the following fixes the issue: Eigen::MatrixXd or Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
73,454,879
73,454,967
Finding a string inside all subdirectories
I try to code a program that behaves like grep -r function. So far I can list all the subdirectories and folders inside of them recursively but what i need to do is to find a string inside all of these files and record them in a .log file. I am building with CMake on Ubuntu. The program compiles fine but probably I hav...
ifstream infile(path); Should be ifstream infile(entry.path());.
73,455,046
73,480,871
How to set _GLIBCXX_USE_CXX11_ABI=0 in Makefile
In CMakelists.txt we can use add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=0), how can I set _GLIBCXX_USE_CXX11_ABI in makefile?
As @Alan Birtles said, I do it like this : g++ $^ -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0 $(INCLUDE) $(LIB) -o $@
73,455,453
73,456,884
how to use decltype(*this) in clang
Here is my code. If i don't comment out the // typedef auto getFoo1() -> decltype(*this);,the program works on gcc,but it compiles failed on clang (https://godbolt.org/z/jzs3f6oM7). class Foo { public: // not work on clang but work on gcc // typedef auto getFoo1() -> decltype(*this); auto getFoo2() -> de...
There are only few places where this is allowed to appear and [expr.prim.this] lists them all, namely it can appear in declarations of member functions, member function templates and default initializers of non-static data members. A typedef declares a type alias, so neither of those above, and therefore this is not al...
73,456,694
73,456,775
How to change wstring value in struct?
I don't know how to change wstring value in struct . I don't know where is my error. do you help me ? I can't understand why string value change success, wstring value change failed . struct TestStruct{ string falg1; wstring falg2; TestStruct setFlag1(string str ) { falg1 = str; return *this; } Test...
I am not sure why are you trying to return a copy of your struct, the code looks really weird. I would use a method returning nothing and then setting the flags works as expected: #include <string> #include <iostream> struct TestStruct{ std::string falg1; std::wstring falg2; void setFlag1(std::string str ) { ...
73,457,393
73,457,591
enum in struct by c++
I have segment of code which from C by compiling in C++. But it fail. Does anyone know to modify? /* types of expressions */ typedef enum { JAM_ILLEGAL_EXPR_TYPE = 0, JAM_INTEGER_EXPR, JAM_BOOLEAN_EXPR, JAM_INT_OR_BOOL_EXPR, JAM_ARRAY_REFERENCE, JAM_EXPR_MAX } JAME_EXPRESSION_TYPE; enum OPERAT...
C++ does not allow implicit conversion from int to enum. You can use static_cast. However, anyhow it would be better to spell it out explicitly, then there is no need for the cast: YYSTYPE jam_null_expression = {ADD ,JAM_ILLEGAL_EXPR_TYPE ,0,0,0}; Note that in C++ there is no need for the typedefs and that there are s...
73,457,572
73,457,629
Why does capturing by value in lambda work although object is deleted?
Why does this code work? // Online C compiler to run C program online #include <cstdio> #include <vector> #include <functional> #include <memory> #include <iostream> using FilterContainer = std::vector<std::function<bool(int)>>; FilterContainer filters; class Widget { public: int divisor = 0; void addFi...
You don't capture the Widget object, you capture the local variable divisorCopy by value. This of course creates a copy of the divisorCopy value, stored internally in the lambda object. This lambda-local copy is separate and distinct from the original divisorCopy variable. When addFilter function returns, the lambda-lo...
73,457,833
73,457,904
Cant put a number into 2d array idk why
ok so im trying to print all characters in a computer. I did a nested loop to put all numbers into the 2d array and print them. int count = 0; char counte[4][5] = {{' ',' ',' ',' ',' '}, {' ',' ',' ',' ',' '}, {' ',' ',' ',' ',' '}, {' ',' ',' ','...
The characters you are trying to print aren't visible characters. You can check what visible ones (starting from 33) at ASCII table
73,457,913
73,457,981
C++ 11 conditional template alias to function
In C++ 11, I want to make a template alias with two specializations that resolve to a different function each. void functionA(); void functionB(); template<typename T = char> using Loc_snprintf = functionA; template<> using Loc_snprintf<wchar_t> = functionB; So I can call e.g. Loc_snprintf<>() and it's resolve to fu...
In C++11 it's not really possible to create aliases of specializations. You must create actual specializations: template<typename T = char> void Loc_snprintf() { functionA(); } template<> void Loc_snprintf<wchar_t>() { functionB(); } With C++14 it would be possible to use variable templates to create a kind o...
73,458,049
73,458,564
How can I pass a function as an optional parameter in C++?
I have two functions that are quite similar, so I'm trying reduce the code duplication. I thought I can create a new function MyFunction() that be called both with or without a func that can be optionally applied to the arguments. So the default for func should be a function that just returns i. I'm not sure if my code...
You can have a default parameter of type std::function<int(int)>, e.g. std::vector<int> MyFunction(const int a, std::vector<int> list, std::function<int(int)> func = [](int i) -> int { return i; }) { std::transform(list.begin(), list.end(), list.begin(), [a,...
73,458,592
73,472,114
C++ ffmpeg encoded audio is distorted
I've made a demuxer/muxer program that takes a video as an input, takes audio and video, then just encodes that red information. So far the video is working fine but the audio is faulty. I can hear the original audio of the input in the background but there is a distorted static sound on the front. I'm setting the AVFr...
You should match input and output sample rates. Your output buffer is allocated regarding your output audio specifications. However, as they are different than your input audio specifications; either it is underflowing and unable to fill your buffer in a input compatible way, or overflowing. The latter one is unlikely,...
73,458,763
73,458,946
type deduction guide on variadic template function
I found some solutions for type deduction guides for variadic classes but not for functions like I intent to use. First, this works as expected: template<typename... T> void print(T&&... args) { ((std::cout << args),...); } int main() { print("Hello ", "World! ", "The answer is ", 42); } gives: Hello Wo...
template<ArgsT... T> is incorrect, ArgsT only applies to a single type, that is, it only checks whether ArgsT<T> is satisfied, so it will never be satisfied. You should use requires-clause for this template<class... T> requires (sizeof...(T) % 2 == 0) && ((sizeof...(T)) / (2*MAX_ARGS+1) == 0) void print(T...
73,458,805
73,458,876
How can I append int variable to string to print path of my DFS algorithm?
I am trying to print the path through a graph made by my DFS algorithm. I am having errors which I do not understand. void GraphTraversal::printPath(std::vector<const Node *> &path) { string myPath; for(int i = 0; i<path.size(); i++) { string dfspath = to_string(dfspath[i].getNodeID()); ...
You declare a string variable named path, but your parameter is already named path. So path[i] actually refers to the string, not to the vector. Also, path[i] is a const Node*, so you must call it's function with : path[i]->getNodeID().
73,458,871
73,562,028
Division using GMP's low-level API
I'm using GMP's low-level interface (mpn_, see https://gmplib.org/manual/Low_002dlevel-Functions) to do some fixed-size 192 bit (three limb) integer calculations. Currently I am trying to divide one random uint192 by another random uint192 and fail to select the right function. There are multiple candidates: mpn_tdiv_...
Ok, solution is simple: Instead of passing the number of allocated limbs to mpn_tdiv_qr pass the number of limbs minus the number of leading zero limbs of the divisor instead. E.g. when using 3 limbs and a concrete divisor has limb[2] == 0, limb[1] != 0 and limb[0] == 0 a 2 is passed for the divisor length. This way it...
73,458,902
73,459,071
Class member template function call not being deducted
I am having trouble understanding why the following does not compile. I have the following code like so (some code ommited): Header: template <typename KeyType, typename ElementType> class TUnorderedMap { public: ElementType* Find(const KeyType Key); const ElementType* Find(const KeyType Key) const; }; struct ...
What is the issue here? Why is neither of the Find functions accepted? With the given instantiation TUnorderedMap <Foo*, Foo> NodeToWidgetLookup; The function Find expects a const pointer Foo *const: const ElementType* Find(Foo* const Key) const; While you are trying to pass a non-const pointer to const argument co...
73,459,254
73,459,373
Why isn't the original value getting incremented twice even though I have two increments
I'm new at programming and can someone explain to me how this code work? #include <iostream> using namespace std; int main () { int a = 3, b = 4; decltype(a) c = a; decltype((b)) d = a; ++c; ++d; cout << c << " " << d << endl; } I'm quite confused how this code run as they give me a result ...
decltype(a) c = a; becomes int c = a; so c is a copy of a with a value of 3. decltype((b)) d = a; becomes int& d = a; because (expr) in a decltype will deduce a reference to the expression type. So we have c as a stand alone variable with a value of 3 and d which refers to a which also has a value of 3. when you incre...
73,459,948
73,460,785
C++ vector remove by value gives off an error
I've followed another question to create a template function that removes a member from a vector by value, however when I try to compile it I'm getting this error: /usr/include/c++/11/bits/predefined_ops.h: In instantiation of ‘bool __gnu_cxx::__ops::_Iter_equals_val<_Value>::operator()(_Iterator) [with _Iterator = __g...
Here is a toy example that does what you're trying to do. #include <iostream> #include <list> #include <vector> template <typename Container> void remove_all_by_value(Container& c, typename Container::value_type val) { c.erase(std::remove_if(c.begin(), c.end(), [&val](const auto& a) { return...
73,460,136
73,460,468
What STL function can I use to replace "while (var != nullptr)" loop?
In book C++ Core Guidelines Explained: Best Practices for Modern C++ there is a quote: There is a proverb in modern C++: “When you use explicit loops, you don’t know the algorithms of the STL.” I am writing a program at the moment, which uses an explicit for loop, that changes an object pointed to by a variable in ea...
Algorithms are ultimately built on iterators. Your loop is not. Therefore, there is no algorithm to fit it. Now, if you're using this particular get_object/get_object_next interface frequently, it might be worthwhile to develop an iterator/range version of it. Presumably this would be some form of InputIterator/Range. ...
73,461,218
73,461,279
Can you write OpenGL shader in different file and later link it to the program?
Can you write OpenGL shader in a different file and later link it to the program? and if it's possible how? writing OpenGL shader in string makes my code messy. Here is example code for shaders: const char* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location ...
Yes, you can have files like my_shader.vs or my_fragment.fs and link them like in this Shader class Just initialize it like this: shader = Shader("./shaders/my_shader.vs", "./shaders/my_fragment.fs");
73,461,523
73,465,007
For a recursive call without a base condition, why does the compiler not show an error during compilation?
I have been programming using the C++ language for quite some time now. I recently came across a situation for which I need help. For a recursive call without a base condition, why does the compiler not show an error during compilation? I, however, receive an error message during runtime. Take the following for an exam...
Modern compilers, in their quest to help you out and generate near-optimal code, will indeed recognize that this function never terminates. However, nothing in the C or C++ language specifications requires that. In contrast to languages like Prolog or Haskell, C/C++ do not guarantee any semantic analysis of your prog...
73,461,831
73,461,882
std::map::find does not access operator==
I created a class MyString and overloaded operator==. MyString can be used without any problems class MyString { public: bool operator== (const MyString& obj) const; }; I want to use MyString as key in std::map. std::map<MyString, value> m_xxx; I can access the inserted data by iterating. for (auto& it : m_ini) {...
std::map does not use operator==. It is a sorted container and by default operator< is used to compare keys of elements in the map. std::map has 4 template arguments: template< class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T> > > class map The...
73,462,506
73,462,677
How to delete specific line from text file c++
This is my text file content. 1 2 3 I want to delete line of this file. #include <iostream> #include <fstream> #include <string> std::fstream file("havai.txt", ios::app | ios::in | ios::out); int main() { std::string line; int number; std::cout << "Enter the number: "; std::cin >> number; while (f...
Removing data from a file is far more complicated than it appears. It is almost always orders of magnitude easier to create a new file and write the information to be kept into it. Open File A for reading. Open File B for writing. For each line in File A: If it's not a line to be discarded, write it to File B. Close F...
73,462,947
73,463,034
Question about overloaded operator T() in C++ template class
I have this little piece of code: template<typename T> class Test { public: //operator T() const { return toto; } T toto{ nullptr }; }; void function(int* a) {} int main(int argc, char** argv) { Test<int*> a; function(a); return 0; } It doesn't compile unless the line operator T() const { return...
operator T() const { return toto; } is a user defined conversion operator, it is not operator(). It's used to define that your class is convertible to a different type. operator() would look like this instead: void operator()() const { ... } In your case, you are using int* as T. If you substitute it yourself in the op...
73,462,991
73,463,083
CMake: Cannot link to a static library in a subdirectory
I have the following folder structure in my c++ project *--build |---(building cmake here) | *--main.cpp | *--CMakeLists.txt (root) | *--modules |---application |------app.h |------app.cpp |------CMakeLists.txt And the code below for both CMakeLists.txt files: CMakeLists.txt (module) cmake_minimum_required(VERSION 3.1...
You don't need to use find_* to locate the library. In fact you cannot locate the library this way, since find_library searches the file system for the library during configuration, i.e. before anything gets compiled. There's good news though: If the targets are created in the same cmake project, you can simply use the...
73,463,183
73,463,564
Address Sanitizer Heap buffer Overflow
I was trying to solve this problem on leet code it works fine on my vs code and gcc compiler but i'm getting this Runtime error: Address sanitizer Heap buffer Overflow error message with a long list of address or something on the website. Help me fix it. Here's the code class Solution { public: char nextGreatestLet...
This code snippet has a lot of problems: The while loop isn't guaranteed to terminate. If the last character of v is == a, then the first v[l] < a test will be false, but v[i] <= a might be true all the way through the array (it looks like v is meant to be pre-sorted into ascending order), which will have you eventual...
73,463,466
73,465,244
How can I force the user of a library template to explicitly tag particular template parameters as acceptable (but only sometimes)?
I have a family of classes in a library that can be "installed" in another class, either as a single member or as an array, dependent on the application. The arrays are indexed with an integer or enum type, dependent on the application (void is used when an array is not meaningful). The installable class itself has n...
This case seems like a good place for template variables. One of their use is to make them a kind of a map - which in this case would greatly increase readability of the client code and move everything to compile-time. If you just want to break compilation the following should be fine: #include <iostream> #include <typ...
73,463,592
73,463,643
what type of data does string.length() return in c++?
I am a beginner in C++. Today, I was trying to solve problem 139 on Leetcode, here is the pseudo-code: for (string& word: wordDict) { int i=0; int word_len = word.length(); cout << i - word.length() << endl; cout << i - word_len << endl; } And here is the result: 18446744073709551611 -5 184467440737095...
The type of the member function length is an unsigned integer type named like size_type. As the type is unsigned then the expression i - word.length() also has an unsigned value because the rank of the type size_type (that usually corresponds to the type size_t) is not less than the rank of the type int. You could wri...
73,463,784
73,463,888
Remove All Adjacent Duplicates In String in C++: Why is my iterator not entering into the for loop again
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ In this Leetcode question, I tried to do it without using the concept of a stack. But according to the answer, I get the loop is not getting completed, why is that the case here? class Solution { public: string removeDuplicates(string s) { ...
Your loop boundary, i < s.length(), is wrong since it'll let s[i + 1] access the string out of bounds*. You need to reset i when a match is found, which you do, but it's followed by i++ directly, so it will never find a match at s[0] == s[1] again. Fixed: string removeDuplicates(string s) { for (unsigned i = 0; i...
73,463,785
73,464,253
How to include libs into Qt project?
I'm trying to figure out how to use the winapi SetWindowSubclass On a non-Qt project under MSVC I can use the API by including: #include <commctrl.h> #pragma comment(lib, "Comctl32.lib") I have been trying for hours unsuccessfully to link this lib on my project. I have found these comctl32.lib on my machine: https://i...
It should be LIBS += -lcomctl32 for your compiler instead of the several other options you tried. This related question has additional detail: Adding external library into Qt Creator project
73,464,159
73,464,285
VS debugger - Identify DLL function names from DLL exports (no PDB available)
I have a segfault in a mess of DLLs that I unfortunately cannot acquire .pdb files for. While I have a stack trace, this is unhelpful as I can't pin down exactly where things are going wrong. I am wondering if there's any way to use the DLL to associate sections of the code with specific exported functions, preferably ...
You can have VS resolve the exports, go into Tools -> Options, then Debugging -> General. Make sure the "Load dll exports (Native only)" item is checked. Note that this will only resolve functions that are actually exported. If the exported function calls some non-exported function in the DLL you won't be getting a nam...
73,464,269
73,464,387
How can I include a header file in, but the header file I include includes the file I want to include
I can't really describe my problem, so I'll show you here with code what I mean: boxcollider.h #include "sprite.h" class BoxCollider { public: BoxCollider(Sprite sprite); }; sprite.h #include "boxcollider.h" class Sprite { public: BoxCollider coll; }; INCLUDE issue. How can I solve this problem?
You have two issues. One is the circular references between the two classes. The other is just the circular includes. That one is easy. All your includes -- ALL of them -- should guard against multiple includes. You can do this two ways. #ifndef BOXCOLLIDER_H #define BOXCOLLIDER_H // All your stuff #endif // BOXCOLLI...
73,465,091
73,471,084
Boost process child with custom environment causes deprecation warning/error
I would like to use Boost::Process::Child to create a process while also supplying an environment variable to that process. While it seems straightforward, I've also got the requirement of compiling with -Wall -Wextra -pedantic -Werror -Wl,--fatal-warnings (Basically, the slightest issue is treated as an error). I'm fo...
Like the commenter, I'm unable to reproduce this on my system. So we really need to know more about what tools you use to compile, and what you're compiling (versions). That said, I think the issue can be skirted by making the Boost include a system include, e.g. with -isystem /path/to/boost or add_includes(SYSTEM /pat...
73,465,491
73,465,921
How to pack all arrays of bytes of data members everything in a single vector?
I have a created a function serialize which takes the Data { a class containing 4 members int32,int64,float,double) as input and returns a encoded vector of bytes of all elements which I will further pass to deserialize function to get the original data back. std::vector<uint8_t> serialize(Data &D) { std::vector<u...
If I bind everything in a single vector, how would I dissect them while deserializing. there should be some kind of delimiter? In a stream, you either know what type that comes next - or you'll have to have some sort of type indicator in the stream. "Here comes a vector of int with size ..." etc: vector int size elem...
73,465,892
73,477,095
How to execute a function with parameters just before exiting a code in C++?
I want to trigger a function with parameters just before exiting the program (exit by "return" in the main or by closing the console). My function will print the values of certain variables in a file. Using the function "atexit" not help me because the pointer to the function is without parameters. Thanks P.S. My major...
Thanks to all of you, the answer proposed by @JeremyFriesner gives me the right thing to do, my code will be like : #include <iosrteam> #include <Windows.h> ... int **S; int n; ofstream out("MyFile.txt"); BOOL WINAPI ConsoleHandler(DWORD CEvent) { switch (CEvent) { case CTRL_C_EVENT: case CTRL_B...
73,466,076
73,466,341
C++ Constrained Variadic Template Parameters
Currently using C++20, GCC 11.1.0. I'm quite new to templates and concepts in general, but I wanted to create a template function with 1 to n number of arguments, constrained by the requirement of being able to be addition assigned += to a std::string. I've been searching for several days now but as you can see I am re...
Attempt2 is pretty close, except that the typename keyword needs to be removed since Stringable is not a type but a concept. The correct syntax would be #include <string> template<typename T> concept Stringable = requires (std::string str, T t) { str += t; }; template<Stringable... Args> void foo(Args&&... args) { ...
73,466,485
73,466,840
Why are loads of symbols missing from OpenSSL libs, such as BIO_ctrl?
I'm mystified by why a large subset of symbols is apparently missing from OpenSSL libs I built on Mac. In a CMake-based project, I'm compiling a lib (Restbed) that links statically with OpenSSL (both libssl and libcrypto). The Restbed lib appears to build fine, but if I try to link an application with it, it fails with...
When you build a static lib, it does not involving linking at all -- you just run a tool (ar or libtool or some such) that collects the compiled object files into a static library and does not link any of them. This means that when you link with a static library, you also need to link with any other libraries (static o...
73,466,665
73,466,839
How do I determine from the documentation what type of exception a function can throw?
I am new to C++ programming but have programmed in higher-level languages to find my way around most documentation. I'm learning about exception handling in C++, specifically with this example: vector<int> myNums; try { myNums.resize(myNums.max_size() + 1); } catch (const bad_alloc& err) { cout << err.what() <...
This is not uncommon. The complexity of the language has increased so much over the years, accumulating multiple revisions to the C++ standard, that even the C++ standard itself can be at odds with itself, sometimes. Let's just see what the C++ standard itself says about two versions of the overloaded resize() vector m...
73,466,716
73,467,143
Heap-buffer overflow when implementing two-pointer approch
I'm solving this brain teaser Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of ...
There are several issues with this code, some simple syntactic mistakes, some algorithmic problems. First, as others have mentioned, i is uninitialized in your outer for loop. Luckily, that never comes into play because you have no braces around the loop body. Your code is equivilent to for (int i; i < numbers.size()...
73,467,607
73,479,402
LLVM: how to assign an array element?
I'm struggling to figure out how to assign an array element using the LLVM c++ API. consider this C code: int main() { int aa[68]; aa[56] = 7; return 0; } using clang -S -emit-llvm main.c I get the following IR (attributes and other things are skipped for simplicity): define dso_local i32 @main() #0 { ...
how can I possibly turn [2 x i32]* into i32* when creating a store? This is exactly what the "get element pointer" instruction does. You have a pointer to an object like a struct or an array, and you want a pointer to one element. %1 = getelementptr [2 x i32], [2 x i32]* %0, i32 1 This isn't quite what you want. P...