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
74,619,458
74,619,683
Can a C++ constructor return a pointer to a cached version of an identical object?
Let's say I have a class Bitmap that has a static cache map textures that holds pointers to all images that have been registered. class Bitmap { public: Bitmap(const std::string &filename); // ... functionality ... private: // ... image data ... std::string filename; static std::map<std::string, std::unique_ptr<Bitmap>> images; } Is it possible for the constructor of Bitmap to search the cache for an existing object with the same filename and then return a reference to that? I've tried something like if (images.find(filename) != images.end()) { *this = images[filename].get(); return; } but that doesn't seem to work. Is there a way at all to achieve this effect using the constructor?
By the time you're actually constructing an object, you're already outside the scope of controlling the object's allocation. The constructor is simply there to initialize the object. One way to achieve this with minimal changes to your code is to make the constructor private and create a static method to perform the create/cache logic. class Bitmap { public: static Bitmap& Get(const std::string &filename); private: Bitmap(const std::string &filename) : filename(filename) { std::cout << "Construct " << filename << "\n"; } std::string filename; static std::map<std::string, std::unique_ptr<Bitmap>> images; }; std::map<std::string, std::unique_ptr<Bitmap>> Bitmap::images; Bitmap& Bitmap::Get(const std::string &filename) { auto it = images.find(filename); if (it == images.end()) { std::unique_ptr<Bitmap> ptr(new Bitmap(filename)); it = images.insert(std::make_pair(filename, std::move(ptr))).first; } return *(it->second); } Driver code: int main() { auto a = Bitmap::Get("foo"); auto b = Bitmap::Get("bar"); auto c = Bitmap::Get("foo"); } Output: Construct foo Construct bar This essentially turns your Bitmap class into a self-managing cache. If you want to allow both cached and uncached bitmap instances, then you would move the caching stuff to a separate factory class such as BitmapManager.
74,619,489
74,620,581
How may I bind a Toast progress bar with my C++ Win32 application?
I'm creating a c++ Win32 application which should show some Toast notifications. One of them contains a progress bar. I need to bind its value with my application in order to update it while the status changes in the currently running operation. The Toast interface containing the progress bar is defined as follow: <toast> <visual> <binding template='ToastGeneric'> <text>Backup in progress</text> <progress title='Working folder' value='0' status='Starting backup...' valueStringOverride='0/1 files' /> </binding> </visual> </toast> To show the Toast notification I call the following function, by passing the above interface in the toastContent string: bool ShowToastNotification(const std::wstring toastContent) { if (!toastContent.length()) return false; // build XML ::CComPtr<ABI::Windows::Data::Xml::Dom::IXmlDocument> pDoc; HRESULT hr = DesktopNotificationManagerCompat::CreateXmlDocumentFromString(toastContent.c_str(), &pDoc); if (FAILED(hr)) return false; // create the notifier. Classic Win32 apps MUST use the Compat method to create the notifier ::CComPtr<ABI::Windows::UI::Notifications::IToastNotifier> pNotifier; hr = DesktopNotificationManagerCompat::CreateToastNotifier(&pNotifier); if (FAILED(hr)) return false; // create the Toast notification (using helper method from Compat library) ::CComPtr<ABI::Windows::UI::Notifications::IToastNotification> pToast; hr = DesktopNotificationManagerCompat::CreateToastNotification(pDoc, &pToast); if (FAILED(hr)) return false; // get access to IToastNotification4, which should contain the binding methods ::CComPtr<ABI::Windows::UI::Notifications::IToastNotification4> pToastData; pToast->QueryInterface(ABI::Windows::UI::Notifications::IID_IToastNotification4, (void**)&pToastData); ABI::Windows::UI::Notifications::INotificationData* pData = nullptr; // FIXME how may I create a valid INotificationData here? // bind the data with the interface hr = pToastData->put_Data(pData); if (FAILED(hr)) return false; // show it hr = pNotifier->Show(pToast); if (FAILED(hr)) return false; return true; } As you can see in the FIXME part above, there is a missing part to achieve the binding before showing the Toast notification, and unfortunately there is absolutely NO documentation from Microsoft which explain how to perform that in a simple C++ Win32 application. The below one explain clearly how to perform a such binding, but only in C#: https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/toast-progress-bar?tabs=builder-syntax Even without documentation I could find that the IToastNotification4 seems to be a valid interface to attach a INotificationData container to my Toast, similar to what is done in the above mentioned documentation. However I don't know how to create a valid INotificationData instance. I saw that a CreateNotificationDataWithValuesAndSequenceNumber() function exists in the INotificationDataFactory interface, but same thing, I face a cruel miss of documentation about how to obtain a such interface. Can someone explain me how I may bind my C++ Win32 application with my progress bar on my Toast notification, in order to send it messages to update its interface? Or can someone explain me how to get the above mentioned interfaces, in order to perform something similar to the above mentioned C# documentation? Or at least can someone point me a documentation which may give information about the INotificationData and INotificationDataFactory interfaces, and how to use them to perform the binding with my Toast progress bar?
If a WinRT class can be created from C#, it means it's activatable (or it's associated with another "statics" class which is), which you can check if you go to NotificationData documentation: [Windows.Foundation.Metadata.Activatable(262144, "Windows.Foundation.UniversalApiContract")] [Windows.Foundation.Metadata.Activatable(typeof(Windows.UI.Notifications.INotificationDataFactory), 262144, "Windows.Foundation.UniversalApiContract")] [Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 262144)] [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)] [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)] public sealed class NotificationData {...} If it's activatable, then you just have to find it's activation class id, and call RoActivateInstance . The class id is visible in the corresponding .h file (here windows.ui.notifications.h) and it's usually very straightforward: <namespace> + '.' + <class name>: ... extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_UI_Notifications_NotificationData[] = L"Windows.UI.Notifications.NotificationData"; ... So here is how you can create it: HRESULT CreateNotificationData(INotificationData** data) { if (!data) return E_INVALIDARG; *data = nullptr; IInspectable* instance; auto hr = RoActivateInstance(HStringReference(RuntimeClass_Windows_UI_Notifications_NotificationData).Get(), &instance); if (FAILED(hr)) return hr; hr = instance->QueryInterface(data); instance->Release(); return hr; } PS: using C++/WinRT is usually easier to use than ATL, WRL or WIL for WinRT types.
74,620,490
74,635,520
I encountered the 10^9+7 problem but I can't understand the relation between the distributive properties of mod and my problem
Given 3 numbers a b c get a^b , b^a , c^x where x is abs diff between b and a cout each one but mod 10^9+7 in ascending order. well I searched web for how to use the distributive property but didn't understand it since I am beginner, I use very simple for loops so understanding this problem is a bit hard for me so how can I relate these mod rules with powers too in loops? If anyone can help me I would be so happy. note time limit is 1 second which makes it harder I tried to mod the result every time in the loop then times it by the original number. for example if 2^3 then 1st loop given variables cin>>a,a would be 2, num =a would be like this a = (a % 10^9 + 7) * num this works for very small inputs but large ones it exceed time #include <iostream> #include <cmath> using namespace std; int main () { long long a,b,c,one,two,thr; long long x; long long mod = 1e9+7; cin>>a>>b>>c; one = a; two = b; thr = c; if (a>=b) x = a - b; else x = b - a; for(int i = 0; i < b-1;i++) { a = ((a % mod) * (one%mod))%mod; } for(int j = 0; j < a-1;j++) { b = ((b % mod) * (two%mod))%mod; } for(int k = 0; k < x-1;k++) { c = ((c % mod) * (thr%mod))%mod; } }
I use very simple for loops [...] this works for very small inputs, but large ones it exceeds time. There is an algorithm called "exponentiation by squaring" that has a logarithmic time complexity, rather then a linear one. It works breaking down the power exponent while increasing the base. Consider, e.g. x355. Instead of multiplying x 354 times, we can observe that x355 = x·x354 = x·(x2)177 = x·x2·(x2)176 = x·x2·(x4)88 = x·x2·(x8)44 = x·x2·(x16)22 = x·x2·(x32)11 = x·x2·x32·(x32)10 = x·x2·x32·(x64)5 = x·x2·x32·x64·(x64)4 = x·x2·x32·x64·(x128)2 = x1·x2·x32·x64·x256 That took "only" 12 steps. To implement it, we only need to be able to perform modular multiplications safely, without overflowing. Given the value of the modulus, a type like std::int64_t is wide enough. #include <iostream> #include <cstdint> #include <limits> #include <cassert> namespace modular { auto exponentiation(std::int64_t base, std::int64_t exponent) -> std::int64_t; } int main() { std::int64_t a, b, c; std::cin >> a >> b >> c; auto const x{ b < a ? a - b : b - a }; std::cout << modular::exponentiation(a, b) << '\n' << modular::exponentiation(b, a) << '\n' << modular::exponentiation(c, x) << '\n'; return 0; } namespace modular { constexpr std::int64_t M{ 1'000'000'007 }; // We need the mathematical modulo auto from(std::int64_t x) { static_assert(M > 0); x %= M; return x < 0 ? x + M : x; } // It assumes that both a and b are already mod M auto multiplication_(std::int64_t a, std::int64_t b) { assert( 0 <= a and a < M and 0 <= b and b < M ); assert( b == 0 or a <= std::numeric_limits<int64_t>::max() / b ); return (a * b) % M; } // Implements exponentiation by squaring auto exponentiation(std::int64_t base, std::int64_t exponent) -> std::int64_t { assert( exponent >= 0 ); auto b{ from(base) }; std::int64_t x{ 1 }; while ( exponent > 1 ) { if ( exponent % 2 != 0 ) { x = multiplication_(x, b); --exponent; } b = multiplication_(b, b); exponent /= 2; } return multiplication_(b, x); } }
74,620,649
74,620,879
Multi-type container C++. Casting to derived template class
I am trying to implement a multi-type container in C++ without using std::any, std::variant, boost::any, etc. The add() function adds new objects (int, string, or other Structures) by wrapping them in the template element class and storing as Structure pointers: using StructPtr = std::shared_ptr<Structure>; class Structure{ public: Structure() = default; Structure(const Structure& oldStruct); Structure operator = (Structure otherStruct); bool operator == (const Structure& otherStruct); template<class T> void add(T obj){ elements.emplace_back(std::make_shared<Element<T>>(obj)); } void print(std::ostream& out); std::vector<StructPtr> elements; }; template<class T> class Element : public Structure{ public: Element() = default; Element(T _element) : element(_element) { } Element( Element& oldElement){ element = oldElement.element; } T element; }; I have a print function that takes in an element and prints it: template<class T> void printElement(std::ostream& out, const Element<T>& element){ printElement(out, element.element); //this functionality has been provided already. } I want to go through each element in the vector and pass it to this print function. However, since they are stores as StructPtrs, I do not know how to cast them into this templated Element class (I cannot use dynamic_cast). This is what I tried: template<class T> void printElement(std::ostream& out, const std::vector<StructPtr>& elements){ for(auto element : elements){ auto elementDerived = static_cast<Element<T>>(*element); printElement(out, elementDerived); } } void printElement(std::ostream& out, const Structure& s){ printElement(out, s.elements); } But this gives an error: no instance of overloaded function "printElement" matches the argument listC/C++(304) task01.cpp(64, 5): argument types are: (std::__1::ostream, const std::__1::vector<StructPtr, std::__1::allocator<StructPtr>>) So, my main question is, how do I call: template<class T> void printElement(std::ostream& out, const Element<T>& element) on each element of the vector?
You can't perform a static_cast inside of printElement() since you don't know what to cast to (dynamic_cast would have helped you with that), so the only solution is to make Structure::print() be virtual and have Element override it, eg: class Structure{ public: ... virtual void print(std::ostream& out) const { printElement(out, elements); } ... }; template<class T> class Element : public Structure{ public: ... void print(std::ostream& out) const override { printElement(out, element); } ... }; void printElement(std::ostream& out, const std::vector<StructPtr>& elements){ for(auto element : elements){ element->print(out); } }
74,621,059
74,621,110
vector data loss when exiting a loop
i did a very basic and small function to convert a number smaller than 256 to binary void convertToBinary(short decimalNumber, vector<short> &binaryNumber) { short divisor = 128; while (decimalNumber != 0) { short divised = decimalNumber/divisor; // 1 binaryNumber.push_back(divised); if (decimalNumber > divisor) { decimalNumber -= divisor; } divisor /= 2; } } but when i try to get the result it always happens to be empty short decimalNumber = 231; //random number vector<short> binaryNumber; convertToBinary(decimalNumber, binaryNumber); for (int i = 0; i < size(binaryNumber); i++) { cout << binaryNumber[i]; } i think i messed up with pointers, but i dont know how to make it work
you end up with divisor = 0 this works fine while (decimalNumber != 0 && divisor > 0)
74,621,444
74,622,351
Loop control inside void function keeps looping
void getDay() { bool repeat; do { cout << "Enter the day code (first 2 letters): "; cin >> weekDay1; cin >> weekDay2; weekDay1 = toupper(weekDay1); weekDay2 = toupper(weekDay2); switch (weekDay1) { case 'M': break; case 'T': break; case 'W': break; case 'F': break; case 'S': break; default: cout << "Invalid input. Please try again.\n"; repeat = true; break; } switch (weekDay2) { case 'O': break; case 'U': break; case 'E': break; case 'H': break; case 'R': break; case 'A': break; default: cout << "Invalid input. Please try again.\n"; repeat = true; break; } }while (repeat == true); return; } I need this function to run once, and loop if the input is not one of the accepted characters. I'm trying to prevent any bad input, but it loops infinitely if the input entered on the initial run is not accepted. It works fine if the input is good on the first run, but I keep getting run-time errors for not initializing bools and I need some help adjusting this control.
The condition in the while loop is always true because you never set it to false in its body. You can do something like this: void getDay() { // Initializing while declaring is a good practice. bool repeat = false; do { . . repeat = false; . switch(...) { ... } } while (repeat); } Now, repeat = true is only called if one of the switch statements invokes default.
74,621,772
74,621,964
How to launch the QMainWindow with a fading animation?
I tried launching my window this way: #include "stdafx.h" #include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); setWindowOpacity(0); QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect(this); QPropertyAnimation* ani = new QPropertyAnimation(eff, "windowOpacity"); ani->setDuration(3000); ani->setStartValue(0); ani->setEndValue(1); ani->setEasingCurve(QEasingCurve::OutBack); ani->start(QPropertyAnimation::DeleteWhenStopped); } #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } But the window never became visible, I would like to it be initialized with a fade in effect. What's the proper way to achieve it?
Two issues I see. First, as originally written, your main function is going to exit immediately after opening the window. Add return a.exec(); at the end of main. Next, you are animating QGraphicsOpacityEffect. As written, your example code has no connection between QGraphicsOpacityEffect and the window. Your animation is animating the property on the effect class, but that doesn't propagate back to the widget. There is no need to use QGraphicsOpacityEffect. Instead, just animate the widget directly: ui.setupUi(this); setWindowOpacity(0); // Notice that the first argument passed in is 'this' - the widget. // the widget is what you want to animate. QPropertyAnimation* ani = new QPropertyAnimation(this, "windowOpacity"); ani->setDuration(3000); ani->setStartValue(0); ani->setEndValue(1); ani->setEasingCurve(QEasingCurve::OutBack); ani->start(QPropertyAnimation::DeleteWhenStopped);
74,621,794
74,621,947
Why can you cast a integer as a void pointer but can't with CString?
Just a heads up, I'm referencing from a working code, and I'm trying to implement the same method but with a CString. The below method that works, casting an integer as a void pointer: void **pParam = new void*[2]; pParam[0] = reinterpret_cast<void*>(this); pParam[1] = reinterpret_cast<void*>(iTrayNumber); _beginthreadex(NULL, 0, &CInspectionDone::InspectionDoneThread, reinterpret_cast<void*>(pParam), 0, NULL); Whereas if I do the same for CString, I'm getting these errors: CString strTest = _T("Hello"); void **pParam = new void*[2]; pParam[0] = reinterpret_cast<void*>(this); pParam[1] = reinterpret_cast<void*>(strTest); errors: 1>d:\v4\apps\serialcomm.cpp(160) : error C2440: 'reinterpret_cast' : cannot convert from 'CString' to 'void *' 1> Conversion requires a constructor or user-defined-conversion operator, which can't be used by const_cast or reinterpret_cast Is it because fundamentally you can't do the same for a CString? I tried searching around the internet and it says the function for reinterpret cast is to convert pointer of one data type to another. Unless maybe pointers are just integers and it's being accepted to be casted. If there are any explanations on this, I'll greatly appreciate it! Thanks in advance.
reinterpret_cast performs a number of specific casts, all of which are needed only in rather special circumstances. You shouldn't need reinterpret_cast for what you are doing here. One of the casts allowed with reinterpret_cast is casting one object pointer type to another object pointer type. The effect of this depends on the exact types. This is mostly useful when casting to char* or unsigned char* to obtain the object representation of an object. reinterpret_cast<void*> is pointless because conversion from any (non-const/volatile) object pointer type to void* is implicit. The cast is not required at all. Even if it is required static_cast will do the same and be less risky (since most use of reinterpret_cast is likely to end with undefined behavior). This conversion doesn't change the pointer value. The void* will point to the same object as the original pointer did. You then need to later cast the void* back to the original type with a static_cast (no reinterpret_cast required either). Casting to other types will almost always end with undefined behavior. Another conversion reinterpret_cast can perform is between object type pointers and integers. This will map the address of the pointer in some implementation-defined way to an integer value (and back). Again the only way this is useful is if you cast the integer value obtained from a pointer back to its original type. Casting a random integer value to a pointer will not likely result in a pointer value that is usable either. All of this is implementation-defined (except for the round-trip pointer->integer->pointer cast leaving the value unchanged). However there simply is no specific conversion in the list of possible conversions for reinterpret_cast that allows casting a class type to a pointer type. So CString can't be cast to void* in this way. But there wouldn't be any meaningful way to do such a conversion anyway. What would you expect the resulting pointer value to represent? You should not need any reintepret_cast here. A simple structure holding the properly-typed types will do: struct Params { CInspectionDone* a; int b; }; void *pParam = new Parames{this, iTrayNumber}; _beginthreadex(NULL, 0, &CInspectionDone::InspectionDoneThread, pParam, 0, NULL); And then InspectionDoneThread can access the parameters with e.g. static_cast<Params>(arg)->a and delete the parameters with delete static_cast<Params>(arg);. Or even better use modern C++. Since a decade ago there is std::thread, which doesn't require any pointers at all. InspectionDoneThread can just be a non-static member function with the integer as argument with appropriate type instead of needing to be a static member function with void* parameter. And then: auto mythread = std::thread(&CInspectionDone::InspectionDoneThread, this, iTrayNumber); or with a lambda: auto mythread = std::thread([&]{ InspectionDoneThread(iTrayNumber); });
74,621,892
74,621,939
Dynamic Programming: Why does the code fail when I break the if statement up into 2 lines?
I am working on this question https://structy.net/problems/min-change in which given a vector of coins and a target amount, I need to return the minimum amount of coins that satisfy the target amount. The variable island size represents the minimum amount of change that should be given to the customer and currentSize represents the current amount of coins it would take to reach the correct change given which coin's path they choose to check as denoted by the recursion. I have 2 code blocks below under the bold headers and my question is what makes the not working code blocks conditionals not work? I first check if the currnent coin paths route is valid, and if its the first valid coin path that leads to the correct change, then current miniumchange we're holding is the first valid pathway. However if we have already had a valid pathways then it would move to the second conditional where I just get the minimum of the current pathway and the total pathway given that the current pathway returns the correct amount of change. In the first block it is simply the 2 if the first block can be distributed as if((currentSize != -1 && islandSize == -1) || (currentSize != -1 && (currentSize + 1 < islandSize))) islandSize = currentSize + 1 And since currentSize must be true in both the cases it can be broken down further into /// first valid size if((currentSize != -1 && islandSize == -1) islandSize = currentSize + 1; /// the new minimum if(currentSize != -1 && currentSize + 1 < islandSize) islandSize = currentSize + 1; Since the second conditional won't modify islandSize if it is already smaller than the currentSize, the code: /// first valid size if((currentSize != -1 && islandSize == -1) islandSize = currentSize + 1; // updates islandSize min if it there exists a smaller current size if(currentSize != -1) islandSize = min(islandSize, currentSize + 1); should only update the islandSize if such a path exists smaller than the currentSize as well. Can someone assist me on where I am going wrong here? And if I can ask the question any better I would love that critique. Working Code unordered_map<int, int> memo; int minChange(int amount, std::vector<int> coins) { if(memo.count(amount)) return memo[amount]; if(amount == 0) return 0; if(amount < 0) return -1; int islandSize = -1; for(auto it : coins){ int currentSize = minChange(amount - it, coins); memo[amount-it] = currentSize; if(currentSize != -1 && (islandSize == -1 || currentSize + 1 < islandSize)) islandSize = currentSize + 1; } // todo return islandSize; } Not working code int minChange(int amount, std::vector<int> coins) { if(memo.count(amount)) return memo[amount]; if(amount == 0) return 0; if(amount < 0) return -1; int islandSize = -1; for(auto it : coins){ int currentSize = minChange(amount - it, coins); memo[amount-it] = currentSize; if(currentSize != -1 && islandSize == -1 ) islandSize = currentSize + 1; if(currentSize != -1) islandSize = min(islandSize, currentSize + 1); } // todo return islandSize; }
The conditional statement if(currentSize != -1 && (islandSize == -1 || currentSize + 1 < islandSize)) { islandSize = currentSize + 1; } could be rewritten as if(currentSize != -1) { if (islandSize == -1 || currentSize + 1 < islandSize) { islandSize = currentSize + 1; } } The two statements if(currentSize != -1 && islandSize == -1) { islandSize = currentSize + 1; } if(currentSize != -1) { islandSize = min(islandSize, currentSize + 1); } could be rewritten as if(currentSize != -1) { if (islandSize == -1) { islandSize = currentSize + 1; } else { islandSize = min(islandSize, currentSize + 1); } } The logic of the conditions just simply isn't the same: If currentSize != -1 is true then the first variant will only assign to islandSize if the second part of the condition is true; While in the second will always assign to islandSize.
74,622,124
74,622,469
Passing method with variadic arguments as template parameter for a function
Suppose to have the following definitions struct Cla { void w(int x){} }; template <typename C, void (C::*m)(int)> void callm(C *c, int args) {} template <typename C, typename... A, void (C::*m)(A...)> void callmv(C *c, A &&...args) {} int main(){ callm<Cla, &Cla::w>(&cla, 3); callmv<Cla, int, &Cla::w>(&cla, 3); } The first function (callm) is ok. The second (callmv), however, does not compile, and g++ gives the following error message test.cpp: In function ‘int main()’: test.cpp:84:28: error: no matching function for call to ‘callmv<Cla, int, &Cla::w>(Cla*, int)’ 84 | callmv<Cla, int, &Cla::w>(&cla, 3); | ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~ test.cpp:52:6: note: candidate: ‘template<class C, class ... A, void (C::* m)(A ...)> void callmv(C*, A&& ...)’ 52 | void callmv(C *c, A &&...args) {} | ^~~~~~ test.cpp:52:6: note: template argument deduction/substitution failed: test.cpp:84:28: error: type/value mismatch at argument 2 in template parameter list for ‘template<class C, class ... A, void (C::* m)(A ...)> void callmv(C*, A&& ...)’ 84 | callmv<Cla, int, &Cla::w>(&cla, 3); | ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~ test.cpp:84:28: note: expected a type, got ‘&Cla::w’ What is the correct syntax? (I already checked Methods as variadic template arguments )
All parameters after a variadic parameter pack are always deduced and can never be passed explicitly. &Cla::w is being interpreted as the next type argument in the parameter pack A, not the non-type template argument. The error you get is the compiler complaining about &Cla::w not being a type. Which means you have to pass the member function first template <typename M, M m, typename C, typename... A> void callmv(C* c, A&&... args) {} callmv<decltype(&Cla::w), &Cla::w>(&cla, 3); Alternatively, you can wrap the member function template<typename F, typename... Args> void callf(F f, Args&&... args) { f(std::forward<Args>(args)...); } callf([](Cla* c, int i) { c->w(i); }, &c, 42);
74,622,227
74,642,091
Avoid calling of function size_t Print::print(unsigned long long n, int base) if it is not implemented
I maintain an Arduino library which uses the following code (simplified) to print results received by infrared. unsigned long long decodedData; // for 8 and 16 bit cores it is unsigned long decodedData; Print MySerial; MySerial.print(decodedData, 16); Most of the 32 bit arduino cores provide the function size_t Print::print(unsigned long long n, int base) and compile without errors. But there are 32 bit cores, which do not provide size_t Print::print(unsigned long long n, int base), they only provide size_t Print::print(unsigned long n, int base) and there I get the expected compile time error call of overloaded 'print(decodedData, int)' is ambiguous. I tried to understand Check if a class has a member function of a given signature but still have no clue. I want to use MySerial.print((uint32_t)(decodedData >> 32), 16); MySerial.print((uint32_t)decodedData & 0xFFFFFFFF, 16); in case the function size_t Print::print(unsigned long long n, int base) is not provided. I tried template<typename T> struct has_uint64_print { template<typename U, size_t (U::*)(unsigned long long, int)> struct SFINAE { }; template<typename U> static char test(SFINAE<U, &U::print>*); template<typename U> static int test(...); static const bool has64BitPrint = sizeof(test<T>(nullptr)) == sizeof(char); }; and this works (Thanks to Remy Lebeau) :-). But this check does not work, since it still references the long long print function (update: and using if constexpr () -which is not available for all cores- does not help). if(has_uint64_print<Print>::has64BitPrint){ MySerial.print(decodedData, 16); } else { MySerial.print((uint32_t)(decodedData >> 32), 16); MySerial.print((uint32_t)decodedData & 0xFFFFFFFF, 16); } Is there any chance to avoid this compile error? BTW. I do not want to substitute all occurences of the 64 bit print with the 2 32 bit prints, only for one seldom used and lazy implemented 32 bit core, since all mainsteam cores work well with the 64 bit print.
With C++11 you can do something like this: #include <iostream> #include <iomanip> #include <type_traits> // First implementation of printer class Impl1 { public: static void print(uint64_t value, int base) { std::cout << "64-bit print: " << std::setbase(base) << value << "\n"; } }; // Second implementation of printer class Impl2 { public: static void print(uint32_t value, int base) { std::cout << "32-bit print: " << std::setbase(base) << value << "\n"; } }; // Template to automatically select proper version template<typename Impl, typename = void> class Print; template<typename Impl> class Print<Impl, typename std::enable_if<std::is_same<decltype(Impl::print), void(uint64_t, int)>::value>::type> { public: static void print(uint64_t value, int base) { Impl::print(value, base); } }; template<typename Impl> class Print<Impl, typename std::enable_if<std::is_same<decltype(Impl::print), void(uint32_t, int)>::value>::type> { public: static void print(uint64_t value, int base) { Impl::print(static_cast<uint32_t>(value >> 32), base); Impl::print(static_cast<uint32_t>(value), base); } }; int main() { Print<Impl1>::print(0x100000001, 16); Print<Impl2>::print(0x100000001, 16); } Second version, with function overloads and standard types: #include <iomanip> #include <iostream> #include <type_traits> // Set to 1 to see effect of using 64 bit version #define HAS_64 0 class Print { public: size_t print(unsigned int value, int base) { return base + 1; // dummy }; size_t print(long value, int base) { return base + 2; // dummy }; size_t print(unsigned long value, int base) { return base + 3; // dummy }; #if HAS_64 size_t print(unsigned long long value, int base) { return base + 4; // dummy }; #endif }; Print MySerial; // If you have C++17 you can just use std::void_t, or use this for all versions #if __cpp_lib_void_t >= 201411L template<typename T> using void_t = std::void_t<T>; #else template<typename... Ts> struct make_void { typedef void type; }; template<typename... Ts> using void_t = typename make_void<Ts...>::type; #endif // Detecting if we have 'print(unsigned long long value, int base)' overload template<typename T, typename = void> struct has_ull_print : std::false_type { }; template<typename T> struct has_ull_print<T, void_t<decltype(std::declval<T>().print(0ull, 0))>> : std::true_type { }; // Can be either class or namesapce namespace PrintXYZ { template <typename Impl, typename std::enable_if<!has_ull_print<Impl>::value, bool>::type = true> size_t print(Impl &p, unsigned long long value, int base) { p.print(static_cast<uint32_t>(value >> 32), base); p.print(static_cast<uint32_t>(value), base); return 0; // Not sure about return value here. } template <typename Impl, typename std::enable_if<has_ull_print<Impl>::value, bool>::type = true> size_t print(Impl &p, unsigned long long value, int base) { return p.print(value, base); } }; int main() { PrintXYZ::print(MySerial, 0x100000001, 16); }
74,622,526
74,622,577
Templatizing a parameter for a function in C++
I'm a beginner for programming and read an example codes, while I was learning about algorithm with C++. template <size_t N> void print(const std::array<int, N>& arr) { for(auto element: arr) { std::cout << element << ' '; } } Now I'm curious what the difference is for the templatizing like above and just passing the parameter like below. void print(const std::array<int, size_t>& arr) Does work they same? If yes, is there an advantage to write codes like the first example? If not same, could explain, what the difference between them is? I guess there is no difference between them maybe..?
Does work they same? No, the second snippet with std::array<int, size_t> won't even compile because the second template parameter of std::array is a non-type template parameter of type std::size_t and so it expects an argument of type size_t(or convertible to it). Thus, size_t is not a valid template argument for the second non-type parameter and hence the second snippet won't compile. //--------------vvvvvv------>invalid argument for a non-type parameter std::array<int, size_t>
74,622,568
74,622,745
Runtime GL_VERSION doesn't match glxinfo?
I need to use Tessellation in OpenGL, which means that my OpenGL version need to be 4.0 or upper. I get my OpenGL version with glxinfo | grep OpenGL in terminal. Output shows in the following: OpenGL vendor string: NVIDIA Corporation OpenGL renderer string: NVIDIA GeForce RTX 3090/PCIe/SSE2 OpenGL core profile version string: 4.6.0 NVIDIA 520.61.05 OpenGL core profile shading language version string: 4.60 NVIDIA OpenGL core profile context flags: (none) OpenGL core profile profile mask: core profile OpenGL core profile extensions: OpenGL version string: 4.6.0 NVIDIA 520.61.05 OpenGL shading language version string: 4.60 NVIDIA OpenGL context flags: (none) OpenGL profile mask: (none) OpenGL extensions: OpenGL ES profile version string: OpenGL ES 3.2 NVIDIA 520.61.05 OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20 OpenGL ES profile extensions: It shows apparently that My OpenGL version is 4.6.0. But when I run the code: glGetString(GL_VERSION); I get: 3.3.0 NVIDIA 520.61.05 The reason that why I find this mismatch is that I get segmentation fault when I call the function: void glPatchParameteri(GLenum pname​​, GLint value​​); My GLAD is generated with the expected version 4.6.0. And my CMakeLists.txt is edited as following: cmake_minimum_required(VERSION 3.23) project(visualization_displacement_map) set(CMAKE_C_STANDARD 11) set(CMAKE_CXX_STANDARD 14) find_package(glfw3 REQUIRED) file(GLOB project_file glad.c main.cpp) add_executable(${PROJECT_NAME} ${project_file} utility/init_func.cpp utility/callback_func.cpp utility/class/SoarCamera.cpp utility/class/SoarCamera.h program/program_test.cpp utility/class/Shader.cpp utility/class/Shader.h utility/debug_func.cpp) target_link_libraries(${PROJECT_NAME} ${TARGET_LIB} -lglfw -lGL -lm -lXrandr -lXi -lX11 -lXxf86vm -lpthread -ldl -lXinerama -lXcursor ) Why does this mismatch happen?
Which context are you requesting at runtime? Almost sounds like you are requesting a 3.3 context? (or the windowing lib you're using is). in glut: glutInitContextVersion( 3, 3 ); glutInitContextProfile( GLUT_CORE_PROFILE ); in glfw: glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); in sdl: SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
74,622,597
74,622,627
Overloaded Constructor Throwing Redefinition Error
I have an assignment that requires me to write overloaded constructors for a class (Car) in c++. I keep getting a redefinition error but cannot pinpoint what's causing it. I feel that it could possibly have to do with the code being separated out between two separate files (Car.h, Car.cpp) but I'm not sure. Here is the class in Car.h: class Car { public: Car(){}; Car(string userMake, string userModel, double userPrice){}; string getMake(); string getModel(); double getPrice(); private: string make; string model; double price; }; Here are the constructors throwing the error in Car.cpp: Car::Car () { make = "DeLorean"; model = "Alpha5"; price = 145000; } Car::Car (string userMake, string userModel, double userPrice) { make = userMake; model = userModel; price = userPrice; } Here are the compiler errors: Car.cpp:6:1: error: redefinition of ‘Car::Car()’ 6 | Car::Car () { | ^~~ In file included from Car.cpp:1: Car.h:10:9: note: ‘Car::Car()’ previously defined here 10 | Car(){}; | ^~~ Car.cpp:14:1: error: redefinition of ‘Car::Car(std::string, std::string, double)’ 14 | Car::Car (string initMake, string initModel, double initPrice) { | ^~~ In file included from Car.cpp:1: Car.h:11:9: note: ‘Car::Car(std::string, std::string, double)’ previously defined here 11 | Car(string initMake, string initModel, double initPrice){}; | ^~~ I felt like I've been following the examples given during lectures and textbook activities very closely so I'm lost on how to troubleshoot.
Car(){}; Car(string userMake, string userModel, double userPrice){}; These are defining the constructor bodies, not just declaring their signatures. Since it looks like you want to implement the constructors outside of the class in a .cpp file (which is good practice to do), just remove the braces. A prototype doesn't have a function body, even an empty one. Car(); Car(string userMake, string userModel, double userPrice);
74,622,645
74,636,953
Why in CPP in some system the RAND_MAX is set to 32K while in others it is 2147483647
In my CPP system whenever I generate a random number using rand() I always get a value between 0-32k while in some online videos and codes it is generating a value between 0-INT_MAX. I know it is dependent on RAND_MAX. So it there some way to change this value such that generated random number are of the range 0-INT_MAX Thanks in advance for the help :) #include<bits/stdc++.h> using namespace std; int main(){ srand(time(NULL)); for(int i=1;i<=10;i++){ cout << rand() << endl; } } I used this code and the random number generated are 5594 27457 5076 5621 31096 14572 1415 25601 3110 22442 While the same code on online compiler gives 928364519 654230200 161024542 1580424748 35757021 1053491036 1968560769 1149314029 524600584 2043083516
rand() is a very old function, going back to the earliest days of C. In those early days, an INT_MAX of 32k was common and well justified. Surely it's easy to see that RAND_MAX > INT_MAX doesn't make any sense. As for why some compilers have updated their RAND_MAX in the intervening years and some have not, I would guess that it's down to a commitment to backwards compatibility. I know that I've been personally bitten by the 32k limit in Microsoft's compiler. But Microsoft has long been a champion of backwards compatibility, so I'll forgive them on this one. Since C++11 there's a bunch of new random number functions that have been introduced. They're better than the old rand() in almost every way, except perhaps for ease of use.
74,623,342
74,638,350
cython cannot insert into deque using iterators
I am wondering if this is a bug or I am doing something wrong: from libcpp.deque cimport deque as cdeque cdef cdeque[int] dq1, dq2 dq1.push_back(0); dq1.push_back(1) dq2.push_back(2); dq2.push_back(3) dq1.insert(dq1.begin(), dq2.begin(), dq2.end()) The above code gives me 2 similar errors at compile time: Cannot convert 'iterator' to Python object. Each error pointing at dq2.begin() and dq2.end(). When inserting only an int it seems to work but not with iterators. Any ideas?
This was a bug in Cython versions prior to 3.0 (see this PR). On an prior version, we have the following options A: wrap insert, e.g. .... cdef extern from *: """ template <typename T, typename It> void insert(T& dest, const It& begin, const It& end){ dest.insert(dest.begin(), begin, begin) } """ void insert[T, It](T& dest, const It& begin, const It& end) ... insert(dq1, dq2.begin(), dq2.end()) B: changing/patching libcpp/deque.pxd in the local installation from void insert(iterator, input_iterator, input_iterator) to correct void insert[InputIt](iterator, InputIt, InputIt) except + This however, will not help if pyx-files needs to be build somewhere else until Cython 3.0 isn't released/used.
74,624,271
74,626,443
Is `v[i] = ++i;` a well-defined behavior?
Reading ES.43: Avoid expressions with undefined order of evaluation, it states that the result of this expression v[i] = ++i; is undefined. I'm assuming that's another way to say we got undefined behavior (UB). Reading SO posts on this topic, specifically Why is i = i++ + 1 undefined behavior in C++11? and Undefined behavior and sequence points, I conclude that the expression should be well-defined since: Value computation of right operand is sequenced before value computation of left operand for assignment operator (N4835, §[expr.ass]/1.) Side-effect of pre-increment operator is sequenced before value computation of the preincrement (sub)expression (hopefully; don't have source for this) meaning we do not have any side-effect unsequenced to value computation or another side-effect for the same object. What am I missing? Note: My question is intended for C++20. If there is any changes regarding this in previous Standards (up until C++11; so C++11, C++14 and C++17) I would like to know the changes as well. Also, I've noticed a similar post on this Why is i = v[i++] undefined?, but it's about post-increment so I didn't find an answer there.
Value computation of right operand is sequenced before value computation of left operand for assignment operator (N4835, §[expr.ass]/1.) Not only value computation, also side effects. This rule was however added only with C++17. This rule alone is enough to make your expression well-defined. But even if the side effects weren't sequenced through =, ++i is defined to be identical to i+=1, and [expr.ass]/1 also says that the side effect of (compound) assignment is sequenced before its value computation, so that your second rule is true (even before C++17). What am I missing? The core guidelines are not purely about C++17 and later. They are warning you that this may be undefined behavior depending on standard version chosen and because it is likely to be completely silent UB, that is still dangerous. There is practically no good reason to write expressions like this. Simply separating into two statement ++i; v[i] = i; takes barely any longer to write and is much easier to follow, regardless of whether v[i] = ++i; also works.
74,624,695
74,624,727
Why is my for loop not working properly when checking if a vector is sorted or not?
I'm trying to check if a vector is sorted or not with a for loop but it's not working properly until I make a small change but the logic seem to be the same to me. this is the code: vector <int> is_list_sorted(vector <int> list_of_numbers){ bool list_is_sorted = true; for(int i = 0; i < list_of_numbers.size(); i++){ if(list_of_number[i] > list_of_numbers[i + 1]){ list_is_sorted = false; } } return list_is_sorted; } int main(){ if(list_is_sorted(vector1){ cout << "the list is sorted" << endl; } else{ cout << "the list is not sorted << endl; } return 0; } I tested this function on three different vectors and the output is always the same "the list is not sorted" until I make a small change in the actual function and instead of: for(int i = 0; i < list_of_numbers.size(); i++){ if(list_of_number[i] > list_of_numbers[i + 1]){ list_is_sorted = false; } } I make it: for(int i = 1; i < list_of_numbers.size(); i++){ if(list_of_number[i] < list_of_numbers[i - 1]){ list_is_sorted = false; } } what's the bug?
With the loop for(int i = 0; i < list_of_numbers.size(); i++) then list_of_numbers[i + 1] will be out of bounds for the last element. If you go out of bounds you will have undefined behavior. A different solution would be to change the loop to: for(int i = 0; i < list_of_numbers.size() - 1; i++) Then i + 1 will not be an out of bounds index anymore. On another note: As soon as you notice that the vector isn't sorted you can return false immediately. You don't need to check the remainder of the vector.
74,624,925
74,626,248
Redefine a Node of linked list: std::string
I am currently working on a school project, the material is new to me at the moment, basically, we are creating a Robot Guider that tracks their movement, distance, speed, etc... one of the functions that we are required to make is renaming a robot, however, they are stored in Node. I have spent some time looking around for a quick solution and I am a little confused by the examples online. If someone could please help but also explain their logic that would be greatly appreciated. we are using two different classes to track all of the information -----CLASS #1: #ifndef RobotList_hpp #define RobotList_hpp #include "Robot.hpp" #include <stdio.h> #include <iostream> class RobotList{ private: class Node{ public: Robot* val; Node* next = nullptr; Node(std::string aName) { val = new Robot; val->setName(aName); } }; Node* head = nullptr; Node* tail = nullptr; public: RobotList() = default; ~RobotList(); void display() const; bool isEmpty(); Robot* find_nth(); void updateList(); void addNode(std::string name); void deleteNode(std::string name); void rename(); void robotDist() const; }; #endif /* RobotList_hpp */ ---CLASS #2: #ifndef Robot_hpp #define Robot_hpp #include <stdio.h> #include <iostream> #include <algorithm> class Robot{ private: int x, y, curSpeed, totDist; std::string name; char lastCommand; bool stop_; int off_or_on; public: std::string getName() { return name; } void setName(std::string a) { this->name = a; } int getTotDist() { return totDist; } void moveRobot(); int findRobot(); }; #endif /* Robot_hpp */ void RobotList::rename(){ std::string new_name; std::cout << "Which robot do you want to rename?"<< std::endl; std::cin >> new_name; Node* temp = head; while(!head){ if(temp->val->getName() == new_name){ // update list with user input new_name // reassign a node that holds a string value } } temp = temp->next; // rest of list til nullptr } This is what I tried to do but it was not operating properly. I wrote out two comments on what I am trying to do. Thanks.
The problem is the while loop. Head is a pointer to the first element so !head is true only when the list is empty, which is not what you want. Head should not be modified because we will lose the start of the list, that's why we have the temp. The loop should stop at the end of the list, we know we reached the end when temp is nullptr. This is convenient because it makes sure we never dereference a null pointer. temp = temp->next; should be placed inside the loop so that it doesn't get stuck at the first element. std::string old_name, new_name; std::cout << "Which robot do you want to rename?"<< std::endl; std::cin >> old_name; // name to search for std::cout << "Enter new name:"<< std::endl; std::cin >> new_name; // new name for the robot with old_name Node* temp = head; // temp = first element(node) of the list while(temp){ // while we haven't reached the end of the list if(temp->val->getName() == old_name){ temp->val->setName(new_name); break; // break if you only want to modify the first occurrence } temp = temp->next; // move to the next node } Also try to use const references for passing objects whenever possible, otherwise you create a lot of unwanted copies.
74,625,015
74,625,115
Multiple inputs in one line in C++
I've newly started learning C++ and am stuck with this problem. I need to insert a (user inputted) number of elements in a single line with space separation. If the number of elements was known, I could just write cin >> var1 >> var2 >> ... >> varN;. But how do I do it with any number of elements (loop maybe)? This is what I'm trying to do: #include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int arr[n]; for (int i=0; i<n; i++) { //stuck here } } I could have written cin >> arr[i]; and proceeded, but that would require the user to press enter after every input, which I cannot do due to the question's restrictions. How do I write the code so that all my input for array elements can be given in a single line? PS: I've seen several similar questions already answered on the site, but most of them involve implementations using vectors or are beyond my current level of understanding. A simpler solution will be appreciated.
cin>>arr[i] does not require the user to press enter after every input. You just need to give whitespace between the integer inputs. It will scan the array normally.
74,625,288
74,625,344
Returning an array with booleans c++
Sorry if this is a duplicate in advance. I am trying to return an array of booleans in a function in c++, where the array's size is declared as an argument to the array. Could I do something like this? bool returnBools(int size) { bool returnValue[size]; // Do some stuff with array return returnValue; }
It's not possible to return an array from a function in C++ (nor in C). The C++ solution is to use a vector. #include <vector> std::vector<bool> returnBools(int size) { std::vector<bool> returnValue(size); // note () not [] // Do some stuff with vector return returnValue; } When manipulating the vector you can use the notation you are already familiar with for arrays e.g. returnValue[i] = true; etc. plus a whole lot more.
74,626,140
74,626,558
First element of array not showing
I was coding a function that squares every number and then sort the array in ascending order But When I ran my code it is not showing the first element of the array i.e. if the array is [1 2 3 4 5] It is showing only [ 4 9 16 25 ] Code: #include <bits/stdc++.h> #include<vector> using namespace std; void sortedSquaredArray(vector<int> &v){ vector<int> ans; int leftPtr = 0; int rightPtr = v.size()-1; while(leftPtr < rightPtr){ if(abs(v[leftPtr]) < abs(v[rightPtr])){ ans.push_back(v[rightPtr] * v[rightPtr]); rightPtr--; } else{ ans.push_back(v[leftPtr] * v[leftPtr]); leftPtr++; } } reverse(ans.begin(),ans.end()); cout<<"Sorted Squared Array: [ "; for(int i=0; i<ans.size(); i++){ cout<<ans[i]<<" "; } cout<<"]"<<endl; } int main(){ // ? Given an integer array 'a' sorted in non-decreasing order, return an array of squares of each number sorted in non-decreasing order int n; cin>>n; vector<int> v; for(int i=0; i<n; i++){ int ele; cin>>ele; v.push_back(ele); } sortedSquaredArray(v); return 0; }
You are missing an equals sign in your "while" inside sortedSquaredArray function. It should look like this: while(leftPtr <= rightPtr).
74,626,322
74,626,541
How to include a c++ library that only provides .h and .dll files (no .lib)?
I'm working on a c++ project where I need to include the IPE library. This is available here, and since I use Windows I download and extract the windows binary package. This provides an 'include' folder with header files, and a 'bin' folder with several .dll files, among them ipe.dll. From what I understand (for example from here there are three things you need to do to link a library: You tell the compiler where to find the library's header files, if they're not in any of its default include-directories. You tell the linker to link the library. You tell the linker where to find the libary, if its not in one of its default search-directories. I use Visual Studio 2022, where these things are done in the project settings. Step 1 is easy, once I add the 'include' folder to 'Additional Include Directories' in the project settings it recognizes my #include<ipelib.h>. For step 2 and step 3 however I think I need to link a .lib file, which is not provided anywhere. Simply only linking the header files and putting the .dll files in my output folder (so skipping step 2 and 3) does not work, this results in loads of LNK2019 'unresolved external symbol' errors. I tried just linking the ipe.dll file (add ipe.dll in Linker/Input/Additional Dependencies) but when building I get this error: Error LNK1107 invalid or corrupt file: cannot read at 0x340 CGALTest C:\Program Files\IPE\ipe-7.2.26\bin\ipe.dll. This approach doesn't seem right with what I know about .dll and .lib files. However maybe this is the way to go and this corrupt file error is caused by the following, mentioned on this page: C++ mandates that it must be compiled with the same compiler that was used to compile Ipe. If you use the binary Ipe distribution for Windows, that means you have to use the g++-mingw-w64-x86-64 toolchain. I feel like this would give a different error (when actually trying to use the program, not when building it), but I'm not sure so I mention it here for completeness. If this is really the problem I have no idea how to actually use the g++-mingw-w64-x86-64 toolchain, but that's a different problem altogether. I also tried creating the .lib file myself as explained here, but that did not work either. This also feels like it should not be necessary; the IPElib documentation never mentions this. I realize this is not a very well known library, but I hope someone will know how to help anyway.
You need a .lib to link to. That .lib knows how to dynamically resolve the symbols in the .dll. If you don't have a .lib, you need to dynamically load the symbols yourself. See: Dynamically load a function from a DLL
74,626,503
74,626,600
How can I create a folder in C++ that is named using a string or char?
I'm trying to create a folder with a custom name for each user that will logged in but it doesn't work. Can you please help me? I'm a beginner and it's quite difficult. #include <iostream> #include <direct.h> using namespace std; int main() { string user = "alex"; _mkdir("D:\\Programe\\VS\\ATM\\Fisiere\\" + user); return 0; } I was trying to make the folder in the same way I make the files, but it doesn't work.
_mkdir is an older function which takes a C string as it's parameter. So you have to convert the std::string that you have into a C string. You can do that with the c_str method. Like this _mkdir(("D:\\Programe\\VS\\ATM\\Fisiere\\" + user).c_str()); This code creates a std::string by appending the path with the user string and then calls c_str on that string and then passes the result of that to _mkdir.
74,627,180
74,637,364
Projection: Is it OK to take address of data member of STL container?
Let's take (as a demo example) a simple counting algorithm for getting the max count of characters in a string. A typical C++17 implementation could be: #include <iostream> #include <unordered_map> #include <string_view> #include <algorithm> #include <utility> using Counter = std::unordered_map<char, std::size_t>; using Pair = Counter::value_type; constexpr std::string_view s{ "abbcccddddeeeeeffffff" }; int main() { Counter counter{}; for (const char c : s) counter[c]++; const auto& [letter, count] = *std::max_element(counter.begin(), counter.end(), [](Pair& p1, Pair& p2) { return p1.second < p2.second; }); std::cout << "\n\nHighest count is '" << count << "' for letter '" << letter << "'\n\n"; } In C++20 we have projections and can use pointer to structure member elements for the projection (and give that to the underlying std::invoke). The solution would be a little bit shorter, not sure, if better (for whatever criteria). Anyway: #include <iostream> #include <unordered_map> #include <string_view> #include <algorithm> using Counter = std::unordered_map<char, std::size_t>; namespace rng = std::ranges; constexpr std::string_view s{ "abbcccddddeeeeeffffff" }; int main() { Counter counter{}; for (const char c : s) counter[c]++; const auto& [letter, count] = *rng::max_element(counter, {}, &Counter::value_type::second); std::cout << "\n\nHighest count is '" << count << "' for letter '" << letter << "'\n\n"; } But, Im not sure about taking the address of a containers data member, residing in the std::namespace. Is this OK?
The only restrictions I see in [namespace.std] are about pointers to member functions. I can't find anything that would disallow taking a pointer to a (public) data member of a standard library class. This also makes sense, since the restrictions for functions are there to allow the standard library implementation to choose a different overload set than described in the standard, as long as direct calls still work as specified. However, there is no similar choice the implementation could make for a data member that is specified in the public interface (not for exposition only). So I don't see anything wrong with &Counter::value_type::second.
74,628,978
74,629,042
How do I open a file txt in a specific folder using visual studio c++?
This is the part of code where I try to open the file f1.txt, it is complete path is C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt ifstream fichier("C:\Users\Hp\Desktop\NSGA2-CDS\DataSet\f1.txt", ios::in); The file cannot be opened and I don't know why?! NSGA2-CDS is the folder that contain the visual studio solution
You have to escape backslashes in the path string: ifstream fichier("C:\\Users\\Hp\\Desktop\\NSGA2-CDS\\DataSet\\f1.txt", ios::in); This has nothing to do with file I/O as such; it's a feature of string literals: \ is used to escape special characters (such as \n, \t), so when it appears in a string, it needs to be escaped as well.
74,629,463
74,629,737
Bubble sort refuses to run in application compilers, but runs on online compilers
So this is the code I wrote for bubble sorting a user defined list. It crashes (brings the error, 'main.exe has stopped working') when I use apps like DevC++, CodeBlocks and VSCode to run. but when I use a web compiler, it works perfectly. (The apps only crash while running this code. They are able to run other pieces of code smoothly) int main() { int n; int numbers[n]; cout << "How many numbers do you want to sort?\n"; cin >> n; cout << "Enter the "<< n <<" values.\n"; for (int w = 0; w < n; w++) { cin >> numbers[w]; } cout << "The unsorted list is: \n"; for (int m = 0; m < n; m++) { cout << numbers[m] << "\t"; } for (int iterat = 0; iterat < n-1; iterat++) { for (int j = 0; j < n-1; j++) { if (numbers[j] > numbers[j + 1]) { int temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } cout << "The sorted list is: \n"; for (int p = 0; p < n; p++) { cout << numbers[p] << "\t"; } } I'm a student and we're currently learning sorting algorithms so I've asked my lecturer and multiple classmates for their help, but they're all stumped on what the problem could be because this should be correct. Please advice me on what be the problem might be and how to fix it.
Problem is numbers[n] with un initialised value of n. It takes some garbage value of n and tries to allocate space. It may work sometime and may fail sometime depending on what is the garbage value its taking. If the garbage value of n is negative or too large, it will fail. Move array declaration after initialisation of n.
74,629,665
74,629,835
Why can't I create a reference to a const pointer?
int *pointer = nullptr; const int *ponter2 = pointer; // working const int *&referpointer = pointer; // error const int *& const referpointer2 = pointer; // it is working; I wonder why a plain pointer can initialize a reference to a constant pointer to a constant, but cannot initialize a reference to a pointer to a constant
If it did work, you could do this int i; int *pointer = &i; const int *&referpointer = pointer; const int const_i = 4; const int *const_pointer = &const_i; referpointer = const_pointer; // same as pointer=const_pointer; via the reference *pointer = 5; // changes const_i Then you would have found a way to change a const variable. That's why const int *&referpointer = pointer; is not allowed.
74,629,674
74,629,719
how to add a background sound in my program that does not stop until I close the console in c++
The issue I'm facing is that the sound is not running in a loop, the whole sound is executed once, it does not repeat. So basically, I have used this method: #include <Windows.h> #include <thread> #include <iostream> void play_music() { PlaySoundA("sound.wav", NULL, SND_FILENAME | SND_LOOP); } int main(){ std::thread t(play_music); //code t.join(); }
From the documentation: SND_LOOP The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. If this flag is set, you must also set the SND_ASYNC flag.
74,629,752
74,629,961
Is there a way to write the following python If statement condition in C++?
Im in the process of trying to recreate a piece of python code for a simple calculator in C++, in python i have the following piece of code thats located in a while loop func = str(input("which function: add, sub, div, mult")) if func in ("add", "sub", "div", "mult"): #secondery if statment else: print("error") how would i go about writing if func in ("add", "sub", "div", "mult"): in C++? i have tried if (func in {"add", "sub", "div", "mult"}){ //secondery if statment else: std::cout << "error \n"; } but this doesn't work.
Here's a working snippet #include <iostream> // std::cout, std::cin #include <string> #include <array> // one of the many STL containers #include <algorithm> // std::find int main() { const std::array<std::string, 4> functions = { "add", "sub", "div", "mult" }; std::string user_input; std::cout << "which function: add, sub, div, mult? "; std::cin >> user_input; if (std::find(functions.begin(), functions.end(), user_input) != functions.end()) { std::cout << "found" << std::endl; } else { std::cout << "not found" << std::endl; } } If you want to dig more into Python's in operator equivalents there's this question with a great answer. NOTE: If you want to know which string was found you should store the iterator returned by std::find() and dereference it when needed.
74,630,061
74,630,554
Matrix out of bounds but can't put condition to check bounds
I have a square matrix, 40 x 40, and a draw circle function that uses this formula. I have another function that reads input from a file, the point itself (x0, y0) and the type of circle (0 or 1) and the radius. void cerc(int x0, int y0, int r, int** matriceHarta, int tip, int n, int m) { if (r == 0) return; int x, y, xx, rr; for (rr = r * r, x = -r; x <= r; x++) for (xx = x * x, y = -r; y <= r; y++) if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0) { if (tip == 0) matriceHarta[x0 + x][y0 + y] = -5; else if (tip == 1) matriceHarta[x0 + x][y0 + y] = -6; } } N and M are the rows and columns, but right now they are both equal. The matrix is allocated dynamically and is transmitted via the int** matriceHarta parameter. If I put the point on (39, 39) and I give it the radius 5, the program returns a negative exit code, which I found out is an out of bounds related error. I looked over the for loops and it makes sense that that'd be the error and tried to create the condition if((x0 + x) < n && (y0 + y) < m) to check the bounds, but it still gives the error. Question is, what am I doing wrong? For contrast, point(37, 4) with radius = 2 is OK, but point(38, 4) with radius = 2 is not OK This is the attempted fix: for (rr = r * r, x = -r; x <= r; x++) for (xx = x * x, y = -r; y <= r; y++) if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0 && (((x0+x) < n) && ((y0+y) < m)) ) //^^^^^ this is the condition i was talking about { if (tip == 0) matriceHarta[x0 + x][y0 + y] = -5; else if (tip == 1) matriceHarta[x0 + x][y0 + y] = -6; }
The issue is that you are testing for the out-of-bounds condition after you have already accessed potential out-of-bounds elements. Let's break it down into separate lines: if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0 && // <-- This binds the conditions (((x0+x) < n) && ((y0+y) < m))) The line above the && marked with <-- is evaluated before the line below the <--. In summary, the logical && is always evaluated from left-to-right, where the right side will not be evaluated if the left side evaluates to false (short-circuit boolean evaluation). Thus the fix is to test the bounds condition first (swap the lines in the code above). However, to make this a little more clear, you could break up the statement into two if statements: if (x0+x < n && y0+y < m) { if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0) { ... } }
74,630,543
74,630,666
Copy constructor throws null value error in C++
(Been out of touch from cpp too long, wanted to brush up for the interview tomorrow). Was revising Deep Copy v/s Shallow Copy. Wrote the code: #include <iostream> class MyClass { public: unsigned int* uivar = nullptr; MyClass() : uivar(new unsigned int) { *(this->uivar) = 3; } ~MyClass() { delete uivar; } MyClass(const MyClass& mCopy) { *(uivar) = *(mCopy.uivar); } }; void function(MyClass m) { *(m.uivar) = 4; } int main() { MyClass myClass; MyClass myClassCopy = myClass; std::cout << *(myClass.uivar) << "\n"; std::cout << *(myClassCopy.uivar) << "\n"; function(myClass); std::cout << *(myClass.uivar) << "\n"; std::cout << "hhhh" << "\n"; *(myClassCopy.uivar) = 5; std::cout << *(myClass.uivar) << "\n"; return 0; } Error(-Warn): Dereferencing NULL pointer uivar at *(uivar) = *(mCopy.uivar);. What am I missing?
Your copy constructor is not correct, it would need to allocate its own pointer MyClass(const MyClass& mCopy) { uivar = new unsigned int(*mCopy.uivar); }
74,631,498
74,636,318
How to use [[(un)likely]] at do while loop in C++20?
do [[unlikely]] {...} while(a == 0); This code can be compiled. But is this the correct way to tell compiler that a is usually non-zero.
Structurally, this is a correct way to say what you're trying to say. The attribute is placed in a location that tags the path of execution that is likely/unlikely to be executed. Applying it to the block statement of the do/while loop works adequately. It would also work within the block. That having been said, it's unclear what good this would do practically. It might prevent some unrolling of the loop or inhibit prefetching. But it can't really change the structure of the compiled code, since the block has to be executed at least once and the conditional branch has to come after the block.
74,631,663
74,631,794
g++: crash when accessing ostringstream::str().c_str()
The code below fails on gcc 9.4.0. Is this just a bug, or have I done something stupid? log declares an ostringstream object, writes a filename and a line number to it, and attempts to do something with the object's underlying str().c_str(). Valgrind shows this crashing at the pointer access. The output I get is: foo.cc, line 100 cptr is at 0x55c45e8f00c0, and is #include <iostream> #include <sstream> #include <cstdarg> using std::cout; using std::ostringstream; void log(const char *fname, int lineno) { ostringstream outstr; outstr << fname << ", line " << lineno; cout << outstr.str() << '\n'; // prints Ok const char *cptr = outstr.str().c_str(); cout << "cptr is at " << (void*) cptr << ", and is " << cptr; // crash } int main() { log("foo.cc", 100); }
std::ostringstream::str() returns a temporary string which will be destructed at the end of the line, this then means cptr is a dangling pointer. Try: std::string str = outstr.str(); const char *cptr = str.c_str(); cout << "cptr is at " << (void*) cptr << ", and is " << cptr;
74,632,788
74,632,824
string relational operator comparison vs string::compare() in cpp
In short I am getting different output for string comparison using string::compare() vs relational operator '<' on std::string class objects. string str = "100"; cout << str.compare("10")<<endl; //prints 1 cout << ("100" < "10") <<endl; //prints 1 Here's the demo url lexicographically "100" is greater than "10" and hence ("100" <"10") must print 0 since it's false but the output 1 i.e true is not expected. The str.compare() function returns > 0 which is expected validating "100" > "10". Why is this happening?
In this statement cout << ("100" < "10") <<endl; you are comparing two pointers of the type const char * to which the used string literals are implicitly converted. The result of such a comparison is undefined (At least in the C Standard there is explicitly stated that such operation is undefined). In fact the above statement is equivalent to cout << ( &"100"[0] < &"10"[0] ) <<endl; If you want to compare strings the you need to write at least like cout << (std::string( "100" ) < "10") <<endl; In this case the output will be 0 Pay attention to that according to the C++ 20 (7.6.9 Relational operators) ...The comparison is deprecated if both operands were of array type prior to these conversions And the both string literals prior to comparison have array types.
74,632,801
74,632,909
How to get a function pointer to a member function
I was working on a project where I needed to get involved with function pointers, more specifically function pointer to member functions. I have read almost all the related questions, however none of them describing my specific problem. So, I will try to describe my problem by a simple example. Let's assume that I have three different header files with different classes, like given below: foo1.h struct Foo1{ int a1; double b1; void (Foo2::*fp)(const double); } foo2.h #include "foo1.h" class Foo2{ public: void print_foo2(const double p){ cout << "From Foo2: " << p << endl; } Foo1 foo1; } foo3.h class Foo3 : public Foo2{ Foo1 foo1; foo1.fp = &Foo2::print_foo2; // cannot do that } So, one of the member variables of struct Foo1 is a function pointer to the member function of Foo2, namely print_foo2. For that reason, I create instance of object foo1 and assign it a pointer to the print_foo2. Class Foo3 inherits from class Foo2. I noted that, as I thought, may be it can be useful information for solution of the problem. However, I cannot get that pointer to the function as Foo2 is not recognized inside struct Foo1. Even including foo2.h in foo1.h doesn't help. If I am not mistaken, this is because Foo1 requires Foo2 for its member variable during construction, but in the same way Foo2 requires Foo1 to be constructed. So, this creates a deadlock. Is it the cause of the problem? If yes, how can I solve it?
Since both Foo2 and Foo3 need the definition of Foo1, they should both #include "foo1.h". Without the definition of Foo1 the compiler will not be able to calculate the size of neither Foo2 nor Foo3. Foo1 on the other hand does not need the definition of Foo2 and can therefore forward declare Foo2 to resolve the deadlock. The pointer (fp) it keeps will have the same size no matter how Foo2 is defined which is why a forward declaration is enough. Comments inline: // foo1.h #pragma once class Foo2; // forward declaration struct Foo1{ int a1; double b1; void (Foo2::*fp)(const double); }; // foo3.h #pragma once #include "foo2.h" #include "foo1.h" // not strictly needed since `foo2.h` includes it class Foo3 : public Foo2{ // proper initalization: Foo1 foo1{1, 3.141, &Foo2::print_foo2}; }; Note: In your code, both Foo2 and Foo3 has a Foo1 member variable. That means that Foo3 has 2 in total. If you only one one Foo1 in Foo3 and instead want Foo3 to initialize the Foo1 in the inherited Foo2, you can remove the Foo1 member from Foo3 and initialize the base class (Foo2) like so: class Foo3 : public Foo2{ public: Foo3() : Foo2{1, 3.141, &Foo2::print_foo2} {} };
74,632,916
74,633,153
How to access and convert pair value?
vector<pair<int,char>> alpha; for(int i = 0; i < 26; i++) { if (letter[i] > 0) { alpha.push_back(pair<int,char>(letter[i], (i+'A'))); } } sort(alpha.begin(), alpha.end()); for(auto& val : alpha){ string str = val.second; } I was trying to convert map value (which was char type) into string type using auto. I need to push those chars into string. How could I solve this?
You could do string str; for(auto& val:alpha){ str.push_back(val.second); // Append to back of string } If you want to just append chars to the string. Or you could do auto str = string s(1, val.second); // 1 is the length of the string, // and val.second is the character to fill it with If you want your strings to be just a single character long. You could use std::generate and std::transform like others suggested if you think that makes your code more readable as other commenters has suggested (I don't think so in this case). I leave that as an exercise for the reader.
74,633,705
74,633,864
Are two std::string_views refering to equal-comparing string literal always also equal?
I have an unordered_map which is supposed to mimic a filter, taking key and value as std::string_view respectively. Now say I want to compare two filters that have the same key-value-pairs: Will they always compare equal? My thought is the following: The compiler tries its best to merge const char*'s with the same byte information into one place in the binary, therefore within a specific translation unit, the string literal addresses will always match. Later I'm passing these addresses into the constructor of std::string_view. Naturally, as std::string_view doesn't implement the comparison operator==(), the compyler will byte-compare the classes and only when address and length match exactly, the std::string_views compare equal. However: What happens if I instantiate a filter outside of this translation unit with exactly the same contents as the first filter and link the files together later? Will the compiler be able to see beyond the TU boundaries and merge the string literal locations as well? Or will the equal comparison fail as the underlying string views will have different addresses for their respective string literals? Demo #include <unordered_map> #include <string_view> #include <cstdio> using filter_t = std::unordered_map<std::string_view, std::string_view>; int main() { filter_t myfilter = {{ "key1", "value"}, {"key2", "value2" }}; filter_t my_second_filter = {{ "key1", "value"}, {"key2", "value2" }}; if (my_second_filter == myfilter) { printf("filters are the same!\n"); } }
Naturally, as std::string_view doesn't implement the comparison operator==(), the compyler will byte-compare the classes That is never the case. If no operator== overload (or since C++20 a rewritten candidate overload of e.g. operator<=>) is available for a class type, then it is simply impossible to compare the type with ==. Even for non-class types the built-in == never performs a bitwise/bytewise comparison of the object representation (i.e. the values of the bytes of storage occupied the object). The built-in == always performs a comparison of values held by the objects. The only way to get bytewise comparison of the object representation is to explicitly have a operator== (or overload to which == can be rewritten) be defined to perform this comparison (e.g. by memcmp). Since that obviously wouldn't make sense for std::string_view (or most types), the standard library does not define std::string_view's operator== like that. It defines operator== (or operator<=> since C++20) instead to properly perform a comparison of the string it refers to, as a value, not as identity of a string literal or character array, see https://en.cppreference.com/w/cpp/string/basic_string_view/operator_cmp.
74,634,570
74,639,506
What can I replace with the sleep command in the Windows variant of ncurses?
#include <curses.h> #include <unistd.h> #include <iostream> int main() { initscr(); mvaddstr(10, 10, "Hello, world"); refresh(); sleep(4); endwin(); std::cout << "DONE\n"; } I'm working on a project and I need to take down the curses windows for a while just to write a path to directory in cmd and then let the curses windows come back. I found this code on this site and tried to use sleep command in the code but it didn't work. So if anyone knew how to solve this please write it down here. Thnx :)
napms is the (portable) curses function to use instead of sleep
74,634,663
74,635,744
Is there ever a reason to create elements dynamically inside of an already existing dynamic array?
This is more of a theoretical question, and a non-serious one at that, but one I couldn't find an answer to online that I'm moreso just curious about. If I were to create some class in C++ (we'll just call it Object) and made a dynamic array of this object type: Object* objectArray = new Object[someSize]; Would there ever be some instance where I would want to make the elements inside the array dynamic as well? I would imagine not, since this array already exists on the heap and there would be no reason to therefore specify that the elements inside should also be on the heap, if I understand how dynamic arrays work correctly. Object** objectArray = new Object*[someSize]; which would let you do things like: objectArray[0] = new Object(*parameters*); I know this question is a bit nonsense, but I was intrigued if there were any use-cases for this type of thing. I couldn't find any similar posts on my own. Still, if someone has asked this, feel free to just redirect me to that page, as I had no luck finding it myself.
One use case would be if you derive other classes from Object, and want the array to hold instances of different types of objects. In that case, you would need to have the array store Object* pointers, and then you would create each object individually. For example: struct Object { virtual ~Object() = default; }; struct Tree : Object { ... }; struct Bush : Object { ... }; struct Rock : Object { ... }; ... Object** objectArray = new Object*[someSize]; objectArray[0] = new Tree(...); objectArray[1] = new Bush(...); objectArray[2] = new Rock(...); ... Of course, you really should use std::vector and std::unique_ptr to manage the dynamic memory, but that doesn't change what is described above, eg: struct Object { virtual ~Object() = default; }; struct Tree : Object { ... }; struct Bush : Object { ... }; struct Rock : Object { ... }; ... std::vector<std::unique_ptr<Object>> objectArray(someSize); objectArray[0] = std::make_unique<Tree>(...); objectArray[1] = std::make_unique<Bush>(...); objectArray[2] = std::make_unique<Rock>(...); ... Or: std::vector<std::unique_ptr<Object>> objectArray; objectArray.push_back(std::make_unique<Tree>(...)); objectArray.push_back(std::make_unique<Bush>(...)); objectArray.push_back(std::make_unique<Rock>(...)); ...
74,634,692
74,635,100
Class templates with multiple unrelated arguments
I have a class template, that creates a class with two members: template<typename coordinateType, typename ...DataTypes> class Object{ public: std::tuple<coordinateType, coordinateType, coordinateType> position; std::tuple<std::vector<DataTypes>...> plantData; }; The issue is, rather than calling auto myObject = Object<float, int, int, int>(); for an instance of Object with 3 ints of data, I want to clean this up and use two separate templates, without the unrelated "float" as the first argument. Is there a way to implement this class so that it would be the equivalent of: auto myObject = Object<float>(); myObject.track<int, int, int>(); And if not, is it possible to separate those two template arguments in any way, or am I stuck with grouping them together?
if you change the caller side a little, you can make track to return a new class. template<typename T, typename...Us> struct Object{ std::tuple<T, T, T> position; std::tuple<std::vector<Us>...> plantData; }; // you can also give it a different name, here I use a specialization instead template<typename T> struct Object<T>{ template<typename...Us> Object<T,Us...> track(); }; void foo(){ auto myObjectCreator = Object<float>(); auto myObject = myObjectCreator.track<int, int, int>(); } https://godbolt.org/z/qhPrEaa96
74,634,786
74,634,879
Avoiding template parameter substitution completely
I have a class that can accept arithmetic types and std::complex. A simplified code of the class is #include <complex> template<typename T> struct is_complex : std::false_type {}; template<typename T> struct is_complex<std::complex<T>> : std::true_type {}; template<class T> struct Foo { void foo(typename T::value_type t) requires (is_complex<T>::value) { } }; Now, I would like to take the internal type of std::complex and use it as the type of the parameters in the foo function.For example, if T is std::complex<double>, then I want the parameter types to be double. This function should only be available when T is indeed std::complex. I thought I could use typename T::value_type as the parameter type, since std::complex has a typedef value_type. Plus, I thought using requires here would avoid T to be substitued in this function in case T wasn't std::complex. Silly me. The issue is that whenever I create a Foo<FundamentalType> the code breaks, since fundamentals don't have ::value_type. int main() { Foo<int> obj; // Breaks the code. //obj.foo(4); // Function shouldn't be considered in overload resolution ideally... Foo<std::complex<int>> obj2; // Works obj2.foo(4); // Works as expected } Ideally, I would like the substitution of T to be ignored for this function in case T is not std::complex. Is that possible? If not, how can I circumvent this?
You're on the right track with is_complex: you'd like the same here, but with a different body of the type. For example, template<typename T> struct complex_value_type {}; template<typename T> struct complex_value_type<std::complex<T>> { using type = T; }; template<typename T> using complex_value_type_t = typename complex_value_type<T>::type; Then, at any point, you can call it as complex_value_type_t<T>: template<class T> struct Foo { template<typename T_ = T> void foo(complex_value_type_t<T_> t) requires (is_complex<T_>::value) { } }; The requires is not absolutely necessary then; it's already covered by complex_value_type_t<T> being defined only for complex<T>.
74,634,852
74,635,392
How do I use a for loop to flash a single LED on and off? (c++) (Mbed Studio) (Nucleo Board)
I am a complete coding noob but I am trying to get all LED's to flash on and off 5 times while specifically using a for loop (it has to be a for loop). The LED in question is attached to a bus (also has to be the case) with the integer assignment of 76. EDIT: When I try a simple for loop with a counter of 5 and then turn the LED's on and off in the statement it only does it once. It may be simpler to assign my LED flashes to the count in the for loop if this is possible? My thinking so far is to either design a for loop to repeat the same number two numbers 5 times (76 and 0) and assign the bus to the count in the statement however I am struggling to get my head around how to do this only 5 times (My mind can only perceive creating a nested loop endlessly repeating) or to somehow nest a for loop with the operation I want on the inner loop counting off of the outer loop. Can anyone tell me if I'm on the right track and if so how to either run my first idea only 5 times or assign my Bus actions to my outer loop for the second? Code so far is below but I have only managed to get the LEDs to turn on. PortOut traffic(PortC, 0b0000000001001100); // The default flash rate is once per second for all tasks int main() { int i; int b; traffic = 0; // 1. Flash the ALL the LEDs 5 times using a for loop, when finished the LEDs must be OFF for (i = 0; i < 5; i= i + 1) { (printf("i%d\n", i)); for (b = i; b < 5;) { traffic = 76; wait_us(1000000); traffic = 0; } } Many thanks in advance, Joe. Tried nesting a for loop to repeat the same two integers 5 times in order to assign the Bus to the count, Only managed to endlessly repeat for loop. Tried nesting a for loop to count to 5 on the outer loop and flash LED's on the inner loop, Only managed to switch LED's on once.
Your outer loop is counting the quantity of pulses. The contents of the loop determine the frequency that an LED is on or off: for (int counter = 0; counter < 5; ++counter) { // Turn on the LEDs traffic = 76; // Wait while the LEDs are on. waitus(1000000); // Turn OFF the LEDs traffic = 0; // Wait while the LEDs are OFF. waitus(1000000); } // End of a pulse The issue is that you a delay after you turn them on and after the LEDs are turned off. You can adjust the different delay amounts; they don't need to be on and off at the same time. The delays should be able to adjust the brightness also.
74,635,031
74,635,067
Memory leak while destroying a BST
I'm trying to code a destructor for my BST so that I don't have to delete everything manually. I've tried multiple destructors for my BST but I keep getting a memory leak when running with valgrind. Here is my code (destructor at the end of code). #include <fstream> #include <iostream> #include <string> using namespace std; //struct for names struct User { string firstname; string lastname; }; //BST struct where the data in the BST are the names in struct User struct BST { User* value; int key=0; BST* leftTree; BST* rightTree; }; // creates a BST ( I do it like this incase i want to run a new function on a BST, but with a field to keep track of the size and initialize to 0) BST* createBST(){ BST* n = nullptr; return n; } // checks if empty bool isEmpty(BST* tree){ if(tree == nullptr){ return true; } return false; } // destroy the BST completely. void destroy(BST* tree){ if (tree != nullptr){ delete tree->value; destroy(tree->leftTree); destroy(tree->rightTree); delete tree; } } Main to see if code works: // TEST to see if code works correctly. int main() { BST* bst = createBST(); // I don't have an insert function yet so I do it manually bst = new BST; bst->key = 15; bst->value = new User{"John","15"}; bst->leftTree = new BST; bst->leftTree->key = 5; bst->leftTree->value = new User{"John","15"}; destroy(bst); return 0; } edit: added delete tree->value; but I still get this error: ==34== Memcheck, a memory error detector ==34== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==34== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info ==34== Command: student/labo12 ==34== ==34== Conditional jump or move depends on uninitialised value(s) ==34== at 0x400923: destroy(BST*) (in /task/student/labo12) ==34== by 0x400950: destroy(BST*) (in /task/student/labo12) ==34== by 0x400950: destroy(BST*) (in /task/student/labo12) ==34== by 0x400ABD: main (in /task/student/labo12) ==34== ==34== Conditional jump or move depends on uninitialised value(s) ==34== at 0x400923: destroy(BST*) (in /task/student/labo12) ==34== by 0x400960: destroy(BST*) (in /task/student/labo12) ==34== by 0x400950: destroy(BST*) (in /task/student/labo12) ==34== by 0x400ABD: main (in /task/student/labo12) ==34== ==34== Conditional jump or move depends on uninitialised value(s) ==34== at 0x400923: destroy(BST*) (in /task/student/labo12) ==34== by 0x400960: destroy(BST*) (in /task/student/labo12) ==34== by 0x400ABD: main (in /task/student/labo12) ==34== ==34== ==34== HEAP SUMMARY: ==34== in use at exit: 0 bytes in 0 blocks ==34== total heap usage: 8 allocs, 8 frees, 208 bytes allocated ==34== ==34== All heap blocks were freed -- no leaks are possible ==34== ==34== For counts of detected and suppressed errors, rerun with: -v ==34== Use --track-origins=yes to see where uninitialised values come from ==34== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
Count the number of new operators and delete operators in your code. They should match. But it your code you care only of the BST objects, and never delete the User. Why don't you implement the destructor of BST that correctly deletes all the fields? Update Ok, after deleting the User you have a problem of incorrectly initialized fields. You have no explicit constructor for BST, so the pointers to left, right and user are initialized with junk. That is what valgrind points you to now.
74,635,051
74,635,964
Why does clang have trouble with optimizing tail calls in destructors?
Here is a simplified singly-linked list, where each node owns the next, along with a function for destroying the list: struct Node { Node* next = nullptr; ~Node() { delete next; } }; void Destroy(Node* head) { delete head; } Clang 15.0.0 with -O3 (Compiler Explorer) gives recursive code for this that uses call instructions, i.e. no tail call recursion through ~Node itself, only operator delete(void*): Destroy(Node*): # @Destroy(Node*) test rdi, rdi je .LBB0_1 push rbx mov rbx, rdi call Node::~Node() [base object destructor] mov rdi, rbx pop rbx jmp operator delete(void*)@PLT # TAILCALL .LBB0_1: ret Node::~Node() [base object destructor]: # @Node::~Node() [base object destructor] push rbx mov rbx, qword ptr [rdi] test rbx, rbx je .LBB1_1 mov rdi, rbx call Node::~Node() [base object destructor] mov rdi, rbx pop rbx jmp operator delete(void*)@PLT # TAILCALL .LBB1_1: pop rbx ret Here is an open-coded version of something similar: struct Node2 { Node2* next = nullptr; }; void Destroy2(Node2* head) { auto* const next = head->next; delete head; if (next) { Destroy2(next); } } Even with -01 clang turns the tail call into an efficient loop with O(1) stack frames involved for an arbitrary number of list nodes: Destroy2(Node2*): # @Destroy2(Node2*) push rbx .LBB2_1: # =>This Inner Loop Header: Depth=1 mov rbx, qword ptr [rdi] call operator delete(void*)@PLT mov rdi, rbx test rbx, rbx jne .LBB2_1 pop rbx ret I understand that compiler optimizations aren't guaranteed, but I'm surprised clang isn't able to do something more efficient with the basic Destroy case. It leads me to think that the key difference is in the fact that Destroy2 is able to free the memory for head before it deals with head->next. But it seems to me that shouldn't matter unless operator delete is allowed to have some visible side effect. Is there an important semantic difference between these two from the point of view of the abstract machine, preventing clang from optimizing the first case? If so, is there a way to make ~Node more friendly to the optimizer so that I don't need to open-code a destroy function?
It's worth calling out explicitly something I alluded to in the question: that the operations in ~Node are in the opposite order that they are in Destroy2. The destructor is something like this: // Pseudocode ~Node() { delete next; free(this); } So the question is why the compiler can't reverse those two operations, putting them in the same order as in Destroy2 and allowing a tail call to ~Node for next. I can't say definitively that this is the answer, but Richard Smith points out that this could be because the compiler is limited in its ability to prove that anything preventing this would be UB. For example if there is a cycle in the list then maybe this could go wrong—a cycle would cause UB even for the existing code, but the compiler may not be able to see that. Perhaps more relevantly without an assumption about finite memory/object count (that the compiler probably doesn't make), the transformation isn't legal because the list may be unbounded without UB in the existing code. As for what to do about it, Richard also points out that in C++20 we can use a destroying operator delete to reorder the operations ourselves, giving the effect of Destroy2 with the convenience of just using delete like normal: struct Node { Node* next = nullptr; void operator delete(Node *p, std::destroying_delete_t) { Node *next = std::exchange(p->next, nullptr); ::delete p; delete next; } ~Node() { delete next; } }; As of today the generated code is good for raw pointers and bad for std::unique_ptr, but the latter gets better if you add [[gnu::flatten]] to the operator.
74,635,124
74,635,673
Convert custom type to QVariant
I have my custom type: enum class MyType : int { TYPENAME1 = 0, TYPENAME2 = 1, TYPENAME3 = 2 }; I need to convert MyType to QVariant. I tried qDebug() << QVariant::fromValue(value) but I received " " instead of property value.
For QVariant to store a custom type, you need the type to be registered with the qt meta object system. Q_ENUM or Q_ENUM_NS in the header of the type qRegisterMetaType<MyType>() called sometime before you try to use the type with QVariant (usually setup somewhere that is called when your app starts)
74,635,859
74,635,907
C++ What's the problem in this line? int [] a = new int[size];
As the title suggests, int [] a = new int[size]; constantly throws me an error. I am not yet familiar with C++ so please help me tweak the code above to as closely similar to the syntax above (above was a given pseudo(?) code in a class) so I can create an array. Thank you. #include <iostream> using namespace std; // Test program int main( ) { int [] a = new int[10]; cout << a[0]; return 0; } Tried running the above code and it failed to compile.
new is for dynamic allocation (of an array on the heap in this case), and returns a pointer to the new array. [] in the declaration are for declaring it to be a stack array (and the brackets belong the right side of the variable name). So the two legal approaches your code is mixing would simplify to either: int a[10]; // Declares a stack array of size 10 or: int *a = new int[10]; // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a` The former is the better solution here (there's no benefit to a heap allocation for such a small array that is only used within the scope of this function, and it would require explicit delete[] a; later to properly clean it up). That said, neither version initializes the values, so the contents of a[0] are uninitialized, and reading from them will get random garbage. Both versions can be changed to initialize the data with zeroes though, e.g.: int a[10] = {0}; // Declares a stack array of size 10 and initializes to zero or: int *a = new int[10](); // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`, initializing to zero Final note: Using raw new is generally frowned upon in modern C++. If you needed heap-allocated contiguous data storage, you're probably better off using a std::vector.
74,636,046
74,662,939
How to start a new process as user "NT AUTHORITY\Network Service"?
I am trying to launch a new process as NT AUTHORITY\Network Service from a process that is running as NT AUTHORITY\System. I have looked at other questions, such as the following, which does not provide a working example: CreateProcess running as user: "NT AUTHORITY/Network Service" without knowing the credentials? And, I have come across some posts which talk about copying a token from a process that is already running as NT AUTHORITY\Network Service: Windows API and Impersonation Part 1 - How to get SYSTEM using Primary Tokens. I wonder, is there a way to launch a process without having to depend on another process to copy a token from? Is there a way to hand-craft a token that can help launch a process as NT AUTHORITY\Network Service using CreateProcessAsUserW(), for example?
I came across a function LogonUser which can be used to create token for required user. The doc shows an example for creating token for NT AUTHORITY\LocalService like this: LogonUser(L"LocalService", L"NT AUTHORITY", NULL, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, &hToken) I used the above in combination with CreateProcessAsUser function which starts child process as NT AUTHORITY\NetworkService where the parent is running as NT AUTHORITY\System #include <Windows.h> HANDLE token; LogonUser( L"NetworkService", L"NT AUTHORITY", nullptr, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, &token); // Setup required variables to start the process LPPROCESS_INFORMATION lpProcessInformation; STARTUPINFOEX si; PWCHAR path; PCWSTR environmentBlockPtr = nullptr; DWORD creationFlags; WCHAR* commandStr; CreateProcessAsUser( token, nullptr, const_cast<WCHAR*>(commandStr), nullptr, nullptr, FALSE, creationFlags, const_cast<WCHAR*>(environmentBlockPtr), path, &si.StartupInfo, lpProcessInformation);
74,636,242
74,636,578
Is it worth initializing constants in the correct type? (I.e. 10UL for unsigned long)
As someone who isn't familiar with digging into post-compiled code, I'm curious if I am wasting my time for zero gain by initializing variables values to the correct type. Suppose I have class with an unsigned long member. class A { public: A() private: unsigned long my_val; }; Let's suppose I'm going to initialize my_val to zero. Does it make any difference at all if I use 0 or 0UL? class A { public: A() private: unsigned long my_val{0}; }; // or class A { public: A() private: unsigned long my_val{0UL}; }; What about in line declarations? // some method elsewhere in my program void B() { unsigned long b_val = 0; // or unsigned long b_val = 0UL; } What is the best practice here?
The short answer is that it makes no difference at all, whatsoever. An integer constant's type is the smallest type that will fit it, but no less than an int. Assigning a value to a wider integer type automatically converts. So, pedantically, a 0 value that's an int gets converted to an unsigned long 0 and gets used to initialize an unsigned long value. Alternatively, an explicit 0 value that's unsigned long from the beginning gets used to initialize the same unsigned long value. The end result is the same, and the former case will have the compiler perform the conversion itself, rather to emit explicit code to do that. The end result can be expected to be the same exact code, generated in both instances.
74,637,105
74,637,293
C++ accessing vectors in classes
i am a beginner in C++ and my question is: why my vector in a class is empty when i try to access that vector elements in another class after i added elements to that vector? i have a class for example class1 and this class has a vector of type string and a member function which adds elements to the vector with push_back() and another member function which has an argument of type string and it returns true if the argument is in the vector or else it returns false. now if i write another class class2 and it has a vector of type string named valid and a member function named check that it reads a string from input and we have a class1 object that we can access the class1 member function to check if this input is in the vector from class1 but looks like in class2 the vector i had in class1 with elements is empty. what am i doing wrong? here is code: class abc{ private: vector<string> words; public: void seta() { string s; cout << "word: "; cin >> s; words.push_back(s); } bool word_check(string a) { for(string b : words) { if(b == a) { return true; } } return false; } }; class b{ private: vector<string> valid; public: void check() { abc mlj; string k; cout << "Enter word to check: "; cin >> k; bool w = mlj.word_check(k); while(w == false) { cerr << "invalid input, try again: "; cin.clear(); cin.ignore(INT_MAX, '\n'); cin >> k; } valid.push_back(k); } }; int main() { abc vkk; vkk.seta(); vkk.seta(); vkk.seta(); b pla; pla.check(); } screenshot of the output i was expecting that i can access vector elements in class from another class
mlj is a new local object in the check method, and it contains no words. All your words were input in the main function and are stored in vkk. So you need to pass that object to check. To do that, modify the method to receive a reference void check(const abc & mlj) { string k; cout << "Enter word to check: "; cin >> k; bool w = mlj.word_check(k); // ... valid.push_back(k); } Now, this will give you a compiler error, because abc::word_check is a non-const method. Let's also fix that by adding the const specifier to the method definition. While we're at it, let's accept the string as a const reference too, and also use references while iterating over the vector. This avoids unnecessary string copying. bool word_check(const string& a) const { for(const string& b : words) { if(b == a) { return true; } } return false; } It should be noted that this can also be achieved with std::find which is provided by the standard library in <algorithm>: bool word_check(const string& a) const { return std::find(words.begin(), words.end(), a) != words.end(); } Let's circle back to your main, and update that to call check correctly: int main() { abc vkk; vkk.seta(); vkk.seta(); vkk.seta(); b pla; pla.check(vkk); // <-- pass vkk here } One other thing to note is your loop in check is broken. If w is false, then the loop will never terminate because you never update w again. How about instead you do this: while ((cin >> k) && !mlj.word_check(k)) { cerr << "invalid input, try again: "; cin.ignore(INT_MAX, '\n'); cin >> k; } if (cin) { valid.push_back(k); } This does a couple of things at once... First, it ensures the stream has actually read a string and not entered some error state (such as end of stream). Under ordinary conditions, reading strings from standard input will not result in error bits being set, so you also don't need cin.clear(). Second, it calls word_check every time around the loop, and only enters the loop body if the check fails. After the loop, we test once again that the stream is good, and if so then it means we read a word and it passed the check. Make these changes, and you're at least on the way to having a working program. There are other nit-picks I could make, but I may have done too many already so I'll stop! Happy coding!
74,637,613
74,645,865
Building C++ solution in VIsual Studio 2022 Community adds a JSON schema folder to project
Visual Studio 2022 Community version 17.4.2 Visual Studio recently updated and now whenever I build my solution a folder appears that contains a massive JSON Schema at [Solution Folder]/JSON/Schemas/Catalog/https%003A%002F%002Fgo.microsoft.com%002Ffwlink%002F%003Flinkid%003D835884 of 600 entries and over 4000 lines. This is causing havoc with my version control. How do I prevent this file from being created?
The value for Configuration Properties > C/C++ > SDLChecks was set to Yes even though the default value is already Yes. In order to fix the issue: Clean all configurations of the project via Build > Batch build... > Select All > Clean. Delete the JSON folder. Set the SDL checks value to <Inherit from parent or project defaults>. Rebuild the project.
74,637,747
74,638,059
Reduce Image bit C++
How can I reduce the number of bits from 24 bits to a number between 0 and 8 bits and distribute the bits for the three colors Red, Green and Blue Any idea ?
This is called "Color Quantization". You have 16.777.216 colors and you want to map them to a smaller number (2 to 256). Step 1: choose the colors you want to use. First their number, then the colors themselves. You need to chose if the colors are fixed for all images, or if they change based on the image (you will need to ship a palette of colors with every image). Step 2: substitute the colors of your image with those in the selection. If the colors are fixed and you want to stay very simple you can use 1 bit per channel (8 colors in total) or 2 bits per channel (64 colors in total). Slightly more complex, use these values for each channel 0, 51, 102, 153, 204, 255, in any possible way, leading to 216 different color combinations. Make a table which associates every color combination with an index. That index requires 8 bits (with some spare). This is called a "web safe palette" (this brings me back to the late 1999). Now you are ready for substitution: take every pixel in your image and the quantized color can be found as x*6//256*51 (// is integer division). If you want a better looking palette, look for the Median cut algorithm.
74,638,562
74,678,141
Convert vector<wchar_t> to string c++
I'm trying to convert a vector<wchar_t> to string (and then print it). std::string(vector_.begin(), vector_.end()); This code works fine, except äöü ÄÖÜ ß. They will be converted to: ��� I also tried converting to wstring and printing with wcout, but I got the same issue. Thanks in advance!
My Solution: First I convert my vector<wchar_t> to an utf16string like this: std::u16string(buffer_.begin(), buffer_.end()); Then I use this function, I found somewhere on here: std::string IO::Interface::UTF16_To_UTF8(std::u16string const& str) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t, 0x10ffff, std::codecvt_mode::little_endian>, char16_t> cnv; std::string utf8 = cnv.to_bytes(str); if(cnv.converted() < str.size()) throw std::runtime_error("incomplete conversion"); return utf8; } I did not write the conversion function, but it works just as expected. With this I can successfully convert a vector<wchar_t> to string
74,639,286
74,639,530
How to calculate float value and then convert to uint8_t?
How to calculate float value and then convert to uint8_t? As below, the current progress is 50, but overall just 50% completed, the correct value is 25, but I got 0. #include <iostream> using namespace std; int main() { uint8_t remaining = 1; uint8_t total = 2; uint8_t progress=50; float value=0; value = (float)(total-remaining)/total; progress = (uint8_t)value*progress; cout<<"value:"<<value<<endl; cout<<"progress:"<<(unsigned)progress<<endl; return 0; } The result are: value:0.5 progress:0 How to get the correct 25?
The (C-style) cast has higher precedence than multiplication, so your progress = (uint8_t)value*progress statement is evaluated as progress = ( (uint8_t)value ) * progress;. Thus, the 0.5 in value (from the previous line) will be truncated to zero. You need to put the multiplication in parentheses. Also, try to avoid using C-style casts: progress = static_cast<uint8_t>(value * progress);
74,640,398
74,667,072
Migrating a Visual Studio C++ Project to Linux and CMake
I'm currently trying to move from Windows 10 to Linux (Pop!_OS), but I'm having trouble getting my C++ Project to compile and run correctly on the latter. My C++ project was created using Visual Studio, where I also specified the include folders, library folders, what should be linked, etc in the solution properties. I now want to switch to writing my code using Neovim and not Visual Studio (or Visual Studio Code) and have tried compiling it via G++. I quickly noticed that my include files weren't recognized, so I tried to use CMake and created a CMakeLists.txt. I tried using both INCLUDE_DIRECTORIES() and TARGET_INCLUDE_DIRECTORIES() but no matter what path I enter, my included files were not recognized. Even when I used a path to the specific include file that caused the first error, it still wasn't recognized. My goal would be that I can specify an include folder and a library folder, so that I can just add files and folders in these and that the new files and folders automatically get recognized when compiling (i.e I would not have to edit the CMakeLists.txt in the future). Is that even possible with CMake and if yes, does anyone know where i can find further information about that or does anyone have a CMakeLists.txt file that does this? If no, would I have to specify each and every file and folder in the CMakeLists.txt file and do the same for every new include and library? Project structure: Overall folder \- build \- include ---> includeFolder1 ---> includeFolder2 ---> ... \- libs ---> library1.lib ---> library2.lib ---> ... \- src --> main.cpp --> other .cpp's and .h's --> other folders with .cpp's and .h's I've tried compiling with G++ and CMake, but both did not work, no matter what I specified as the include and library paths.
I have found the problem that caused my errors. The problem wasn't with CMake, it was with Windows and Linux specific details. I always received errors like "<foo\foo.h> no such file or directory", which led me to think that CMake couldn't find the include directory or the files in it. The problem, however, is with the include path itself. On Windows, paths can be given with a backslash ('\') but on Linux, paths are denominated with a forward slash ('/'). So in my example, the path to the file was "../foo/foo.h" but my code had "#include <foo\foo.h>". So when migrating a project from Windows to Linux, be sure to watch out for backslashes in your #include statements! Below is a template CMakeLists.txt, that should be a good starting point if you want to migrate your Visual Studio project to Linux. I've used glfw (+ glad) as an example library: cmake_minimum_required(VERSION 3.20) project(ExampleProject) add_executable(${PROJECT_NAME} src/glad.c src/main.cpp) target_include_directories(${PROJECT_NAME} PRIVATE include) target_link_libraries(${PROJECT_NAME} GL dl glfw)
74,640,655
74,640,824
How Do I Combine 4 bit values to get a single integer
I spent hours trying to figure this out. I have four binary values that I want to combine into a single number. I got it working with two numbers but I need to get it working with four. int Index = ((Bitplane0_ROW[p] & (1 << N)) >> N) | (((Bitplane1_ROW[p] & (1 << N)) >> N) << 1); // Works I am stumped. Thanks in advance. Edit.. Here is the complete program. int main() { int Bitplane0_ROW[] = { 0b01100110 , 0b11111111, 0b01011010, 0b01111110, 0b00000000, 0b10000001, 0b11111111, 0b01111110 }; // Array to to store numbers Last Row is first. int Bitplane1_ROW[] = { 0b01111110, 0b11111111, 0b11111111, 0b11011011, 0b11111111, 0b01111110, 0b00000000, 0b00000000 }; int Bitplane2_ROW[] = { 0b00000000, 0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000}; int Bitplane3_ROW[] = { 0b00000000, 0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000,0b00000000 }; int N = 7; //to store bit int c = 0; BYTE* buf = new BYTE[8 * 5]; unsigned char White[] = {255, 255, 255}; unsigned char Green[] = {53, 189,104 }; unsigned char Brown[] = {59,85,142 }; unsigned char Tan[] = {154,194,237 }; for (int p = 0; p < 8; p++) { for (int j = 0; j < 8; j++) // Row 6 { int Index = ((Bitplane0_ROW[p] & (1 << N)) >> N) | (((Bitplane1_ROW[p] & (1 << N)) >> N) << 1); // Works if(Index == 0) { // Index 0 (White) // Index = 0; buf[c + 0] = White[Index]; buf[c + 1] = White[Index+1]; buf[c + 2] = White[Index+2]; } else if (Index == 1) { // Index 1 (Green) //Index = 0; buf[c + 0] = Green[Index]; buf[c + 1] = Green[Index+1]; buf[c + 2] = Green[Index+2]; } else if (Index == 2) { // Index 2 (Brown) //Index = 0; buf[c + 0] = Brown[Index]; buf[c + 1] = Brown[Index+1]; buf[c + 2] = Brown[Index+2]; } else if (Index == 3) { // Index 3 (Tan) Index = 0; buf[c + 0] = Tan[Index]; buf[c + 1] = Tan[Index+1]; buf[c + 2] = Tan[Index+2]; } else if (Index == 15) { // Index 1 (Green) Index = 0; buf[c + 0] = Green[Index]; buf[c + 1] = Green[Index+1]; buf[c + 2] = Green[Index+2]; } c += 3; N--; } N = 7; } SaveBitmapToFile((BYTE*)buf, 8, 8, 24, 0, "C:\\Users\\Chris\\Desktop\\Link_Sprite.bmp"); delete[] buf; return 0;
You can shift the bits manually or just use std::bitset: #include <bitset> // ... std::bitset<4> bs; bs.set(0, (Bitplane0_ROW[p] >> N) & 1); bs.set(1, (Bitplane1_ROW[p] >> N) & 1); bs.set(2, (Bitplane2_ROW[p] >> N) & 1); bs.set(3, (Bitplane3_ROW[p] >> N) & 1); unsigned long index = bs.to_ulong();
74,641,369
74,641,674
Crash a thread in a Win32 application
I have an application which implements crash handling and reporting using Google Crashpad and Sentry. The application implements a watchdog which checks for freezes on critical threads, and aborts the application if it detects such a case. However, when the "crash" gets reported to Sentry, the thread that "crashed" is, of course, the watchdog thread and not the actual thread which was frozen. I need to trigger the frozen thread to abort to enable Sentry to correctly group related freezes together for analysis. On POSIX systems, I can do this trivially: pthread_kill(_threadHandle, SIGABRT); On Windows, however, there doesn't seem to be an equivalent. TerminateThread cleanly kills the thread without triggering an abort, which is not suitable. I believe that what I want to do is accomplishable with SuspendThread, GetThreadContext and ResumeThread, but how do I do this without significantly corrupting the call stack (which needs to be intact for diagnosis)?
You can set the trap flag to cause an EXCEPTION_SINGLE_STEP. CONTEXT context = { 0 }; context.ContextFlags = CONTEXT_ALL; if (SuspendThread(hThread) == (DWORD)-1) handleError(); if (!GetThreadContext(hThread, &context)) handleError(); context.EFlags |= 0x100; // set trap flag if (!SetThreadContext(hThread, &context)) handleError(); if (ResumeThread(hThread) == (DWORD)-1) handleError();
74,641,491
74,641,516
How can I convert a std::string to std::vector?
I have some code which I need to serialize a vector into bytes, then send it to a server. Later on, the the server replies with bytes and I need to serialize it back into a vector. I have managed to serialize into bytes okay, but converting back into a vector is getting the wrong values: #include <iostream> #include <string> #include <vector> int main() { std::vector<double> v = {1, 2, 3}; std::cout << "Original vector: " << std::endl; for (auto i : v) { std::cout << i << " "; } std::cout << std::endl; std::string str((char *)v.data(), sizeof(v[0])*v.size()); std::cout << "Vector memory as string: " << std::endl << str << std::endl; std::cout << "Convert the string back to vector: " << std::endl; auto rV = std::vector<double>(&str[0], &str[str.size()]); for (auto i : rV){ std::cout << i << " "; } std::cout << std::endl; return 0; } This outputs: Original vector: 1 2 3 Vector memory as string: �?@@ Convert the string back to vector: 0 0 0 0 0 0 -16 63 0 0 0 0 0 0 0 64 0 0 0 0 0 0 8 64 What is going wrong with my conversion from a string to a vector, and how can I fix it? Here is a link to run the code.
Like this std::vector<double>((double*)str.data(), (double*)(str.data() + str.size())); Basically the same as your code, but I've added some casts. In your version the chars get converted directly into doubles (as if you had written rV[0] = str[0] etc) and the vector is sizeof(double) times too big.
74,641,809
74,641,884
Add the elements of a file into a class object
I have this file that contains a name cost unit and qty of items that I need to read from and put it into a class object I want each line in the file to be a its own object the file This is the constructor for my class Cost::Cost(string name, double cost, string unit, double qty) : Item(name, unit) { this->getName() = name; this->cost= cost; this->getUnit() = unit; this->qty = qty; } I tried to do this ifstream inFile("data.txt"); string line, word, name, unit; double cost = 0.0, qty = 0.0; vector<string> itemStr; vector<Cost> itemObj; while (inFile) { while (getline(inFile, line)) { std::stringstream stream(line); while (getline(stream, word, delim)) { itemStr.push_back(word); } name = itemStr.at(0); cost = std::stod(itemStr.at(1)); unit = itemStr.at(2); qty = std::stod(itemStr.at(3)); Cost c(name, cost, unit, qty); itemObj.push_back(c); } } but it would only put the first line into the object multiple times when I want each line into its own object
Your bug is here vector<string> itemStr; vector<Cost> itemObj; while (inFile) { while (getline(inFile, line)) { std::stringstream stream(line); while (getline(stream, word, delim)) { itemStr.push_back(word); } it should be vector<Cost> itemObj; while (inFile) { while (getline(inFile, line)) { vector<string> itemStr; std::stringstream stream(line); while (getline(stream, word, delim)) { itemStr.push_back(word); } In your version the itemStr vector just grows and grows, but you keep reusing the same four elements at the start of the vector, that's why you get the same object added repeatedly. In my version the itemStr vector starts at size zero for each new line. It's good practice to declare variables as close to where you use them as possible (instead of declaring them at the start of the function). It's cleaner and make bugs like this less likely. You can also remove the while (inFile) loop which does nothing.
74,642,027
74,644,083
Python C++ API make member private
I'm making a python extension module using my C++ code and I've made a struct that I use to pass my C++ variables. I want some of those variables to be inaccessible from the python level. How can I do that? typedef struct { PyObject_HEAD std::string region; std::string stream; bool m_is_surface = false; bool m_is_stream = false; } PyType; I want m_is_surface and m_is_stream to be inaccessible by the user. Only PyType's methods should access it. So the and user CAN'T do something like this: import my_module instance = my_module.PyType() instance.m_is_surface = False # This should raise an error. Or preferably the user can't see this at all I cannot just add private to the struct because python type members are created as a standalone function and is linked to the type later on, so I cannot access them inside the struct's methods. So if I say: int PyType_init(PyType *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"thread", "region", "stream", NULL}; PyObject *tmp; if (!PyArg_ParseTupleAndKeywords(args, kwds, "bs|s", kwlist, &self->thread, &self->region, &self->stream)) return -1; return 0; } It will raise an is private within this context error.
You should do nothing. Unless you create an accessor property these attributes are already inaccessible from Python. Python cannot automatically see C/C++ struct members.
74,642,496
74,642,669
constexpr initialization std::array of std::array
The following code does not compile #include <array> #include <iostream> #include <utility> template <std::size_t N> class A { template <std::size_t... Ints> static constexpr void get_phi_base_impl(std::array<std::array<double, N>, N>& res, std::index_sequence<Ints...>) { ( (std::get<Ints>(res).fill(0), std::get<Ints>(std::get<Ints>(res)) = 1), ...); } public: static constexpr std::array<std::array<double, N>, N> get_phi_base(); static constexpr std::array<std::array<double, N>, N> base = get_phi_base(); }; template <std::size_t N> constexpr std::array<std::array<double, N>, N> A<N>::get_phi_base() { std::array<std::array<double, N>, N> res; get_phi_base_impl(res, std::make_index_sequence<N>{}); return res; } int main() { A<4> a; for (const auto& el : a.base) { for (const auto& x : el) std::cout << x << ' '; std::cout << std::endl; } return 0; } Check it Live on Coliru. g++ give a rather cryptic error main.cpp:13:76: error: 'static constexpr std::array<std::array<double, N>, N> A<N>::get_phi_base() [with long unsigned int N = 4]' called in a constant expression 13 | static constexpr std::array<std::array<double, N>, N> base = get_phi_base(); | ~~~~~~~~~~~~^~ main.cpp:17:48: note: 'static constexpr std::array<std::array<double, N>, N> A<N>::get_phi_base() [with long unsigned int N = 4]' is not usable as a 'constexpr' function because: 17 | constexpr std::array<std::array<double, N>, N> A<N>::get_phi_base() | ^~~~ clang++ gives a more understandable error test.cpp:13:57: error: constexpr variable 'base' must be initialized by a constant expression static constexpr std::array<std::array<double, N>, N> base = get_phi_base(); ^ ~~~~~~~~~~~~~~ test.cpp:27:27: note: in instantiation of static data member 'A<4>::base' requested here for (const auto& el : a.base) ^ test.cpp:19:40: note: non-constexpr constructor 'array' cannot be used in a constant expression std::array<std::array<double, N>, N> res; ^ test.cpp:13:64: note: in call to 'get_phi_base()' static constexpr std::array<std::array<double, N>, N> base = get_phi_base(); Strangely enough, if I remove the printing part in main() //for (const auto& el : a.base) // { // for (const auto& x : el) // std::cout << x << ' '; // std::cout << std::endl; // } both compilers do not complain anymore. Enabling warnings, I just get a warning of unused variable a. I am compiling with -std=c++17 -Wall -pedantic. Is there a way to constexpr construct an std::array of std::array? And why the error disappear if I omit printing? I am mainly interested in an answer with c++17. The answer to this question explains why the above code compiles in C++20, and not in C++17. However, it does not answer to the specific question of constexpr-populating an std::array<std::array<T, N>, N>. In particular, the initialization res{}; given in the answer does not fix the problem (another compilation error appears).
In C++17, a constexpr function must not contain "a definition of a variable for which no initialization is performed". This restriction is removed in C++20. In C++17, you can make your 2D array (I assume it's meant to be an identity matrix) like so: constexpr double identity_matrix_initializer(std::size_t x, std::size_t y) { return x == y ? 1.0 : 0.0; } template<std::size_t IndexY, std::size_t... IndicesX> constexpr auto make_identity_matrix_row_helper(std::index_sequence<IndicesX...>) -> std::array<double, sizeof...(IndicesX)> { return { identity_matrix_initializer(IndicesX, IndexY)... }; } template<std::size_t... IndicesX, std::size_t... IndicesY> constexpr auto make_identity_matrix_helper(std::index_sequence<IndicesX...>, std::index_sequence<IndicesY...>) -> std::array<std::array<double, sizeof...(IndicesX)>, sizeof...(IndicesY)> { return {{ make_identity_matrix_row_helper<IndicesY>(std::index_sequence<IndicesX...>{})... }}; } template<std::size_t N> constexpr auto make_identity_matrix() -> std::array<std::array<double, N>, N> { return make_identity_matrix_helper(std::make_index_sequence<N>{}, std::make_index_sequence<N>{}); } Demo These functions can of course be static inside A.
74,642,765
74,643,704
C++ classes in Header Files
I am a real beginner in C++ and am having some major problems with my current task. The goal is to implement basic Complex arithmetic in C++, but all the videos/webistes I used to get in touch with this topic did not include a .hpp (Complex.hpp) that we need to use to run our tests. But adding the Complex{...} class to this header file causes several problems in my code. #ifndef H_lib_Complex #define H_lib_Complex namespace arithmetic { class Complex { public: double re, im; Complex(); //init Complex with (0,0) Complex(double r); //init Complex with (r,0) Complex(double r, double i); //init Complex with (r,i) double real(Complex c); //return real part of Complex }; } #endif And my Complex.cpp looks like this: #include "lib/Complex.hpp" <- no complaining about the path namespace arithmetic { Complex::Complex() { this->re = 0; this->im = 0; } Complex::Complex(double r) { this->re = r; this->im = 0; } Complex::Complex(double r, double i) { this->re = r; this->im = i; } double Complex::real(Complex c){ return c.re; } //add some more functionality like abs, norm, conj,... } // namespace arithmetic Now, If I want to test my code, the test file shows the following error messages: #include "lib/Complex.hpp" <-- lib/Complex.hpp: No such file or directory(gcc) #include <cmath> #include <sstream> #include <gtest/gtest.h> using namespace arithmetic; using namespace std; TEST(TestComplex, realImag) { Complex a; Complex b = 42.0; Complex c(1.0, 2.0); ASSERT_FLOAT_EQ(a.real(), 0); ...(more tests) At ASSERT_FLOAT_EQ it shows: #define ASSERT_FLOAT_EQ(val1,val2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, val1, val2) Expands to: ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, a.real(), 0) too few arguments in function call C/C++(165) But if I understand it correctly, this test received two values a.real and 0, so why did it still not work?
real takes an argument of type Complex. I think you meant double Complex::real(){ return this->re; } change the declaration accordingly too.
74,643,322
74,648,055
If a C++ module partition B imports module partition A, is anything imported by partition A also visible in partition B?
In one module where I have partitions, I noticed that if a partition imports another partition, everything the second partition imports is also visible in the first partition. Is this correct behavior or a bug in the compiler? I am using VS2022. Lets say we have some module Foo: // Foo.ixx export module Foo; export void foo() { }; And we have another module Bar with two partitions: // Bar.ixx export module Bar; export import :PartA; export import :PartB; The first partition imports module Foo: // PartA.ixx export module Bar:PartA; import Foo; export void partA() { foo(); } The second partition imports the first partition: // Part B.ixx export module Bar:PartB; import :PartA; export void partB() { partA(); foo(); // should this compile? } Partition partB is calling function foo() from module Foo. partB did not import Foo, but partA did. In VS2022, the project compiles fine but Intellisense complains that 'foo' is undefined. Which one is correct?
[basic.scope.namespace]/2 spells out whether a name used in one TU is in scope of a TU that imports it. The short version is that foo is visible if Bar:Part2 imports Foo. So... does it? Yes. When a module partition unit imports another partition (which must be of the same module, since you cannot import someone else's partitions), it also implicitly imports non-exported TUs import by that partition: Additionally, when a module-import-declaration in a module unit of some module M imports another module unit U of M, it also imports all translation units imported by non-exported module-import-declarations in the module unit purview of U. So Bar:Part2 indirectly imports Foo.
74,643,334
74,644,996
Why loop starts with i = n/2 for doing heap sort?
I need to change max-heap code to min-heap code. I changed some parts, but when I print, I get only the min-heap array by order, not sorted. #include <iostream> #include <fstream> #define MAX_TREE 100 using namespace std; typedef struct { int key; }element; element a[MAX_TREE]; void SWAP(element root, element target, element temp) { root = target; target = temp; } void adjust(element e[], int root, int n) { //array로 입력된 tree를 min heap으로 adjust(조정해서) sort /*adjust the binary tree to etablish the heap*/ int child, rootkey; element temp; temp = a[root]; //root element assign rootkey = a[root].key; //root element's key value child = 2 * root; //root ( a[i] )의 left child //leftChild: i * 2 (if i * 2 <= n) rightChild: i * 2 + 1(if 1 * 2 + 1 <= n) while (child <= n) { //if child exists if ((child < n) &&//compare left child with right child (a[child].key > a[child + 1].key))// //if leftChild.key > rightChild.key child++;//move to smaller child if (rootkey < a[child].key) //if it satisfies min heap break; //break when root key is smaller than child's key else { //if it doesn't satisfies min heap a[child / 2] = a[child]; //assign child to parent child *= 2; //loop until there's no child } } a[child / 2] = temp; //if there's no more child, assign root element to child/2 } void heapSort(element a[], int n) { /*perform a heap sort on a[1:n]*/ int i; element temp; temp = a[1]; for (i = n / 2; i > 0; i--) { //<-This is the part I don't understand adjust(a, i, n); } for (i = n - 1; i > 0; i-- ) { SWAP(a[1], a[i + 1], temp); adjust(a, 1, i); } } void P1() { int n; std::fstream in("in1.txt"); in >> n; printf("\n\n%d\n", n); for (int i = 1; i <= n; i++) { element temp; in >> temp.key; a[i] = temp; } heapSort(a, n); //6 5 51 3 19 52 50 } int main() { P1(); } It's my professor's example code. I need to input numbers from file in1.txt. In that file there are values for n, m1, m2, m3... n is the number of key values that will follow. Following m1, m2, ... are the key values of each element. After getting input, I store integers in an array that starts with index [1]: it's a binary tree represented as an array. I need to min-heapify this binary tree and apply heapsort. This code was originally max-heap sort code. There are maybe some lines I missed to change. I don't get why I need to start for statement with i = n/2. What's the reason?
Why for statement starts with i=n/2? This is the part I don't understand This loop: for (i = n / 2; i > 0; i--) { adjust(a, i, n); } ... is the phase where the input array is made into a heap. The algorithm calls adjust for every internal node of the binary tree, starting with the "last" of those internal nodes, which sits at index n/2. This is Floyd's heap construction algorithm. There would be no benefit to calling adjust on indexes that are greater than n/2, as those indices represent leaves in the binary tree, and there is nothing to "adjust" there. The call of adjust will move the value at the root of the given subtree to a valid position in that subtree, so that that subtree is a heap. By moving backwards, this accumulates to bigger subtrees becoming heaps, until also the root is a heap. The error The error in your code is the SWAP function. As you pass arguments by value, none of the assignments in that function impact a. Correction: void SWAP(element &root, element &target) { element temp = root; root = target; target = temp; } And on the caller side, drop temp.
74,643,474
74,646,156
How can I use multiple filters on a single sink with boost::log
I'm using a sink to log information and a file with information on the different levels I want for each tag I created like so: sink->set_filter(logging::trivial::severity >= logging::trivial::warning && expr::attr<std::string>("Tag") == tag); [...] sink->set_filter(logging::trivial::severity >= logging::trivial::warning && expr::attr<std::string>("Tag") == tag1); with both tag and tag1 different tags I also tried to apply the documentation of boost::phoenix to my problem but I can't figure out how to implement it. Right now, I have this code, but it just overrides the filter each time I get into a leaf. void setSinks() { logging::core::get()->add_global_attribute("Tag", attrs::mutable_constant<std::string>("")); std::string path = "..../log_config.json"; [def of sink...] pt::ptree root; pt::read_json(path, root); std::function<void(pt::ptree, std::string)> parse_tree; auto setFilter = [](std::string tag, std::string logLevel) { logging::trivial::severity_level level; if (logLevel == "TRACE") level = logging::trivial::trace; else if (logLevel == "DEBUG") level = logging::trivial::debug; else if (logLevel == "INFO") level = logging::trivial::info; else if (logLevel == "WARNING") level = logging::trivial::warning; else if (logLevel == "ERROR") level = logging::trivial::error; else if (logLevel == "FATAL") level = logging::trivial::fatal; else level = logging::trivial::debug; return logging::trivial::severity >= level && expr::attr<std::string>("Tag") == tag; }; parse_tree = [&sink, &setFilter, &parse_tree](pt::ptree tree, std::string tag) { for (const auto& v : tree) { std::string name = v.first; pt::ptree value = v.second; if (value.empty()) { sink->set_filter(setFilter(tag + "." + name, value.data())); } else { parse_tree(value, (tag.empty() ? name : tag + "." + name)); } } }; parse_tree(root, ""); }
If your list of tags is known and fixed at compile time, you can compose a filter using template expressions like this: sink->set_filter ( (expr::attr<std::string>("Tag") == tag1 && logging::trivial::severity >= severity1) || (expr::attr<std::string>("Tag") == tag2 && logging::trivial::severity >= severity2) || ... ); Here, tag1, tag2, severity1 and severity2 may be constants or dynamic values, e.g. obtained from a file. If the list of tags is more dynamic, you could use channel_severity_filter. It is used to map severity level thresholds to different channels, and in your case your "Tag" attribute plays the role of a channel name. // Create a threshold table. If not using keywords, you have to explicitly // specify the value types of Tag and Severity attributes. auto min_severity = expr::channel_severity_filter< std::string, logging::trivial::severity_level>("Tag", "Severity"); // Populate the table. You may do this dynamically, in a loop. min_severity[tag] = severity; sink->set_filter(min_severity); You may also combine this filter with other template expressions, as shown in the docs. Lastly, you can implement whatever filtering logic you want by writing your own filtering function. typedef std::map<std::string, logging::trivial::severity_level> severity_table_t; bool my_filter( severity_table_t const& table, logging::value_ref<std::string> tag, logging::value_ref<logging::trivial::severity_level> severity) { // Check if Tag and Severity attributes were present in the log record if (!tag || !severity) return false; // Check if the Tag is present in the table auto it = table.find(*tag); if (it == table.end()) return false; // Check if Severity satisfies the threshold return *severity >= it->second; } // Populate the table, e.g. from a file severity_table_t table; sink->set_filter(boost::phoenix::bind( &my_filter, table, expr::attr<std::string>("Tag").or_none(), expr::attr<logging::trivial::severity_level>("Severity").or_none())); You can also do away with Boost.Phoenix and implement attribute value extraction yourself. typedef std::map<std::string, logging::trivial::severity_level> severity_table_t; // Populate the table, e.g. from a file severity_table_t table; sink->set_filter ( [table](logging::attribute_value_set const& record) { // Check if Tag and Severity attributes were present in the log record auto tag = record["Tag"].extract<std::string>(); if (!tag) return false; // You can use keywords to reference attribute values auto severity = record[logging::trivial::severity]; if (!severity) return false; // Check if the Tag is present in the table auto it = table.find(*tag); if (it == table.end()) return false; // Check if Severity satisfies the threshold return *severity >= it->second; } );
74,643,731
74,644,303
Finding the actual type (float, uint32_t...) based on the value of an enum (kFloat, kUint32...)
I am reading data from a file and the type of the data is stored as a uint8_t which indicates the type of data I am about to read. This is the enum corresponding to the declaration of these values. enum DataType { kInt8, kUint16, kInt16, kUint32, kInt32, kUint64, kInt64, kFloat16, kFloat32, kFloat64 }; I then get a function that reads the values stored in the file with the specific type, something like this: template<typename T> readData(T*& data, size_t numElements) { ifs.read((char*)data, sizeof(T) * numElements); } uint8_t type; ifs.read((char*)&type, 1); uint32_t numElements; ids.read((char*)&numElements, sizeof(uint32_t)); switch (type) { case kUint8: uint8_t* data = new uint8_t[numElements]; readData<uint8_t>(data, numElements); // eventually delete mem ... break; case kUint16: uint16_t* data = new int16_t[numElements]; readData<uint16_t>(data, numElements); // eventually delete mem ... break; case ... etc. default: break; } I have just represented 2 cases but eventually, you'd need to do it for all types. It's a lot of code duplication and so what I'd like to do is find the actual type of the values given the enum value. For example, if the enum value was kUint32 then the type would be uint32_t, etc. If I was able to do so, the code could become more compact with something like this (pseudo-code): DataType typeFromFile = kUint32; ActualC++Type T = typeFromFile.getType(); readData<T>(data, numElements); What technique could you recommend to make it work (or what alternative solution may you recommend?).
You're trying to take a runtime value and map it to a compile-time type. Since C++ is a compile-time typed language, there's no escaping that, at some point, you're going to have to do something like a switch/case statement at some point. This is because each option needs to have its own separate code. So the desire is to minimize how much of this you actually do. The best way to do it with standard library tools is to employ a variant. So, you create a variant<Ts>, such that the Ts types are unique_ptr<T[]>s, where the various Ts are the sequence of types in your enumeration in order. This way, the enumeration index matches the variant index. The unique_ptr part is important, as it will make the variant destroy the array for you without having to know which type it stores. So the only thing the switch/case needs to do is create the array. The processing of the array can happen in a visitor, which can be a template, as follows: variant_type data_array{}; switch (type) { case kUint8: data_array = std::make_unique<std::uint8_t[]>(numElements); case kUint16: data_array = std::make_unique<std::uint16_t[]>(numElements); default: //error out. `break` is not an option. break; } std::visit([&](auto &arr) { using arrtype = std::remove_cvref_t<decltype(arr)>; readData<typename arrtype::element_type>(arr.get(), numElements); ///... }, data_array); //data_array's destructor will destroy the allocated arrays.
74,644,036
74,644,104
i want to print a matrix into an txt file using a display function
i want to output a matrix into a txt file using a display function ( i tried to do it without the displayDor function and still didn't work) the error is in the last line inside the function enregistrer line 48 and its saying : [Error] no match for 'operator<<' (operand types are 'std::ofstream {aka std::basic_ofstream}' and 'void') the code is the following : 01 -#include <iostream> 02 -#include<ctime> 03 -#include<cstdlib> 04 -#include<fstream> 05 -using namespace std; 06 -struct Case{ 07 - bool N,W,S,E; 08 - }; 09 - 10 -struct laby{ 11 - int p; 12 - int q; 13 - Case **tab; 14 - }; 15 - 16 -laby *cree_laby(int p,int q){ 17 - laby *labyr=new laby; 18 - labyr->p=p; 19 - labyr->q=q; 20 - labyr->tab=new Case*[p]; 21 - for(int i=0;i<p;i++){ 22 - labyr->tab[i]=new Case[q]; 23 - for(int j=0;j<q;j++){ 24 - labyr->tab[i][j].N=false; 25 - labyr->tab[i][j].W=false; 26 - labyr->tab[i][j].S=false; 27 - labyr->tab[i][j].E=false; 28 - } 29 - } 30 - return labyr; 31 - } 32 - 33 -void displayLaby(const laby &labyr){ 34 - for(int i=0;i<labyr.p;i++){ 35 - for(int j=0;j<labyr.q;j++){ 36 - cout<<'['<<labyr.tab[i][j].N<<','<<labyr.tab[i][j].E<<','<<labyr.tab[i][j].S<<','<<labyr.tab[i][j].W<<']'; 37 - } 38 - cout<<"\n"; 39 - } 40 - } 41 - 42 -void enregistrer(laby & labyr,char *filename){ 43 - ofstream f; 44 - f.open(filename); 45 - f<<labyr.p; 46 - f<<labyr.q; 47 - f<<endl; 48 - f<<displayLaby(labyr); 49 -} 50 - 51 -int main(){ 52 - laby *labyr; 53 - labyr=cree_laby(5,5); 54 - enregistrer(*labyr,"laby.txt"); 55 - return 0; 56 - } i tried to use a function display and i used loops also to output the maze into a txt file but they are both not working, i would appreciate the help, Thank you,
Your displayLaby writes to std::cout, if you want it to write somewhere else (like a file) then you have to pass the stream as a parameter to the function. Like this void displayLaby(const laby &labyr, ostream& os){ for(int i=0;i<labyr.p;i++){ for(int j=0;j<labyr.q;j++){ os<<'['<<labyr.tab[i][j].N<<','<<labyr.tab[i][j].E<<','<<labyr.tab[i][j].S<<','<<labyr.tab[i][j].W<<']'; } os<<"\n"; } } void enregistrer(laby & labyr,char *filename){ ofstream f; f.open(filename); f<<labyr.p; f<<labyr.q; f<<endl; displayLaby(labyr, f); } Here os is the new parameter, and writes go to that stream instead of cout. The type of the new parameter is ostream& which means it will work for any kind of output stream. Of course if you want to write to cout anyway then you just call the new function like this displayLaby(labyr, cout);.
74,644,259
74,644,667
Make a library with cmake that use the SDL
I am trying to create a library on the top of SDL2. For the compilation I'm using cmake. First I had this CMakeLists.txt for the library : cmake_minimum_required(VERSION 3.10) project(SquareEngine) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/") find_package(SDL2 REQUIRED) find_package(SDL2_image REQUIRED) include_directories(${SDL2_INCLUDE_DIRS}) include_directories(${SDL2_IMAGE_INCLUDE_DIRS}) set (SRCS Main.cpp Rectangle.cpp Scene.cpp SquareEngine.cpp) set (HEADERS Rectangle.hpp Scene.hpp SquareEngine.hpp utils/Color.hpp utils/Vector.hpp) add_library(SquareEngine ${SRCS} ${HEADERS} ${SDL} ${SDL_SRC}) target_link_libraries(SquareEngine ${SDL2_LIBRARIES} ${SDL2_IMAGE_LIBRARIES}) To include the SDL2 and SDL2 image I follow this instructions. When I try to build it's work perfectly. Now I try to use my library in a project. I create my own project and I link my librairy that is located in a subfolder /SquareEngine in my project. For the project I use this CMakeLists.txt : cmake_minimum_required(VERSION 3.10) project(Demo) set (SRCS Main.cpp) add_subdirectory(SquareEngine) add_executable(Demo ${SRCS}) target_link_libraries(Demo PUBLIC SquareEngine) target_include_directories(Demo PUBLIC SquareEngine) When I try to build the project I got an error like this : Cannot open include file: 'SDL.h': No such file or directory I try to figure out for long time and I don't have any clue why. Maybe it will be better to use the SDL in static rather than shared ?
I think you need to add the SDL include dirs to the SquareEngine library: target_include_directories(SquareEngine PUBLIC ${SDL2_INCLUDE_DIRS} ${SDL2_IMAGE_INCLUDE_DIRS})
74,644,403
74,644,557
no match for ‘operator<<’ in C++
I'm new to C++ and I am trying to reproduce the following code from pybeesgrid repo (https://github.com/berleon/pybeesgrid/blob/master/src/beesgrid.cpp) namespace beesgrid { std::string getLabelsAsString(const Grid::idarray_t & id_arr) { std::stringstream ss; for (size_t i = 0; i < id_arr.size(); i++) { const auto & id = id_arr.at(i); if (i % 4 == 0 && i != 0) { ss << "."; } ss << id; } return ss.str(); } } I am getting the error: error: no match for ‘operator<<’ (operand types are ‘std::stringstream’ {aka ‘std::__cxx11::basic_stringstream<char>’} and ‘const boost::logic::tribool’) 17 | ss << id; | ~~ ^~ ~~ | | | | | const boost::logic::tribool | std::stringstream {aka std::__cxx11::basic_stringstream<char>} From what I understood I need to overload the << operator to read the specific types I have. Is that right? Does anyone knows how to fix it? Thanks. I tried to add the line std::stringstream& operator <<( std::stringstream &os,const id& id ); such as the code is now namespace beesgrid { std::string getLabelsAsString(const Grid::idarray_t & id_arr) { std::stringstream ss; for (size_t i = 0; i < id_arr.size(); i++) { const auto & id = id_arr.at(i); std::stringstream& operator <<( std::stringstream &os,const id& id ); if (i % 4 == 0 && i != 0) { ss << "."; } ss << id; } return ss.str(); } } But this way also doesn't work and I get the error: variable "id" is not a type name
The problem is that you haven't overloaded operator<< for boost::logic::tribool. To solve this replace std::stringstream& operator <<( std::stringstream &os,const id& id ); with //----------------------------------------------------------vvvvvvvvvvvvvvvvvvvvv--->replaced id with boost::logic::tribool here in the second parameter std::stringstream& operator <<( std::stringstream &os,const boost::logic::tribool& id );
74,645,916
74,646,740
How do I read inputs from file in c++
is there a way to read inputs from txt file 6 0 1 1 2 3 1 1 2 1 3 0 1 4 0 1 4 5 1 3 4 1 5 3 1 for the part int V = 6; Graph g(V); g.insertEdge(0,1,1); g.insertEdge(2,3,1); g.insertEdge(1,2,1); g.insertEdge(3,0,1); g.insertEdge(4,0,1); g.insertEdge(4,5,1); g.insertEdge(3,4,1); g.insertEdge(5,3,1); #include<bits/stdc++.h> using namespace std; # define INF 0x3f3f3f3f // creating a struct for an edge struct Edge { int u, v, wt; }; class Graph { int V; // adjacency list list < pair <int, int > >*adjacency; vector < Edge > edges; public : Graph( int V ) { this->V = V ; adjacency = new list < pair <int, int > >[V]; } // declaring all the functions // inserting an edge void insertEdge ( int u, int v, int w ); // deleting an edge void deleteEdge( int u, int v, int w ); // finding minimum path int minimumPath (int u, int v ); // deleting an edge void deleteEdge( int u, int v ); // finding min cycles int FindMinCycle(); }; // inserting an edge void Graph :: insertEdge ( int u, int v, int w ) { adjacency[u].push_back( make_pair( v, w )); adjacency[v].push_back( make_pair( u, w )); Edge e = { u, v, w }; edges.push_back ( e ); } // deleting an edge void Graph :: deleteEdge( int u, int v, int w ) { adjacency[u].remove(make_pair( v, w )); adjacency[v].remove(make_pair(u, w )); } // finding minimum path function int Graph :: minimumPath ( int u, int v ) { // storing vertices set< pair<int, int> > setds; // vector for distances vector<int> dist(V, INF); /* insert self source at first and initialize its distance as 0 */ setds.insert(make_pair(0, u)); dist[u] = 0; while (!setds.empty()) { /* The first vertex in Set is the one with the shortest distance; remove it from Set. */ pair<int, int> tmp = *(setds.begin()); setds.erase(setds.begin()); /* To preserve the vertices sorted distance, vertex label must be put in second of pair (distance must be first item in pair) */ int u = tmp.second; list< pair<int, int> >::iterator i; for (i = adjacency[u].begin(); i != adjacency[u].end(); ++i) { int v = (*i).first; int weight = (*i).second; if (dist[v] > dist[u] + weight) { /* If the distance of v is not INF, then it must be in our set; therefore, it should be removed and reinserted with an updated shorter distance. We only remove from Set the vertices for which the distance has been determined. Therefore, they would never see us arrive here. */ if (dist[v] != INF) setds.erase(setds.find(make_pair(dist[v], v))); dist[v] = dist[u] + weight; setds.insert(make_pair(dist[v], v)); } } } return dist[v] ; } // finding minimum path function int Graph :: FindMinCycle ( ) { int min_cycle = INT_MAX; int E = edges.size(); for ( int i = 0 ; i < E ; i++ ) { Edge e = edges[i]; /* Obtain the edge vertices that we currently delete from the graph, and then use Dijkstra's shortest path technique to discover the shortest path between these two vertices. */ deleteEdge( e.u, e.v, e.wt ) ; int dist = minimumPath( e.u, e.v ); /* If this is the shortest cycle, update min cycle; otherwise, add weight to currently deleted edges to create a cycle. */ min_cycle = min(min_cycle, dist + e.wt); // add current edge back to the graph insertEdge( e.u, e.v, e.wt ); } return min_cycle ; } int main() { int V = 6; Graph g(V); g.insertEdge(0,1,1); g.insertEdge(2,3,1); g.insertEdge(1,2,1); g.insertEdge(3,0,1); g.insertEdge(4,0,1); g.insertEdge(4,5,1); g.insertEdge(3,4,1); g.insertEdge(5,3,1); cout << "Minimum weight cycle in the graph is: "<<g.FindMinCycle() << endl; return 0; }
Simply use std::ifstream to open the file, and then use operator>> to read the values from it (it will handle skipping all of the whitespace in between the values), eg: #include <iostream> #include <fstream> using namespace std; ... int main() { int V, u, v, w; ifstream ifs("filename.txt"); if (!ifs.is_open()) { cerr << "Cannot open the file" << endl; return 0; } ifs >> V; Graph g(V); while (ifs >> u >> v >> w) { g.insertEdge(u, v, w); } cout << "Minimum weight cycle in the graph is: " << g.FindMinCycle() << endl; return 0; }
74,646,460
74,646,516
lvalue required as left operand of assignment 2
#include <iostream> using namespace std; int main() { int g1, m1, s1, g2, m2, s2, x, y, z; cin >> g1 >> m1 >> s1 >> g2 >> m2 >> s2; x=g1+g2; y=m1+m2; z=s1+s2; if(m1+m2>59) x+1 && y=y-60; if(s1+s2>59) y+1 && z=z-60; cout << x << y << z; } I'm new to c++ and don't know how to fix it, can someone help me?
The problem is that assignment operator = has the lowest precedence in your expressions: if(m1+m2>59) x+1 && y=y-60; if(s1+s2>59) y+1 && z=z-60; Thus, the compiler sees the expressions like this: (x + 1 && y) = (y - 60); (y + 1 && z) = (z - 60); And the result of (x + 1 && y) and (y + 1 && z) cannot be assigned, because it's an rvalue. Instead you probably want the assignment to take place prior to evaluating result of &&: if(m1 + m2 > 59) x + 1 && (y = y - 60); if(s1 + s2 > 59) y + 1 && (z = z - 60);
74,646,548
74,653,172
How do I use conio.h and dos.h with gcc?
I want to learn C++ and I using YouTube, but there in code are modules conio.h and dos.h. But GCC don't knows them. Which whit the same functions I can use? (Any from another questions about this don't solving my problem) I tried remove conio.h from code, but in the code, I have functions from it. That same with dos.h. After that, my text editor offered to me module coco_conio.h. What is that? Functions , that I think that are from conio.h and dos.h: #include <conio.h> #include <dos.h> HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); COORD CursorPosition; void setcursor(bool visible, DWORD size) { CONSOLE_CURSOR_INFO lpcursor; lpCursor.bvisible = visible; lpCursor.dwSize = size; SetConsoleCursorInfo(console, &lpCursor); getch(); if(kbhit()) {
This code here is a mix of the Windows API and old MS DOS libraries for the Borland Turbo compilers from 1989. You should be studying neither if your goal is to learn C++. gcc/mingw only supports Windows, not MS DOS nor 30 year old Borland-specific libraries. General advise: Don't search for knowledge or wisdom on Youtube. Reading books or taking classes are still the best bets for obtaining relevant and correct knowledge. If you are new to programming then starting with C++ is a poor choice, since it's by far the most complex programming language out there. Python, Java or C# might be more suitable as first language. Study object-orientated design at the same time as you are learning programming. Learning C before C++ isn't a bad idea since C++ is largely based on C and the languages have lots of similarities.
74,647,130
74,647,197
Why this template class works, despite using std::less oddly
This code works: #include <iostream> constexpr static auto less = std::less{}; #include <string> std::string a = "1"; std::string b = "1"; int main(){ std::cout << ( less( 6, 3 ) ? "Y" : "N" ) << '\n'; std::cout << ( less( a, b ) ? "Y" : "N" ) << '\n'; } According en.cppreference.com, std::less is implemented like this: template<class T> struct Less{ constexpr bool operator()(const T &lhs, const T &rhs) const{ return lhs < rhs; } }; but if this is true, how std::less{}; works? It will require to pass the type - std::less<int>{}; Alternatively, if implementation is like this: struct Less{ template<class T> constexpr bool operator()(const T &lhs, const T &rhs) const{ return lhs < rhs; } }; everything will works. But if this is like it is, why use class and not lambda? Strangely enough, but this code also works: #include <iostream> constexpr static auto less = std::less<int>{}; #include <string> std::string a = "1"; std::string b = "1"; int main(){ // obviously for strings it no longer works. // std::cout << ( less( 6, 3 ) ? "Y" : "N" ) << '\n'; std::cout << ( less( a, b ) ? "Y" : "N" ) << '\n'; } So what is really going on here?
Since C++14 std::less is declared as template< class T = void > struct less; and it has a specialization for void that has an operator() with the form of template< class T, class U> constexpr auto operator()( T&& lhs, U&& rhs ) const -> decltype(std::forward<T>(lhs) < std::forward<U>(rhs)); This operator() deduces the types of the parameters for you and returns lhs < rhs. This is what allows your first code block to compile. In your second example you switch less to be constexpr static auto less = std::less<int>{}; and this forces you to have comparator that only works for ints.
74,647,306
74,647,467
How to move an object from one vector to another, without destroying any?
I have a vector of objects that represent GPU resources. I ended up with a pretty dangerous scenario: the objects can only be safely created or destroyed in a specific thread, but another thread still needs to be able to move them around between vectors. As a safeguard, I deleted their copy constructor, copy assignment, and move assignment methods; the only method that isn't deleted is their move constructor. Is there a way I can move an object like this from the middle of one vector, to the back of another vector? class MappedBuffer { public: MappedBuffer(GLuint name, char * mapping) : m_name(name), m_mapping(mapping) { assert(std::this_thread::get_id() == RENDER_THREAD_ID); }; MappedBuffer(MappedBuffer && other) : m_name(other.m_name), m_mapping(other.m_mapping) { other.m_name = 0; other.m_mapping = 0; } MappedBuffer(const MappedBuffer & other) =delete; MappedBuffer & operator=(MappedBuffer && other) =delete; MappedBuffer & operator=(const MappedBuffer & other) =delete; ~MappedBuffer() { assert(m_name == 0 || std::this_thread::get_id() == RENDER_THREAD_ID); if (m_name) { gl::buffer::unmap(m_name); gl::buffer::dealloc(m_name); } } private: char * m_mapping {0}; // directly points to GPU memory GLuint m_name {0}; }; // not the render thread int f(size_t srcIndex, std::vector<MappedBuffer> & src, std::vector<MappedBuffer> & dest) { // how could someone do something like the following, but without destroying any of the objects? dest.push_back(src.begin() + srcIndex); dest.erase(src.begin() + srcIndex); }
Two vectors do not share an allocation (except if one is move-constructed/-assigned from the other). Therefore moving between vectors implies creating a new object in the new vector's allocation and destroying the one in the old allocation. Only node-based containers offer an interface to reassign elements between containers without a move of the stored object, e.g. std::list::splice. The alternative is to add an indirection to the vector, by storing pointers (of whatever kind) to the objects instead of the objects themselves in it. Without indirection per element this can't work. You can't insert into the vector either under these constraints. Insertion may cause reallocation and consequently move and destruction of objects. However, the type you are showing already contains an indirection via the char* pointer. Your class sets m_name to zero and therefore an "empty" state if it is moved-from and the destructor won't actually do anything. So destruction after a move is completely safe. The move assignment can simply behave in exactly the same way. And then there won't be any issue at all. As long as the copy operations are deleted, the container can only destroy an object in a moved-from state or if deletion of elements is explicitly requested (e.g. .clear()). Otherwise destroying would mean dropping an object with a value that could have never had a copy made, implying that the container would lose information that it may not lose. The container also can't use a move assignment to overwrite a non-empty object for the same reason, except when erasure of an element is requested.
74,647,368
74,647,462
How to go (in a random order) through all the elements of a 2D array with a specific state
I have a simple 2D array in C++ like this: Cell field[57][57]; enum State {foo, bar, baz}; Where each Cell is defined as typedef struct Cell_t{ enum State state; int value; float temperature; }Cell; My goal is to go through the field and do something with all the cells which have their state currently set as foo. The goal is to go through these in a random order. After having gone through all of the foo cells, one time step is finished and the next can happen. That means that for example, the field might contain 1000 cells whose state is baz, and 197 cells whose state is foo, the rest is bar. They are all at random places in the 2D array. I need to go through all the foo cells in random order, do something with them, and only them. The thing is that the actions of one foo cell can turn a cell that was not foo before into a foo cell. This new cell, however, will not make its move in this step, only the foo cells that were foo before the first change of this step can make their move. What would be the correct way to do this? What I tried: I went through the field sequentially, looking for foo cells, added their coordinates to a vector of coordinate arrays {x,y}, then chose one randomly, accessed it (by knowing its coordinates) in the field, did the necessary action, then deleted the coordinates from the vector. Then I chose the next random coordinates, and the next, until the vector is empty. The next step can begin afterwards. However, I can have thousands upon thousands of cells at any given time and constantly adding and removing items from the vector can be costly. What is the fastest way to do this?
You can put all the coordinates of foo cells in an std::vector and std::shuffle it. That's what I would do: #include <random> #include <algorithm> int main() { Cell field[57][57]; std::vector<std::pair<int, int>> cellsToVisit; for (int i = 0; i < 57; i++) { for (int j = 0; j < 57; j++) { if (field[i][j].state == foo) { cellsToVisit.push_back({i, j}); } } } std::default_random_engine rng; std::shuffle(cellsToVisit.begin(), cellsToVisit.end(), rng); for (const auto& ij: cellsToVisit) { std::cout << "Visit cell " << ij.first << ", " << ij.second << std::endl; } return 0; }
74,647,547
74,647,713
Determinant of a Matrix, C++ code troubleshooting
main.c #include <stdio.h> #include <string.h> #include "matrix.h" int main(){ //Prompt the user for the size of matrix to be calculated. printf("Welcome to the matrix determinant calculator!\n\n"); printf("Please select the matrix size you would like to input: \n"); printf("\t (A): 2x2 matrix\n"); printf("\t (B): 3x3 matrix\n\n"); char selection; //Stores matrix size selection scanf(" %c", &selection); int size; //Size of matrix //Uses selection from user to determine value to assign to 'size' if (selection == 'A' || selection == 'a'){ size = 2; } else if (selection == 'B' || selection == 'b'){ size = 3; } else{ printf("Your selection is invalid. Please start over.\n"); return 0; } printf("\nYou have selected a %dx%d matrix.\n\n", size, size); //Initialize pointer array int** matrix = (int**)malloc(size * sizeof(int*)); for (int i = 0; i < size; i++){ matrix[i] = (int*)malloc(size * sizeof(int)); } readMatrix(matrix, size); //Sets up matrix by taking input from user int calc = determinant(matrix, size); //Calculates determinant printf("The %dx%d matrix is: \n\n", size, size); //Displays the matrix on the console for (int row = 0; row < size; row++){ for (int col = 0; col < size; col++){ printf("%d\t", matrix[row][col]); } printf("\n"); } //Deletes stored data for (int i = 0; i < size; i++){ free(matrix[i]); } free(matrix); printf("\nThe determinant of the matrix is: %d\n", calc); return 0; } determinant.c #include <iostream> #include <string> #include "matrix.h" #include "determinant.h" using namespace std; int determinant(int** matrix, int size){ int detm_calc; //Determinant calculation variable //Determine which formula to use - 2x2 or 3x3 matrix. if (size == 2){ //2x2 case int a = matrix[0][0]; int b = matrix[0][1]; int c = matrix[1][0]; int d = matrix[1][1]; detm_calc = (a*d) - (b*c); } else{ //3x3 case int a = matrix[0][0]; int b = matrix[0][1]; int c = matrix[0][2]; int d = matrix[1][0]; int e = matrix[1][1]; int f = matrix[1][2]; int g = matrix[2][0]; int h = matrix[2][1]; int i = matrix[2][2]; detm_calc = a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h - e*g); } return detm_calc; } determinant.h #ifndef DETERMINANT_H #define DETERMINANT_H #include <string> #include <iostream> #include "matrix.h" int determinant(int**, int); #endif matrix.c #include <stdio.h> #include <stdlib.h> #include "matrix.h" #include "determinant.h" void readMatrix(int** matrix, int size){ for (int i = 0; i < size; i++){ for (int j = 0; j < size; j++){ printf("Please enter the integer for row %d column %d:\t", i+1, j+1); scanf("%d", &matrix[i][j]); } printf("\n"); } } matrix.h #ifndef MATRIX_H #define MATRIX_H #include <string> #include <iostream> #include "determinant.h" void readMatrix(int**, int); #endif Makefile determinant: main.o determinant.o matrix.o g++ main.o determinant.o matrix.o -o determinant.out main.o: main.c g++ -c main.c determinant.o: determinant.c determinant.h g++ -c determinant.c matrix.o: matrix.c matrix.h g++ -c matrix.c My code to create a determinant of a matrix is infinitely looping. What is wrong with the code shown? I believe it has something to do with the code within the main.c function and Initializing the pointer array but I can't pinpoint what is wrong.
There is something wrong with your includes. You are trying to include 'iostream' in a .c file, while iostream is only used for c++. In c, you can import <stdio.h>, which gives you access to the 'printf' function. You are also importing 'string.h', which you are not using in your program. You also forgot to include <stdlib.h> in your main.c file, which is needed to call malloc. In determinant.c, you are also using a namespace. C does not allow namespaces. While compiling, you are using g++. g++ is used to compile c++ code. Since your files are written in c, you should use gcc.
74,647,845
74,648,132
Need a way to check template type and if not in the range of allowed types then have compile time error in C++
I need to have a template class where each object adds itself to a vector and based on the template type parameter(allowed only: string, int, float) add to the corresponding container. I need a way to have compile time checks for the type and based on the check add to the corresponding container and if the type is not one of the allowed types compile time error should be emitted. Example: code vector<myClass<int>*> intVec; vector<myClass<float>*> floatVec; vector<myClass<string>*> stringVec; template<typename T> struct myClass { myClass() { /*pseudo code if(T == int) { intVec.push_back(this); } else if(T == float) { floatVec.push_back(this); } else if(T == string){ stringVec.push_back(this); } else { // error } */ } T value; } How can I achieve this ?
Use specialization and a helper function, e.g. template<typename T> struct myClass; inline std::vector<myClass<int>*> intVec; inline std::vector<myClass<float>*> floatVec; inline std::vector<myClass<std::string>*> stringVec; template<typename T> void add(myClass<T>*); template<> void add(myClass<int>* p) { intVec.push_back(p); } template<> void add(myClass<float>* p) { floatVec.push_back(p); } template<> void add(myClass<std::string>* p) { stringVec.push_back(p); } template<typename T> struct myClass { myClass() { add(this); } T value; };
74,648,931
74,648,951
Case statement saying it appeared before
I have these 2 case statements: case SDLK_w && SDLK_a: { ball.posX -= mers; ball.posY -= mers; break; } case SDLK_w && SDLK_d: { ball.posX += mers; ball.posY -= mers; break; } The second SDLK_w gives me an error saying: case label value has already appeared in this switch It may be because case statements don't work with &&, but it only shows me an error at the second W key and not at the first one. Any suggestions?
SDLK_w && SDLK_a is another way of writing 1 because they are both true. SDLK_w && SDLK_d is also another way of writing 1. Perhaps you meant this case SDLK_w: case SDLK_a: // two case statements in a row: both of them run the same code { ball.posX -= mers; ball.posY -= mers; break; } case SDLK_w: case SDLK_d: { ball.posX += mers; ball.posY -= mers; break; } but it still doesn't make sense because SDLK_w has two cases.
74,649,350
74,649,730
Separate a float into 4 uint8_ts and then merge back together
I'm working on developing both the client(C) and server(C++) side of an RF connection. I need to send a float value, but the way the architecture is set up I have to arrange my message in a struct that limits me to 3 uint8t parameters: p0, p1, p2. My solution was to break the float into an array of 4 uint8_ts and send in 2 separate messages and use p0 as an identifier whether the message contains the first or second half. So far I have something like this: Server (C++): sendFloat(float f) { messageStruct msg1, msg2; uint8_t* array = (uint8_t*)(&f); msg1.p0 = 1; //1 means it's the first half msg1.p1 = array[0]; msg1.p2 = array[1]; msg2.p0 = 0; //0 means it's the second half msg2.p1 = array[2]; msg2.p2 = array[3]; sendOverRf(msg1); sendOverRf(msg2); } Client(C): processReceivedMessage (uint32_t id, uint32_t byteA, uint32_t byteB) //(p0,p1,p2) are routed here { static uint32_t firsHalfOfFloat; uint32_t ondHalfOfFloat; float combinedFloat; if(id == 1) //first half { firstHalfOfFloat = (byteA << 8) | byteB; } else //second half { secondHalfOfFloat = (byteA << 8) | byteB; combinedFloat = (float)((firstHalfOfFloat << 16) | secondHalfOfFloat); } writeFloatToFile(combinedFloat); } then on request the client must then send that float back Client(C): sendFloatBack(uint8_t firstHalfIdentifier) // is commanded twice by server with both 0 and 1 ids { messageStruct msg; float f = getFloatFromFile(); uint8_t* array = (uint8_t*)(&f); msg.p0 = firstHalfIdentifier; if(firstHalfIdentifier == 1) //First half { msg.p1 = array[0]; msg.p2 = array[1]; } else //Second half { msg.p1 = array[2]; msg.p2 = array[3]; } sendOverRf(msg); } and finally the Server (C++) gets the value back: retrieveFunc() { float f; uint32_t firstHalf; uint32_t secondHalf; messageStruct msg = recieveOverRf(); firstHalf = (msg.p1 << 8) | msg.p2; msg = receiveOverRf(); firstHalf = (msg.p1 << 8) | msg.p2; f = (firstHalf << 16) | secondHalf; } but I'm getting really wrong values back. Any help would be great.
Unions are a very convenient way to disassemble a float into individual bytes and later put the bytes back together again. Here's some example code showing how you can do it: #include <stdio.h> #include <stdint.h> typedef union { uint8_t _asBytes[4]; float _asFloat; } FloatBytesConverter; int main(int argc, char** argv) { FloatBytesConverter fbc; fbc._asFloat = 3.14159; printf("Original float value is: %f\n", fbc._asFloat); printf("The bytes of the float are: %u, %u, %u, %u\n" , fbc._asBytes[0] , fbc._asBytes[1] , fbc._asBytes[2] , fbc._asBytes[3]); // Now let's put the float back together from the individual bytes FloatBytesConverter ac; ac._asBytes[0] = fbc._asBytes[0]; ac._asBytes[1] = fbc._asBytes[1]; ac._asBytes[2] = fbc._asBytes[2]; ac._asBytes[3] = fbc._asBytes[3]; printf("Restored float is %f\n", ac._asFloat); return 0; }
74,649,528
74,649,645
Coroutines: Do co_yielded string_views dangle?
I want to mix up the co_yielding string literals and std::strings Generator<std::string_view> range(int first, const int last) { while (first < last) { char ch = first++; co_yield " | "; co_yield std::string{ch, ch, ch}; } } However, I'm wondering about the lifetime of the std::string? Maybe it's safe if you know you are going to consume the string_view immediately? for(auto sv : range(65, 91)) std::cout << sv; https://godbolt.org/z/d5eoP9aTE You could make it safe like this Generator<std::string_view> range(int first, const int last) { std::string result; while (first < last) { char ch = first++; co_yield " | "; result = std::string{ch, ch, ch}; co_yield result; } }
co_yield is a fancy form of co_await. Both of these are expressions. And therefore, they follow the rules of expressions. Temporaries manifested as part of the evaluation of the expression will continue to exist until the completion of the entire expression. co_await expressions do not complete until after the coroutine resumes. This is important, as you often co_await on prvalues, so if you do something as simple as co_await some_function(), you need the return value of some_function to continue to exist, as its await_resume function needs to be able to be called. As previously stated, co_yield is just a fancy form of co_await. So the rules still apply. So any string_view objects returned by your generator will point to valid values between calls to resume the coroutine.
74,651,333
74,659,581
Vulkan Validation Layers Not Available
I'm new to Vulkan, and I've been following vulkan-tutorial.com which has been a great resource so far. However, one weird thing I've come to realize is that validation layers are supported on my device, but cannot be used without being overridden in vkconfig. Following the tutorial, this is my C++ code at the moment: auto check_validation_layer_support() -> bool { // Get the number of layers uint32_t layerCount = 0U; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); // Get the layer properties std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); // Iterate through to check support for (const char* layerName : VulkanInstance::validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if(!layerFound) return false; } return true; } static constexpr std::array<const char* const, 1UL> validationLayers { "VK_LAYER_KHRONOS_validation", }; source "/opt/vulkansdk/1.3.224.1/setup-env.sh" export VK_LAYER_PATH="$VULKAN_SDK/lib/vulkan/layers" export VK_INSTANCE_LAYERS="VK_LAYER_LUNARG_api_dump:VK_LAYER_KHRONOS_validation" When running vkconfig and overriding to use Validation Layers, suddenly everything works perfectly fine. However, if it is not a forced override, it will not work at all. I'm using the LunarG SDK (1.3.224.1) for Arch Linux (Wayland).
Your setting for VK_LAYER_PATH does not look right. The setup script should set a "layer path" environment variable for you and so you could try not exporting VK_LAYER_PATH after running the setup script. And if you were to set VK_LAYER_PATH, it should be something like $VULKAN_SDK/etc/vulkan/explicit_layer.d. Note that the setup script actually sets VK_ADD_LAYER_PATH which tells the loader to look in the SDK in addition to and before the system default paths. Setting VK_LAYER_PATH after running the setup script causes the loader to ignore VK_ADD_LAYER_PATH and use only VK_LAYER_PATH, which was faulty in your case. This left the loader with no good paths to find layers.
74,651,380
74,651,491
Utilizing large data in a class that is instanated multiple times
I have the following class: #include <map> using namespace std; class A { const map<A, B> AToB = ;//... big data chunk const map<A, C> AToC = ;//... big data chunk B AsBType() { return AToB.at(data); } //... same for AsCType, etc Data data; } I'm currently concerned with how I can reuse the lookup tables AsBType and AsCType between the multiple A classes that I will create, like so: vector<A> vec; for (i=0;i<100;i++) { vec.push_back({SomeData}); } //Then I am able to do this: B foo = vec[bar].AsBType(); From my knowledge, this approach will store a copy of the large maps into each A object, which I don't want. In other words, how can I use some large data in a commonly used class so that I don't use up memory(by creating redundant maps)? I've thought of the following approahes: Make the maps global and make A reference the global object. const map<A,B> AToB = ; //... class A { Data data; public: B AsBType() { return AToB.at(data); } //... } I don't prefer this method, since it makes the map global when I only want A to access it. Make a translation singleton object to convert between the types. class A { Data data; public: Data GetData() { return data; } } class ATranslator { const map<A,B> AToB = ; //... B AsBType(A a) { return AToB.at(a.GetData()); } } However this singleton will have to be passed around everywhere. Perhaps putting the instanated tranlsator object in the global spoce works, but I haven't tried that yet.
When you want a single object shared by all instances of a class, make it a static data member: class A { static const map<A, B> AToB = ;//... big data chunk static const map<A, C> AToC = ;//... big data chunk //... };
74,651,912
74,652,057
Error C4430 missing type specifier - int assumed. C++ does not support default-int
I'm getting an missing type specifier error for line 12 ( inline CUserCmd*cmd = nullptr;) for this code and all the answers i can find are about functions but this is an inline variable so I'm rather confused. #pragma once #include "../core/interfaces.h" class CEntity; namespace globals { inline CEntity* localPlayer = nullptr; // update the local player pointer void UpdateLocalPlayer() noexcept; inline CUserCmd*cmd = nullptr; inline bool sendPacket; } Additionally I'm getting this syntax error "Error C2143 syntax error: missing ; before *" (also for line 12) which i don't understand as when i add it (CUserCmd ; *cmd) i get another error I'm guessing this is caused by the first error but i don't really know. As stated earlier I tried looking through various stack overflow questions and wikis but all the stuff i can find is about functions which isn't exactly helpful.
You haven't provided a complete program, but I suspect that's part of the problem. The two errors you mention both point to the compiler being unable to find a definition for CUserCmd. If that's included in a header, make sure you #include it.
74,652,016
74,652,647
How to use uiohook library in CMake project?
I am trying to install the following C library: https://github.com/kwhat/libuiohook I did the described steps which seem to work with no error. $ git clone https://github.com/kwhat/libuiohook $ cd uiohook $ mkdir build && cd build $ cmake -S .. -D BUILD_SHARED_LIBS=ON -D BUILD_DEMO=ON -DCMAKE_INSTALL_PREFIX=../dist $ cmake --build . --parallel 2 --target install The problem is I don't know what to do next. I tried to copy the code from the simple hook example and tried to execute the code in a different executable with the following CMakeLists.txt. cmake_minimum_required(VERSION 3.20) project(libuihook_test) include_directories("/Users/ahoehne/libuiohook/dist/include") find_library(lib uiohook) if(NOT lib) message(FATAL_ERROR "uiohook library not found") endif() set(CMAKE_CXX_STANDARD 17) add_executable(libuihook_test main.cpp) target_link_libraries(libuihook_test lib) which doesn't work and results in a CMake Error at CMakeLists.txt:9 (message): uiohook library not found the log from installing is the following: [ 14%] Building C object CMakeFiles/uiohook.dir/src/darwin/input_helper.c.o [ 14%] Building C object CMakeFiles/uiohook.dir/src/logger.c.o [ 21%] Building C object CMakeFiles/uiohook.dir/src/darwin/input_hook.c.o [ 28%] Building C object CMakeFiles/uiohook.dir/src/darwin/post_event.c.o [ 35%] Building C object CMakeFiles/uiohook.dir/src/darwin/system_properties.c.o [ 42%] Linking C shared library libuiohook.dylib [ 42%] Built target uiohook [ 57%] Building C object CMakeFiles/demo_post.dir/demo/demo_post.c.o [ 57%] Building C object CMakeFiles/demo_properties.dir/demo/demo_properties.c.o [ 71%] Linking C executable demo_properties [ 71%] Linking C executable demo_post [ 71%] Built target demo_post [ 71%] Built target demo_properties [ 78%] Building C object CMakeFiles/demo_hook.dir/demo/demo_hook.c.o [ 85%] Building C object CMakeFiles/demo_hook_async.dir/demo/demo_hook_async.c.o [ 92%] Linking C executable demo_hook [100%] Linking C executable demo_hook_async [100%] Built target demo_hook [100%] Built target demo_hook_async Install the project... -- Install configuration: "" -- Installing: /Users/ahoehne/libuiohook/dist/lib/libuiohook.1.2.0.dylib -- Up-to-date: /Users/ahoehne/libuiohook/dist/lib/libuiohook.1.dylib -- Up-to-date: /Users/ahoehne/libuiohook/dist/lib/libuiohook.dylib -- Up-to-date: /Users/ahoehne/libuiohook/dist/include/uiohook.h -- Installing: /Users/ahoehne/libuiohook/dist/lib/cmake/uiohook/uiohook-config.cmake -- Installing: /Users/ahoehne/libuiohook/dist/lib/cmake/uiohook/uiohook-config-noconfig.cmake -- Installing: /Users/ahoehne/libuiohook/dist/bin/demo_hook -- Installing: /Users/ahoehne/libuiohook/dist/bin/demo_hook_async -- Installing: /Users/ahoehne/libuiohook/dist/bin/demo_post -- Installing: /Users/ahoehne/libuiohook/dist/bin/demo_properties -- Installing: /Users/ahoehne/libuiohook/dist/lib/pkgconfig/uiohook.pc I consulted the CMAKE Docs but honestly right now confuses me more than it helps. I am sure at some point I will have an aha moment and connect the dots. Most tutorials do an excellent job of explaining you C/C++ but they all lack the more advanced stuff around build tools, testing, debugging, and so on, everything you basically need to build more complex projects. So I am also grateful for book/video suggestions. I also tried different combinations of include_directories, add, link library also an absolute path but nothing seems to work and I get a library not found error or uiohook.h not found. I am well aware that C and C++ are completely different languages and different practices apply I am not sure If I could have fixed this question to one. But basically try to learn C++ but need to access a lot of C libs.
As the library provides a uiohook-config.cmake you should use that to link to the library via find_package rather than using find_library. Something like this should work: set(CMAKE_PREFIX_PATH /Users/ahoehne/libuiohook/dist/lib/cmake/uiohook/) find_package(uiohook REQURIED) target_link_libraries(libuihook_test uiohook)
74,652,242
74,652,495
std::function argument to receives any number of arguments
I've defined a template function that receives std::function. and I want to send a member function. that works fine (example: test2) How can I rewrite it so std::function receives any number of argument? (test3) another question - can this be done without the std::bind? struct Cls { int foo() { return 11; } }; template<typename T> void test2(std::function<T()> func) {} template<typename T, typename... Args> void test3(std::function<T(Args... args)> func, Args&&... args) {} int main() { Cls ccc; test2<int>(std::bind(&Cls::foo, ccc)); // Ok test3<int>(std::bind(&Cls::foo, ccc)); // does not compile! } This is the error I receive: no matching function for call to ‘test3<int>(std::_Bind_helper<false, int (Cls::*)(), Cls&>::type)’ 34 | test3<int>(std::bind(&Cls::foo, ccc));
The issue is that std::bind doesn't return a std::function, it returns some unspecified callable type. Therefore the compiler can't deduce the correct template parameters for test3. The way to work around that is to make your function accept any callable type instead of trying to accept a std::function: template <typename Func, typename... Args> void test3(Func&& func, Args&&... args) {} This will work with a std::bind result, a lambda, a raw function pointer, a std::function, etc. can this be done without the std::bind? Sort of. A pointer to a member function always requires an instance of the class to be called on. You can avoid needing to explicitly std::bind the instance into a wrapper by passing it as a parameter and using the std::invoke helper to call the function. For pointers to member functions, std::invoke treats the first parameter as the object to call the member on. For example: struct Cls { int foo() { return 11; } }; template <typename Func, typename... Args> void test3(Func&& func, Args&&... args) { std::invoke(std::forward<Func>(func), std::forward<Args>(args)...); } void bar(double, int) {} int main() { Cls ccc; test3(bar, 3.14, 42); // Works with a raw function pointer test3(&Cls::foo, ccc); // Works with a pointer to member function test3([](int){}, 42); // Works with other callable types, like a lambda } Demo
74,652,634
74,652,741
how to sort a vector of string and integer pairs by the second key value which is integer?
I have a vector storing the most frequent words in a file. Initially the values was stored in a map of strings and integers but then I copied the map into the vector I thought it would be easier to sort. Then I realized that the std sort() function sorts the vector by the first key (string in this case). But I want to sort it such that the most used words at the top and the least used at the bottom. #include <iostream> #include <fstream> #include <map> #include <algorithm> #include <vector> #include <iterator> using namespace std; int main(){ fstream fs; fs.open("/Users/brah79/Downloads/skola/c++/codeTest/test.txt"); string word; map <string, int> list; while(fs >> word){ if(list.find(word) != list.end()){ list[word]++; } else{ list[word] = 1; } } vector <pair <string, int> > vector(list.begin(), list.end()); sort(vector.begin(), vector.end() greater<int>()); for(int i = 0; i < vector.size(); i++){ if(vector[i].second == 1){ cout << vector[i].first << " is repeated " << vector[i].second << " time" << endl; } else{ cout << vector[i].first << " is repeated " << vector[i].second << " times" << endl; } } return 0; }
First of all, as mentioned in a comment, this is too complicated: if(list.find(word) != list.end()){ list[word]++; } else{ list[word] = 1; } It looks up the key word twice, when it has to be looked up only once, because this does the same: list[word]++; operator[] already does add a default constructed element if none exists in the map. Then I see no reason to store the item you want to have sorted as first rather than second: std::vector<std::pair<int,std::string> v; // dont use same name for type and variable for (const auto& e : list) { // with using namespace std there is no way to distinguish this from std::list :( v.emplace_back( e.second , e.first ); } Now you can use std::sort with std::greater. Alternatively, keep the pairs as they are and write a custom comparator that compares std::pair(second,first).
74,652,952
74,653,283
Alias within a class template
For following class template<typename T> class test { public: using unit = std::micro; }; How do I access unit like test::unit without having to specify the template argument or make it a template alias. Please note that inserting a dummy template argument like e.g . int is not an option since some template classes cannot be instantiated with such types.
First, it is important to understand that really everything in the template depends on the template parameter T. Even if it looks like it does not on first sight. Consider that there can be a specialization: template <> struct foo< bar > {}; Now there is a foo instantiation that has no member alias. And thats the reason why foo::unit cannot work the way you wish. Please note that inserting a dummy template argument like e.g . int is not an option since some template classes cannot be instantiated with such types. I don't understand this argument. If there is a different class template (there are no template classes, they are called class templates) which cannot be instantiated with int then choose a different default. You need not use the same default for all. However, as discussed above the approach with using a default argument and then refering to the alias via foo<>::unit is flawed anyhow. The simple solution is to not have the alias as member: using unit = std::micro; template<typename T> class test { }; On the other hand, if it should be part of the class, it can be moved to a non-template base class: struct base { using unit = std::micro; } template <typename T> struct test : base {};
74,654,454
74,654,631
Change the comparator for a map that is defined by a variadic template
I have the following piece of code, // Type your code here, or load an example. #include <string> #include <map> #include <iostream> struct alpha{ alpha() = default; alpha(std::string str, int i ) : mystr(str), num(i){} std::string mystr{"abc"}; int num{0}; bool operator <( const alpha &al ) const { return ( mystr < al.mystr ); } }; struct beta{ beta() = default; beta(std::string str, int i ) : mystr(str), num(i){} std::string mystr{"abc"}; int num{0}; bool operator <( const beta &b1 ) const { return ( mystr < b1.mystr ); } }; template<template<typename ...> class Tcont, typename... Titem> struct label_str { Tcont<Titem...> kindA; }; struct Label_map { label_str<std::map, alpha, beta> al_beta_map; }; struct big_map { Label_map first; Label_map second; }; int main() { auto a1 = alpha("a1", 1); auto a2 = alpha("a2", 2); auto a3 = alpha("a3", 3); auto a4 = alpha("a4", 4); auto a5 = alpha("a5", 5); auto b1 = beta("b1", 1); auto b2 = beta("b2", 2); auto b3 = beta("b3", 3); auto b4 = beta("b4", 4); auto b5 = beta("b5", 5); big_map bigg; auto &first_map = bigg.first; auto &second_map = bigg.second; first_map.al_beta_map.kindA[a5] = b5; first_map.al_beta_map.kindA[a2] = b2; first_map.al_beta_map.kindA[a3] = b3; first_map.al_beta_map.kindA[a4] = b4; first_map.al_beta_map.kindA[a1] = b1; auto &mmmap = first_map.al_beta_map.kindA; for ( auto [p,_] : mmmap ) std::cout << "( " << p.mystr << ", " << p.num << " )" << std::endl; } I want to change the comaparator for alpha and beta to num instead of mystr. I understand that I have to write a custom lambda to compare but I am not sure because of the variadic templates. Assuming I do not have access to change the alpha and beta, how do I do this? godbolt like is here Link
Type of the custom comparator must be passed to std::map as the third argument, you can actually use the variadic label_str to your advantage there: struct num_comparator { template <typename T> bool operator()(const T &l, const T &r) const { return (l.num < r.num); } }; struct Label_map { label_str<std::map, alpha, beta, num_comparator> al_beta_map; }; One could use a lambda but the hassle with it is the lambdas are not default constructible until C++20, meaning just std::map<alpha, beta,decltype(global_lambda)> is not enough, you have to explicitly pass it in the ctor too. That could be done in your case but I see struct simpler. Just note that std::map only ever compares it's keys, alphas in your case. beta::operator< is never used.
74,654,566
74,654,619
Prime number between N and M
So I was trying to get the prime number between two numbers, it works fine but it also prints out odd numbers int prime(int num1, int num2) { int sum{0}; while (num1 <= num2) { for (int i = 1; i <= num1; i++) { if (num1 % i == 0) //remainder needs to be zero { if (num1 % 2 == 0) continue; //continue the loop if the number is even if (i * num1 == num1 && num1 / i == num1) {//make sure it only prints prime numbers cout << num1 << endl; sum += num1; } } } num1++; } return sum; } Console log I tried to make a for loop that iterates between 1 and N and if the remainder is zero it also checks if the number is even.. if it is then it continues the loop. and then i checked for prime numbers.. if (i * num1 == num1 && num1 / i == num1) i expected it to print out only prime numbers and last the sum of them but it also counts odd numbers
This if statement if (i * num1 == num1 && num1 / i == num1) {//make sure it only prints prime numbers cout << num1 << endl; sum += num1; } is always evaluated for any number when i is equal to 1. So the code has a logical error. At least there is no sense to start the for loop for (int i = 1; i <= num1; i++) with i equal to 1. Pay attention to that prime numbers are defined for natural numbers that is for numbers of unsigned integer types. I would write the function at least the following way unsigned long long int sum_of_primes( unsigned int first, unsigned int last ) { unsigned long long int sum = 0; if (not ( last < first )) { do { bool prime = first % 2 == 0 ? first == 2 : first != 1; for (unsigned int i = 3; prime && i <= first / i; i += 2) { prime = first % i != 0; } if (prime) sum += first; } while (first++ != last); } return sum; } For example if in main to write this statement std::cout << "sum_of_primes(0, 10) = " << sum_of_primes( 0, 10 ) << '\n'; then its output will be sum_of_primes(0, 10) = 17 Indeed in this range [0, 10] prime numbers are 2, 3, 5, 7 and their sum is equal to 17.
74,655,092
74,655,349
Function that returns templated object with any template argument type
I have a templated class, say: template <class C, int I> class A { A() {}; someMethod(){...}; }; Now, let's say I have several objects of this class used in my code with different template parameters (classes B,C, and D are some defined classes): A<B, 1> object1; A<C, 2> object2; A<D, 3> object3; What I would like to have is a function that returns one of these three objects based on some logic: A getObject(){ if(condition1) return object1; else if(condition2) return object2; else return object3; } However, when I try to compile this, I get error: invalid use of template-name ‘A’ without an argument list, which makes sense, but I don't know which arguments should I provide? For instance, if I put A<B, 1> getObject(){ return object1; } then I can only return object1, but not object2 or object3. Ultimately, my goal is to have something like: A obj = getObject(); ... lot's of code where obj.someMethod() get's called a lot ...
This is simpler to reason about if you think of A<B,1>, A<B,2> and A<B,3> as three completely unrelated classes Foo, Bar and Moo, which they bascially are. Now try to find a way to return those from a single method: You need a common base or any or variant ... runtime polymorphism: The same method returns an object and you do not care about the type as long as it implements an interface. class A_base { virtual void someMethod() = 0; virtual ~A() {} }; template <class C, int I> class A : public A_base { A() {} void someMethod() override {/*...*/} }; std::unique_ptr<A_base> getObject() { //... } I assumed that condition is only known at runtime. Otherwise the whole quesiton is moot, because if it is know at compile time then you could simply make getObject a template that returns only the one type determined by the condition.
74,655,645
74,656,882
Multiple inheritance ambiguities with minimal code clutter
I have two interfaces: IFace2 derives from IFace class IFace { public: virtual ~IFace() = default; virtual void doit() = 0; }; class IFace2 : public IFace { public: virtual void doit2() = 0; }; I am trying reduce code clutter that is required by the implementations. In IFace2Impl I would like to use the same implementation from IFaceImpl. Unfortunately, that forces me to resolve ambiguity and I need to override every function in IFace2Impl: class IFaceImpl : public IFace { public: void doit() override { } }; class IFace2Impl : public IFaceImpl, IFace2 { public: using IFaceImpl::doit; // not resolving ambiguity void doit2() override { } }; int main() { IFace2Impl impl; } When I try to compile this code, the compiler gives me an error message: <source>(36): error C2259: 'IFace2Impl': cannot instantiate abstract class <source>(24): note: see declaration of 'IFace2Impl' <source>(36): note: due to following members: <source>(36): note: 'void IFace::doit(void)': is abstract <source>(6): note: see declaration of 'IFace::doit' https://godbolt.org/z/91M1j8bv3 For each virtual function I have to provide full definition: class IFace2Impl : public IFaceImpl, IFace2 { public: void doit() { IFaceImpl::doit(); } void doit2() override { } }; Is there a way to handle this more elegantly? When number of interface method grows, the more ambiguities I have to resolve.
Virtual inheriance might help, so IFaceImpl would have only one IFace instead of 2: class IFace { public: virtual ~IFace() = default; virtual void doit() = 0; }; class IFace2 : public virtual IFace { public: virtual void doit2() = 0; }; class IFaceImpl : public virtual IFace { public: void doit() override {} }; class IFace2Impl : public IFaceImpl, public virtual IFace2 // virtual not required here, but would be with IFace3Impl... { public: void doit2() override {} }; Demo
74,655,881
74,656,562
OpenGL Camera Rotation with glm
I'm trying to rotate camera but instead it rotates and changes position. float m_CameraRotation = 30.0f; TShader.Bind(); glm::mat4 proj = glm::ortho(0.0f, 1000.0f, 0.0f, 1000.0f, -1.0f, 1.0f); glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0, 0)); glm::mat4 vp = proj * view; glm::mat4 transform = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)) * glm::rotate(glm::mat4(1.0f), glm::radians(m_CameraRotation), glm::vec3(0, 0, 1)); TShader.UniformSetMat4f("u_ViewProjection", vp); TShader.UniformSetMat4f("u_Transform", transform); Shader gl_Position = u_ViewProjection * u_Transform * vec4(aPos, 1.0); And my triangle coordinates float TriangleVertices[] = { // positions // colors 500.0f, 700.0f, 0.0f, 1.0f, 0.0f, 0.0f, // top 250.0f, 300.0f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom left 750.0f, 300.0f, 0.0f, 0.0f, 0.0f, 1.0f // bottom right }; unsigned int TriangleIndices[] = { 0, 1, 2 }; This is my triangle without rotation. And this is my triangle with m_CameraRotation = 30.0f; What's causing this?
Since your translations don't do anything, the only transformations applied to the triangle's vertices are the rotation first and the orthographic projection second. The rotation axis being +z, it will rotate everything in the xy plane around the origin by m_CameraRotation degrees counterclockwise. Your triangle isn't really translated, it's rotated around the origin. The green vertex for example is at (250, 300) before rotation, and approximately (66.5, 384.8) after. Looking back at your screenshots, this is exactly where I would expect the triangle to be. To rotate the triangle around its center, or around the center of the screen, or around any point P, you need to translate it first by -P, then rotate it, then translate it back by +P. Something like: glm::vec3 center(500.f, 500.f, 0.f); glm::mat4 rotation = glm::rotate(glm::radians(m_CameraRotation), glm::vec3(0, 0, 1)); glm::mat4 transform = glm::translate(center) * rotation * glm::translate(-center); You could also try doing the orthographic projection first and the rotation second. Side note: you don't need the identity matrix as first argument to glm::translate and glm::rotate every time.
74,656,665
74,656,698
Is there a conversion from pointer to array?
For example, for the following code, I know that p is a pointer, which points to the first element of the array arr, and I also know that the array will degenerate into an array under certain conditions, but why can the [] operation be performed on the pointer here? #include<iostream> using namespace std; int main() { int arr[10]; arr[3] = 10; int* p = arr; cout << p[3]; return 0; } Is there any documentation for this? run it online
From the C++ 20 Standard (7.6.1.2 Subscripting) 1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall be a glvalue of type “array of T” or a prvalue of type “pointer to T” and the other shall be a prvalue of unscoped enumeration or integral type. The result is of type “T”. The type “T” shall be a completely-defined object type.62 The expression E1[E2] is identical (by definition) to *((E1)+(E2)), except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise. The expression E1 is sequenced before the expression E2. That is when an array is used in this expression *((E1)+(E2)) then it is converted implicitly to pointer to its first element.
74,656,830
74,666,483
set vcpkg x-buildtrees-root option in manifest or in cmakepresets.json
I've a CMake project that uses vcpkg.json for using vcpkg, and CMakePresets.json for setting the CMake options. This is the vcpkg.json: { "name": "myproj", "version": "1.0.0", "dependencies": [ "boost", "qt" ] } This is the CMakePresets.json: { "version": 3, "cmakeMinimumRequired": { "major": 3, "minor": 22, "patch": 1 }, "configurePresets": [ { "name": "default", "displayName": "Default Config", "description": "Default config generator with ninja", "generator": "Ninja", "binaryDir": "${sourceDir}/build/${presetName}", "hidden": true, "cacheVariables": { "CMAKE_TOOLCHAIN_FILE": "e:/lib/vcpkg/scripts/buildsystems/vcpkg.cmake", "VCPKG_DEFAULT_TRIPLET": "x64-windows", "CMAKE_EXPORT_COMPILE_COMMANDS": "TRUE" }, "environment": { } }, { "inherits": "default", "name": "debug", "displayName": "Debug", "description": "Debug build.", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } }, { "inherits": "default", "name": "release", "displayName": "Release", "description": "Release build.", "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } } ], "buildPresets": [ { "name": "Debug", "configurePreset": "debug" }, { "name": "Release", "configurePreset": "release" } ], "testPresets": [ { "name": "debugtest", "configurePreset": "debug", "output": {"outputOnFailure": true}, "execution": {"noTestsAction": "error", "stopOnFailure": true} } ] } When I open the project folder with Visual Studio 2022, it start to build the vcpkg libraries, and everything goes well, until it builds qtwebengine, that returns me an error: 1> [CMake] Installing 376/432 qtwebengine:x64-windows... 1> [CMake] Building qtwebengine[core,default-features,geolocation,spellchecker,webchannel]:x64-windows... 1> [CMake] -- Using cached pypa-get-pip-38e54e5de07c66e875c11a1ebbdb938854625dd8.tar.gz. 1> [CMake] -- Cleaning sources at E:/lib/vcpkg/buildtrees/qtwebengine/src/8854625dd8-861bd167bd.clean. Use --editable to skip cleaning for the packages you specify. 1> [CMake] -- Extracting source E:/lib/vcpkg/downloads/pypa-get-pip-38e54e5de07c66e875c11a1ebbdb938854625dd8.tar.gz 1> [CMake] -- Using source at E:/lib/vcpkg/buildtrees/qtwebengine/src/8854625dd8-861bd167bd.clean 1> [CMake] -- Setting up python virtual environmnent... 1> [CMake] -- Installing python packages: html5lib 1> [CMake] -- Setting up python virtual environmnent...finished. 1> [CMake] CMake Warning at ports/qtwebengine/portfile.cmake:85 (message): 1> [CMake] Buildtree path 'E:/lib/vcpkg/buildtrees/qtwebengine' is too long. 1> [CMake] 1> [CMake] Consider passing --x-buildtrees-root=<shortpath> to vcpkg! 1> [CMake] 1> [CMake] Trying to use 'E:/lib/vcpkg/buildtrees/qtwebengine/../tmp' 1> [CMake] Call Stack (most recent call first): 1> [CMake] scripts/ports.cmake:147 (include) 1> [CMake] 1> [CMake] 1> [CMake] CMake Error at ports/qtwebengine/portfile.cmake:90 (message): 1> [CMake] Buildtree path is too long. Build will fail! Pass 1> [CMake] --x-buildtrees-root=<shortpath> to vcpkg! 1> [CMake] Call Stack (most recent call first): 1> [CMake] scripts/ports.cmake:147 (include) 1> [CMake] error: building qtwebengine:x64-windows failed with: BUILD_FAILED 1> [CMake] error: Please ensure you're using the latest port files with `git pull` and `vcpkg update`. Basically I need to set the --x-buildtrees-root=<shortpath> option when building the library with vcpkg. I can do it manually, but how can I set this option in order to be called automatically when I build the dependencies with Visual Studio? How can I update my configuration files?
The variable VCPKG_INSTALL_OPTIONS is meant for passing further options to vcpkg install. So just set it in your preset.
74,657,257
74,657,501
C++ unordered set of custom class - segfault on insert
I am following a tutorial on creating a hexagon map for a game. The source has it in struct, but I want it to be a class and so far I am unable to make it work. It compiles fine, but when I try to insert a new value in it, it segfaults. I am probably doing the hash function wrong, or something, but I have ran out of ideas on fixing it. Thanks! main.c #include <unordered_set> #include "hexagonField.hpp" int main(int argc, char **argv) { std::unordered_set <HexagonField> map; map.insert(HexagonField(0, 0, 0)); return 0; } hexagonField.hpp #ifndef HEXAGON_H #define HEXAGON_H #include <assert.h> #include <vector> class HexagonField { public: const int q, r, s; HexagonField(int q, int r, int s); ~HexagonField(); HexagonField hexagonAdd(HexagonField a, HexagonField b); HexagonField hexagonSubtract(HexagonField a, HexagonField b); HexagonField hexagonMultiply(HexagonField a, int k); int hexagonLength(HexagonField hex); int hexagonDistance(HexagonField a, HexagonField b); HexagonField hexagonDirection(int direction /* 0 to 5 */); HexagonField hexagonNeighbor(HexagonField hex, int direction); const std::vector<HexagonField> hexagonDirections = { HexagonField(1, 0, -1), HexagonField(1, -1, 0), HexagonField(0, -1, 1), HexagonField(-1, 0, 1), HexagonField(-1, 1, 0), HexagonField(0, 1, -1) }; bool operator == (const HexagonField comparedHex) const { return this->q == comparedHex.q && this->r == comparedHex.r && this->s == comparedHex.s; } bool operator != (const HexagonField comparedHex) const { return !(*this == comparedHex); }; }; namespace std { template<> struct hash<HexagonField> { size_t operator()(const HexagonField & obj) const { return hash<int>()(obj.q); } }; } #endif hexagonField.cpp #include "hexagonField.hpp" HexagonField::HexagonField(int q, int r, int s): q(q), r(r), s(s) { assert (q + r + s == 0); } HexagonField HexagonField::hexagonAdd(HexagonField a, HexagonField b) { return HexagonField(a.q + b.q, a.r + b.r, a.s + b.s); } HexagonField HexagonField::hexagonSubtract(HexagonField a, HexagonField b) { return HexagonField(a.q - b.q, a.r - b.r, a.s - b.s); } HexagonField HexagonField::hexagonMultiply(HexagonField a, int k) { return HexagonField(a.q * k, a.r * k, a.s * k); } int HexagonField::hexagonLength(HexagonField hex) { return int((abs(hex.q) + abs(hex.r) + abs(hex.s)) / 2); } int HexagonField::hexagonDistance(HexagonField a, HexagonField b) { return hexagonLength( hexagonSubtract(a, b)); } HexagonField HexagonField::hexagonDirection(int direction /* 0 to 5 */) { assert (0 <= direction && direction < 6); return hexagonDirections[direction]; } HexagonField HexagonField::hexagonNeighbor(HexagonField hex, int direction) { return hexagonAdd(hex, hexagonDirection(direction)); }
If you run your program under a debugger, you will see it actually overflowed the stack while trying to construct HexagonField objects. This is because every object has a vector of 6 more HexagonField objects, which in turn needs another vector, and so on. As a quick fix, you can take hexagonDirections out of the HexagonField class and move it to a static file-scoped variable at the top of HexagonField.cpp instead: static const std::vector<HexagonField> hexagonDirections = { HexagonField(1, 0, -1), HexagonField(1, -1, 0), HexagonField(0, -1, 1), HexagonField(-1, 0, 1), HexagonField(-1, 1, 0), HexagonField(0, 1, -1) }; Alternatively, you can leave hexagonDirections as a static class member and move the definition to your .cpp file: // HexagonField.h class HexagonField { ... static const std::vector<HexagonField> hexagonDirections; ... }; // HexagonField.cpp const std::vector<HexagonField> HexagonField::hexagonDirections = { HexagonField(1, 0, -1), HexagonField(1, -1, 0), HexagonField(0, -1, 1), HexagonField(-1, 0, 1), HexagonField(-1, 1, 0), HexagonField(0, 1, -1) };
74,657,605
74,658,314
What mechanism can I use for an optional function parameter that gets a value assigned if not provided?
In Python I can do something like: def add_postfix(name: str, postfix: str = None): if base is None: postfix = some_computation_based_on_name(name) return name + postfix So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for postfix. It needs to be calculated. (which is why I can't just have a default value). In C++ I reached for std::optional and tried: std::string add_postfix(const std::string& name, std::optional<const std::string&> postfix) { if (!postfix.has_value()) { postfix.emplace("2") }; return name + postfix; } I'm now aware that this won't work because std::optional<T&> is not a thing in C++. I'm fine with that. But now what mechanism should I use to achieve the following: Maintain the benefits of const T&: no copy and don't modify the original. Don't have to make some other postfix_ so that I have the optional one and the final one. Don't have to overload. Have multiple of these optional parameters in one function signature.
One possibility is to use a std::string const* (a non-constant pointer to a const std::string) as a function argument. std::string add_postfix(const std::string& name, std::string const* postfix = nullptr) { std::string derivedSuffix; if(!postfix) { derivedSuffix = some_computation(name); postfix = &derivedSuffix; } return name + *postfix; } Some care is required with the details here. derivedSuffix needs to be an object that lasts at least as long as the pointer postfix refers to it. Therefore it cannot be contained entirely within the if(!postfix) block, because if it did then using *postfix outside of it would be invalid. There's technically still a bit of overhead here where we create an empty std::string even when postfix isn't nullptr, but we never have to make a copy of a std::string with actual values in it.
74,659,156
74,659,822
Is there a way to use a using-declaration inside a requires-expression
I want to test whether a type can be passed to some function, but I'd like to use ADL on the function lookup and include a function from a certain namespace. Consider this code: #include <utility> #include <vector> template<class T> concept Swappable = requires(T& a, T& b) { swap(a,b); }; static_assert(Swappable<std::vector<int>>); // #1 static_assert(Swappable<int>); // #2 #1 succeeds, it finds std::swap because std is an associated namespace of std::vector<int>. But #2 fails, a built-in type has no associated namespace. How would I write something like: template<class T> concept Swappable = requires(T& a, T& b) { using std::swap; // illegal swap(a,b); }; AFAIK, you're not allowed to use a using-declaration inside a requires-expression. (NOTE Although there is a perfectly fine standard C++ concept for this, std::swappable, this example uses swap for exposition only. I'm not particularly looking to test whether something is actually swappable, I'm just trying to find a way to implement such a concept where a customization function has a default implementation in a known namespace, but might have overloads in an associated namespace.) EDIT As a workaround, I can implement the concept in a separate namespace where the names are pulled in. Not too happy about it but it works. namespace detail { using std::swap; template<class T> concept Swappable = requires(T& a, T& b) { swap(a,b); }; } // and then either use it using detail::Swappable; // or redefine it template<class T> concept Swappable = detail::Swappable<T>;
You can put it inside a lambda: template<class T> concept Swappable = []{ using std::swap; return requires(T& a, T& b) { swap(a, b); }; }();
74,660,389
74,668,554
Freetype2 not linking on Windows correctly
I've been fighting freetype2 for a week trying to get it to work on Windows 32 bit but it just won't. My CMakeLists.txt is as follows: cmake_minimum_required(VERSION 3.0.0) set(CMAKE_CXX_STANDARD 17) project(template-project) # change the name here file(GLOB_RECURSE SOURCE_FILES src/*.cpp) add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES}) list(APPEND CMAKE_PREFIX_PATH "D:/Installs/ProgFiles/glew") find_package( OpenGL REQUIRED ) include_directories( ${OPENGL_INCLUDE_DIRS} ) # this is so stupid set(CMAKE_SIZEOF_VOID_P 4) if (${CMAKE_CXX_COMPILER_ID} STREQUAL Clang) # ensure 32 bit on clang set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -target i386-pc-windows-msvc") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -target i386-pc-windows-msvc") add_definitions("--target=i386-pc-windows-msvc") endif() set(FT_DISABLE_HARFBUZZ TRUE) target_include_directories(${PROJECT_NAME} PRIVATE libraries/minhook/include libraries/gd.h/include libraries/gd.h/ libraries/imgui libraries/glad/include libraries/stb libraries/freetype2/include ) add_subdirectory(libraries/minhook) add_subdirectory(libraries/cocos-headers) add_subdirectory(libraries/glfw) add_subdirectory(libraries/glm) add_subdirectory(libraries/freetype2) target_link_libraries( ${PROJECT_NAME} ${OPENGL_LIBRARIES} glfw ) if( MSVC ) if(${CMAKE_VERSION} VERSION_LESS "3.6.0") message( "\n\t[ WARNING ]\n\n\tCMake version lower than 3.6.\n\n\t - Please update CMake and rerun; OR\n\t - Manually set 'GLFW-CMake-starter' as StartUp Project in Visual Studio.\n" ) else() set_property( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT GLFW-CMake-starter ) endif() endif() target_link_libraries(${PROJECT_NAME} opengl32.lib minhook cocos2d rpcrt4.lib glm ${PROJECT_SOURCE_DIR}/libraries/freetype2/objs/Win32/Release/freetype.lib) The biggest issue in the output are these lines: [cmake] -- Could NOT find PkgConfig (missing: PKG_CONFIG_EXECUTABLE) [cmake] -- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR) [cmake] -- Could NOT find PNG (missing: PNG_LIBRARY PNG_PNG_INCLUDE_DIR) [cmake] -- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR) [cmake] -- Could NOT find BZip2 (missing: BZIP2_LIBRARIES BZIP2_INCLUDE_DIR) [cmake] -- Could NOT find BrotliDec (missing: BROTLIDEC_INCLUDE_DIRS BROTLIDEC_LIBRARIES) I am on windows and completely unsure how to fix these. I've tried installing zlib via mingw32, and I've tried linking it the same way I do things like minhook and glad to no avail.
I recommend a different approach than manual downloading of opensource dependencies when using MinGW. Instead of searching for individual binary downloads switch to use msys2 to install MinGW and use the package management of msys2 to all of your dependent open source libraries. The first step is to remove your current MinGW install so you have no conflicting / possibly incompatible MinGW dlls in your PATH that may cause you problems in the future when executing your programs. After that install msys2: How to install MinGW-w64 and MSYS2? Then to install your dependencies for 32 bit open the mingw32 terminal which by default is installed in "C:\msys64\mingw32.exe" and use the package manager of msys2 pacman to install the dependent packages. The web page for msys2 has a convenient package search feature at the top center of this page: https://packages.msys2.org/queue Lets start with zlib from your dependencies. Type in zlib in the search box and press search. Type mingw-w64-zlib then look for i686 packages for mingw to find the correct package for 32 bit mingw. I found the following link for zlib for mingw32 has the following page: https://packages.msys2.org/package/mingw-w64-i686-zlib?repo=mingw32 The install instructions for that are listed in the center of the page: pacman -S mingw-w64-i686-zlib so copy this command to the mingw32 terminal: JMDLAPTOP1+dresc@JMDLAPTOP1 MINGW32 ~ # pacman -S mingw-w64-i686-zlib resolving dependencies... looking for conflicting packages... Packages (1) mingw-w64-i686-zlib-1.2.13-2 Total Download Size: 0.10 MiB Total Installed Size: 0.39 MiB :: Proceed with installation? [Y/n] Press Y to install this package. :: Proceed with installation? [Y/n] y :: Retrieving packages... mingw-w64-i686-zlib-1.2.13... 102.8 KiB 126 KiB/s 00:01 [###############################] 100% (1/1) checking keys in keyring [###############################] 100% (1/1) checking package integrity [###############################] 100% (1/1) loading package files [###############################] 100% (1/1) checking for file conflicts [###############################] 100% (1/1) checking available disk space [###############################] 100% :: Processing package changes... (1/1) installing mingw-w64-i686-zlib [###############################] 100% JMDLAPTOP1+dresc@JMDLAPTOP1 MINGW32 ~ Continue a similar process for the other dependent packages.
74,660,413
74,660,518
Multiplication Table Based On BOTH User Inputs
I am trying to create a multiplication table that is based on BOTH user inputs. I want to ask the user the first and second integer and then to print out the first integer by the second integer that amount of times. For example, if I choose 5 for first integer and 10 for second integer, I want the results printed as such: 5 x 1 = 5 5 x 2 = 10 and so forth... I do not know whether I should be using for loops or an array for this type of program. I am about 15 weeks of learning C++. When I execute the code, nothing happens in the executable. Here is the code: cout<<" Multiplication Table"<<endl; cout<<"----------------------"<<endl; cout<<" Input a number: "; cin>>multiplyNumber; cout<<"Print the multiplication table of a number up to: "; cin>>multiply2Number; for (int a = multiplyNumber; a < multiply2Number; a++){ for (int b = multiply2Number; b < multiply2Number; b++){ cout<<a<<" X "<<" = "<<endl; }
You don't see the numbers being outputted because your inner for loop is never entered, as b (which has the value of multiply2Number) can never be less than multiply2Number. Do you want the second number to be the number of entries to display, starting at x 1 and progressing sequentially? If so, then try something like this: cout << " Multiplication Table" << endl; cout << "----------------------" << endl; cout << " Input a number: "; cin >> number; cout << "Print the multiplication table of a number up to: "; cin >> lastMultiplier; for (int multiplier = 1; multiplier <= lastMultiplier; ++a){ cout << number << " X " << multiplier << " = " << (number * multiplier) << endl; } Online Demo Or, do you want the second number to be the highest multiplied value to stop at, and you want to display however many entries is required to reach that value? If so, then try something like this instead: cout << " Multiplication Table" << endl; cout << "----------------------" << endl; cout << " Input a number: "; cin >> number; cout << "Print the multiplication table of a number up to: "; cin >> lastResult; for (int multiplier = 1, result = number; result <= lastResult; result = number * ++multiplier){ cout << number << " X " << multiplier << " = " << result << endl; } Online Demo
74,660,477
74,660,637
How to use a library created using Bazel
I'm relatively new to Cpp and I was trying to build a simple app for a quant project. I've managed to use Bazel to convert a chunk of my code to a library residing in the bazel-bin directory in my repository as a .lib file. However, I'm not able to figure out how to use this library in my main.cpp which is outside the library I created. Could anyone help with this? Thanks!
I'm not sure if I understood your question correctly, but I think, there is a .lib file that you want to use it (technically speaking, you need to link that .lib file to another app, or accessing in the main.cpp). Ok, it depends on what build-system you use. for MSVC: Add the full path of the .lib file to Project Property Page -> Linker -> Input -> Additional Dependencies. and don't forget to add the path to .h files (include path) to Project Property Page -> C/C++ -> General -> Additional Include Directories It's the same for other build systems, you have to link it to the final built item. for gcc there is a -L flag for the lib and a -h flag to point to the include directories. in CMake: include_directories( path/to/include/directory ) link_directories( path/to/directory/that/lib/lives ) add_executable(main main.cpp) target_link_libraries(main lib_file_name) if the lib file name is lib_file_name.lib you should not include .lib (just for cmake)