question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,791,394
73,791,549
Cannot initialize a std::vector of objects when class contains std::thread
I'm running into an error with a more complicated class structure which I have boiled down to the below simple test case. The actual intent is to use a ctor with parameters, but the error occurs even when explicitly calling the empty ctor. class TestFun{ public: explicit TestFun(const std::function<void()>& fun) : m_thread(fun) {} ~TestFun() {m_thread.join();} private: std::thread m_thread; }; class Test : public TestFun{ public: Test() : TestFun( [this](){std::cout << "test\n";}) {} }; std::vector<Test> tests(10); // This compiles std::vector<Test> tests(10, Test()); // This gives an error The error is: /usr/include/c++/11/bits/stl_uninitialized.h:288:63: error: static assertion failed: result type must be constructible from input type What's going on here?
As stated in documentation on std::vector constructor on this line: std::vector<Test> tests(10); // This compiles you use Constructs the container with count default-inserted instances of T. No copies are made. on another side on this line: std::vector<Test> tests(10, Test()); // This gives an error you try to use another variant: Constructs the container with count copies of elements with value value. As std::thread is not copy constructible it implicitly deletes default copy constructor of you class, so this variant does not compile. From std::thread documentation No two std::thread objects may represent the same thread of execution; std::thread is not CopyConstructible or CopyAssignable, although it is MoveConstructible and MoveAssignable.
73,791,436
73,829,034
Are concepts able to check private non-static data members?
I made a concept that checks the type of a data member: #include <concepts> #include <iostream> template < typename DataType > struct StaticA { private: static DataType value; }; template < typename DataType > struct NonStaticA { private: DataType value; }; template < typename DataType > struct B { DataType value; }; template < typename Class > concept Concept = std::same_as < decltype(Class::value), int >; int main() { std::cout << Concept < StaticA < int > > << "\n"; // Prints 0 std::cout << Concept < NonStaticA < int > > << "\n"; // Prints 0 or 1, depending on the compiler. std::cout << Concept < B < int > > << "\n"; // Prints 1 return 0; } In this case, the second print should also be 0 on MSVC, just like it happens on gcc, right? I believe that's the case, because of this answer: C++ concept with friend-like access You may check the aforementioned code here: https://godbolt.org/z/9afcEes7x Thanks for your attention!
It seems that this issue was indeed a bug: https://developercommunity.visualstudio.com/t/C-concepts-are-able-to-access-private-/10155281 The fix shall be released in the future.
73,791,478
73,793,388
Cast pointer to union to known base class of unknown active member
Suppose I have a union and I know the active member derives from some (non-standard layout) base class, but I don't know which specific member is active. Is it legal to cast a pointer to that union, via void *, to a pointer to the base class, then use that base pointer? For example, is this (which does compile with g++ 11.3.0 with -std=c++23) legitimate? class base { public: virtual bool foo() = 0; }; class derived_1 : public base { bool foo() override { return true; }; }; class derived_2 : public base { bool foo() override { return false; }; }; union some_base { derived_1 x; derived_2 y; bool foo() { return static_cast<base *>(static_cast<void *>(this))->foo(); }; };
The union object that this points to is pointer-interconvertible with the active derived_1 or derived_2, but it is not pointer-interconvertible with the base class subobject of either. Pointer-interconvertibility between base and derived classes applies only to standard layout classes. Therefore the cast will not result in a pointer to the base class subobject and the member access will have undefined behavior as the actual type of the pointed-to object is not similar to that of the expression. The layout of the classes is not relevant to this. It is more similar to an aliasing violation. However, even regarding layout, there is nothing requiring the implementation to place the Base subobject at zero offset (or at equal offsets at all) into derived_1 and derived_2. The ABI specification will make a determination regarding the last point though. Then assuming that the layout is appropriate, it may very well work in practice. I am not sure whether or to what degree compilers use this aliasing-type violation for optimization in practice.
73,791,559
73,817,231
window fails to initiate when specifying a custom class name registered with RegisterClass to CreateWindowEx but only the second time I do it
I'm creating a window that's supposed to contain buttons. When I create the first window (the container) I use a WNDCLASS to specify a WindowProc callback function to lpfnWndProc and it works as intended. When I do it the second time with a window, specifying a callback used to detect when the button is clicked, it doesn't work; the CreateWindowEx call there returns NULL (comment below shows where). When I don't create WNDCLAS wB below and specify some other valid lpClassName to CreateWindowEx instead, such as Button it works fine. code used #pragma comment(linker, "/entry:wWinMainCRTStartup") #include <windows.h> #include <iostream> HWND button; LRESULT CALLBACK ButtonWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) { WNDCLASS wc = {}; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszClassName = L"textedit"; RegisterClass(&wc); HWND hwnd = CreateWindowEx( 0, wc.lpszClassName, L"textedit", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 340, 240, NULL, NULL, hInstance, NULL); if (hwnd == NULL) { return 0; } HWND hWndEdit = CreateWindowEx(WS_EX_CONTROLPARENT, L"Edit", L"id here", WS_BORDER | WS_CHILD | WS_VISIBLE, 94, 20, 140, 40, hwnd, NULL, NULL, NULL); // if I leave wcB unused/remove it and // specify L"Button" as the lpClassName to CreateWindowEx below, the button displays WNDCLASS wcB = {}; wcB.lpfnWndProc = ButtonWindowProc; wcB.hInstance = hInstance; wcB.lpszClassName = L"modify"; RegisterClass(&wcB); ShowWindow(hwnd, nCmdShow); // doing the exact same thing I did when creating the first window // but it fails to create the window HWND hButton = CreateWindowEx(0L, L"modify", L"modify", BS_FLAT | WS_VISIBLE | WS_CHILD, 94, 70, 140, 50, hwnd, NULL, hInstance, NULL); ShowWindow(hButton, nCmdShow); // here hButton is NULL <---------------------- if (hButton == NULL) { return 0; } MSG msg = {}; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } LRESULT CALLBACK ButtonWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_DESTROY: PostQuitMessage(0); return 0; case BN_CLICKED: std::cout << "clicked"; case WM_PAINT: PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1)); EndPaint(hwnd, &ps); return 0; } return 0; return DefWindowProc(hwnd, uMsg, wParam, lParam); }; LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_DESTROY: PostQuitMessage(0); return 0; case WM_PAINT: PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1)); EndPaint(hwnd, &ps); return 0; } return DefWindowProc(hwnd, uMsg, wParam, lParam); } GetLastError() returns 1400, but I don't understand how the handle hwnd could possible be invalid because as I mentioned before, when I just change the lpClassName I pass to CreateWindowEx, it works without errors. I would appreciate any help in finding out why the window (the HWND of which is hButton) does not initiate, and possible workarounds.
The solution to the problem in the title was solved by the comment by Igor Tandetnik: ButtonWindowProc returns 0 for all messages it doesn't handle, and doesn't pass them to DefWindowProc. In particular, it returns 0 in response to WM_NCCREATE, which is a signal that the window creation has failed. You probably didn't mean to put return 0; right before return DefWindowProc(...); After fixing that, the window was created but was invisible. To fix that I used FillRect with a valid brush handle SetDCBrushColor(hdc, bkcolor); SetBkColor(hdc, RGB(187, 189, 189)); FillRect(hdc, &ps.rcPaint, (HBRUSH)GetStockObject(DC_BRUSH)); To detect left mouse button clicks you need to check for the WM_LBUTTONDOWN message.
73,791,938
73,792,107
Why can I not push_back a element into a vector pointer?
My code is the following: #include <vector> int main() { std::vector<int> *vec; vec->push_back(1); return 0; } This program segfaults, no matter which compiler I try it with. I also tried using a smart pointer, but it also segfaults. I now have two questions: Why and how can I solve this? Does having a pointer to a vector (specifically a smart pointer) even make sense? In my online searches, I only saw it the other way around, a vector of unique_ptr's. Which makes more sense and why?
Pointers are trivial objects, so the result of default-initializing one is that its value is indeterminant. Since that's what you did, your pointer doesn't point to anything. That means trying to access the thing it points to results in undefined behavior. You need to create an object for your pointer to point to. For instance, you could dynamically-allocate a new std::vector<int>: std::vector<int>* vec = new std::vector<int>; vec->push_back(1); // fine delete vec; // dynamically-allocated, so you have to delete it when you're done with it There's basically no reason to do that though. A std::vector is already essentially just a pointer to a dynamically-allocated array plus a little bit of extra metadata to store the size of the array. There are very few legitimate reasons to dynamically-allocate a std::vector instead of just declaring it locally (or as a data member of some class, etc): std::vector<int> vec; vec.push_back(1);
73,793,368
73,793,398
What happens to the old one after swapping with an unnamed object in C++
Consider the statement decltype(s){}.swap(s), where s is a STL class entity. If s is not ::std::array, this gets a nice complexity ( O(constant) ). But I wonder, where the old one goes? Is it automatically deleted? I think so, for the old one will never be used again. But I'm not sure about that (if the compiler will think so).
The content of s is swapped with the content of the temporary object created by decltype(s){}. Effectively, s will simply become re-initialized with its default content, and the temporary object will destroy the old content when itself is destroyed when it goes out of scope. And FYI, swap() works with std::array, too.
73,793,723
73,793,808
c++11 expanding parameter pack inside of a lambda
I'm trying to assign a lambda to my std::function that contains 1 call to Test for each type specified in the parameter pack, does anyone know how to do this? template<typename T> void Test() { } template<typename ... Ts> void Expand() { std::function<void(void)> func = [Ts] { for (const auto& p : { Ts... }) Test<Ts...>(); }; } int main(int argc, char** argv) { Expand<int, char>(); } I am trying to have this expand to... Test<int>(); Test<char>();
template<typename ... Ts> Ts here represents types. Template parameters are types. [Ts] { // ... } A lambda's capture captures values, and discrete objects rather than types. There's no such thing as a capture of types. for (const auto& p : { Ts... }) Range iteration iterates over values in some container. A braced initialization list is a list values too, not types. The major confusion here is the confusion between types and values, in C++. If the intent is to generate "call to Test for each type specified in the parameter pack", then the simplest solution is to use C++17's fold expression: template<typename ... Ts> void Expand() { std::function<void(void)> func = [] { ( Test<Ts>(), ...); }; } You tagged your question as C++11, but in the year 2022 it is highly likely that your compiler support C++17 as well. In the unlikely event that you're limited to C++11, a helper throwaway void function can be used as a crutch: template<typename ...Args> void ignore_me(Args && ...args) { } template<typename ... Ts> void Expand() { std::function<void(void)> func = [] { ignore_me( (Test<Ts>, 0)...); }; }
73,793,851
73,794,731
Why does " error: no match for 'operator<<' " occur when searching for the iterator?
I am looking for the positions of an element using find(); method, but for some reason it conflicts whit the cout<< and I don't understand why. #include <bits/stdc++.h> using namespace std; int main() { int n, busquedas, num, vas=0, pet=0; vector <int> arreglo; cin>>n; for(int i = 0; i < n; i++){ cin>> num; arreglo.push_back(num); } cin>>busquedas; for(int i = 0; i < busquedas; i++){ cin>>num; std::vector<int>::iterator it = std::find(arreglo.begin(), arreglo.end(), num); cout<<it; //Here the error occurs } return 0; } Also I have tried to change the iterator to the auto type and it shows the same error.
This error means that the << operator is not supported for the iterator type with std::cout. Try doing this if you want to see the distance of the iterator from the beginning of the vector. std::cout << std::distance(arreglo.begin(), it) << std::endl; Or this if you want the value in the array the iterator points to (thanks @Slava for the idea of the segfault avoidance). if (it != arreglo.end()) std::cout << *it << std::endl;
73,795,409
73,796,269
Is C++Builder (10.4 and above) a C++17 compliant compiler
I've been using previous version of C++ Builder and I decided to upgrade to 10.4 before 11.2 as I need C++17 compatibility. I'm already facing an issue with "scoped_lock" (C++ Builder 10.4 community edition => scoped_lock are missing (at least seems to be a path mess)) but now even that example from ccp_reference does not compile #include <variant> #include <string> #include <cassert> #include <iostream> int main() { std::variant<int, float> v, w; v = 42; // v contains int int i = std::get<int>(v); assert(42 == i); // succeeds w = std::get<int>(v); w = std::get<0>(v); // same effect as the previous line w = v; // same effect as the previous line // std::get<double>(v); // error: no double in [int, float] // std::get<3>(v); // error: valid index values are 0 and 1 try { std::get<float>(w); // w contains int, not float: will throw } catch (const std::bad_variant_access& ex) { std::cout << ex.what() << '\n'; } using namespace std::literals; std::variant<std::string> x("abc"); // converting constructors work when unambiguous x = "def"; // converting assignment also works when unambiguous std::variant<std::string, void const*> y("abc"); // casts to void const * when passed a char const * assert(std::holds_alternative<void const*>(y)); // succeeds y = "xyz"s; assert(std::holds_alternative<std::string>(y)); // succeeds } The compiler whines that there is no viable overload '=' at 2nd line of main (and further on). Basically, variant types do not seem to be usable at all. I've tried to make sure that c++17 is selected and I'm not using the "classic" version, but Clang, but nothing works. So am I missing something big or shall I just give up because that compiler is simply not at C++ 17 level?
std::variant is broken in C++ Builder for some types. However, the compiler is intended to support C++17, and many C++17 features work. You could use boost::variant instead. There is a workaround in comments: Issue: The assignment and constructor of Dinkumware std::variant checks that the value is assignable to exactly one type (_One_t<is_assignable, _Ty&, _Types&...>). This breaks those operations for a combination from int and double as they are assignable to each other. Fix: I've changed _One_ta to _One_ts in file 'variant' lines 607, 611, 614, 918, 919, 920, and 926 and also _One_tc to _One_ts in code lines 624,628, and 631. This limits these operators to the same types and works for me. I guess, that unambiguous conversions would be acceptable as well, but I've not checked the standard beyond looking to cppreference.com.
73,796,007
73,796,584
Use of overloaded oeprator[] is ambiguous
Simplified code as below: #include <string> #include <string_view> struct object{ operator std::string(){return "";} } struct foo{ foo operator[](std::string_view s){ return foo{}; } template <typename T> operator T(){ return object{}; } }; int main(){ foo f; std::string s = f["a"]; } clang gives an error: error: use of overloaded oeprator '[]' is ambiguous (with oeprand types 'foo' and 'const char*') note: candidate function foo operator[](std::string_view s) note: built-in candidate operator[](long, const char*) note: built-in candidate operator[](long, const volatile char*) but gcc compiles above code successfully. clang version is 12.0.1, gcc is 7.5.0 I'm confused, which compiler is right?
template <typename T> operator T(){ return object{}; } I think clang is correct here, since this snippet makes the foo class convertible to any type, and viable template functions are supposed to be instantiated before overload resolution comes into play: Before overload resolution begins, the functions selected by name lookup and template argument deduction are combined to form the set of candidate functions As you can see, the overload struggles with the following arguments: (long, const char*), so it has to be expression similar to this 3["a"] which is perfectly legal as per cppreference: expr1 [ expr2 ] For the built-in operator, one of the expressions (either expr1 or expr2) must be a glvalue of type “array of T” or a prvalue of type “pointer to T”, while the other expression (expr2 or expr1, respectively) must be a prvalue of unscoped enumeration or integral type. The result of this expression has the type T However it also gives a clue how to differentiate between built-in subscript and custom overloads: expr1 [ { expr, ... } ] The form with brace-enclosed list inside the square brackets is only used to call an overloaded operator[]. So you should be good if the said example is written like this: int main(){ foo f; std::string s = f[{"a"}]; return 0; } Or convert the subscript to string explicitly, so the compiler doesn't confuse it with built-in operator for arrays: int main(){ using namespace std::string_literals; foo f; std::string s = f["a"s]; return 0; }
73,796,018
73,797,216
Capturing shared_ptr in lambda using std::move
In following code std::move in lambda capture list felt unnecessary to me, but compiler does seem to need it. As there is extra code for copying shared_ptr is generated if I don't use std::move. Question is, why compiler can't optimise this on its own. template<typename T> std::function<void(void)> prepLambdaImpl(std::shared_ptr<T> aptr) { #ifdef CONVERT_SHARED_PTR_TO_XVALUE return [aptr=std::move(aptr)] #else return [aptr] #endif { printf("use count: %ld\n", aptr.use_count()); }; } Working example: https://godbolt.org/z/W3oWEjsjK
Automatic move only happens in return statement in some specific circumstances, which are not met here. Last usage doesn't trigger a move instead of a copy. The as-if rule allows optimization as long than observable behaviour is unchanged. Whereas we know the 2 forms are equivalent, it is not easy to know. Especially move and copy are unrelated functions; so optimizers only uses the copy code to try to optimize it (and it probably misses some extra information as invariant of the class (as refcounter not 0 at start of function)).
73,796,216
73,796,250
C++ - Class implicitly convertible to size_t
I have created a simple class and I would like it to be convertible to size_t. But I don't understand how to do it. class MyClass { private: std::size_t size; public: MyClass(); ~Myclass(); }; I tried this got some errors : Error: namespace std has no member class size_t Thanks for your help in advance.
std::size_t can be found in multiple headers, for example <cstddef> To enable the conversion, you can provide a operator std::size_t member function : #include <cstddef> class MyClass { private: std::size_t size; public: operator std::size_t() const { return this->size; } //... }; the compiler will call the member function when needed: int main() { MyClass foo; std::size_t s = foo; }
73,797,112
73,797,672
Need help understanding why this invalid C++ code compiles successfully
The following code compile correctly for me in some environments (e.g. on compiler explorer with GCC 9.3.0) and complains in others (CentOS 7.9.2009 (Core), GCC 9.3.1). #include <iostream> #include <string> using namespace std; int main() { std::string name="aakash"; name.erase(name.begin()+2, name.cend()); return 0; } When I get an error, the error is: test.cpp:6:40: error: no matching function for call to 'std::basic_string<char>::erase(__gnu_cxx::__normal_iterator<char*, std::basic_string<char> >, std::basic_string<char>::const_iterator)' 6 | name.erase(name.begin()+2, name.cend()); | ^ In file included from /opt/rh/devtoolset-9/root/usr/include/c++/9/string:55, from /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/locale_classes.h:40, from /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/ios_base.h:41, from /opt/rh/devtoolset-9/root/usr/include/c++/9/ios:42, from /opt/rh/devtoolset-9/root/usr/include/c++/9/ostream:38, from /opt/rh/devtoolset-9/root/usr/include/c++/9/iostream:39, from test.cpp:1: /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/basic_string.h:4698:7: note: candidate: 'std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::erase(std::basic_string<_CharT, _Traits, _Alloc>::size_type, std::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int]' 4698 | erase(size_type __pos = 0, size_type __n = npos) | ^~~~~ /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/basic_string.h:4698:23: note: no known conversion for argument 1 from '__gnu_cxx::__normal_iterator<char*, std::basic_string<char> >' to 'std::basic_string<char>::size_type' {aka 'long unsigned int'} 4698 | erase(size_type __pos = 0, size_type __n = npos) | ~~~~~~~~~~^~~~~~~~~ /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/basic_string.h:4714:7: note: candidate: 'std::basic_string<_CharT, _Traits, _Alloc>::iterator std::basic_string<_CharT, _Traits, _Alloc>::erase(std::basic_string<_CharT, _Traits, _Alloc>::iterator) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::basic_string<_CharT, _Traits, _Alloc>::iterator = __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >; typename _Alloc::rebind<_CharT>::other::pointer = char*]' 4714 | erase(iterator __position) | ^~~~~ /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/basic_string.h:4714:7: note: candidate expects 1 argument, 2 provided /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/basic_string.h:4734:7: note: candidate: 'std::basic_string<_CharT, _Traits, _Alloc>::iterator std::basic_string<_CharT, _Traits, _Alloc>::erase(std::basic_string<_CharT, _Traits, _Alloc>::iterator, std::basic_string<_CharT, _Traits, _Alloc>::iterator) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::basic_string<_CharT, _Traits, _Alloc>::iterator = __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >; typename _Alloc::rebind<_CharT>::other::pointer = char*]' 4734 | erase(iterator __first, iterator __last); | ^~~~~ /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/basic_string.h:4734:40: note: no known conversion for argument 2 from '__normal_iterator<const char*,[...]>' to '__normal_iterator<char*,[...]>' 4734 | erase(iterator __first, iterator __last); | ~~~~~~~~~^~~~~~ | ~~~~~~~~~^~~~~~ The error looks reasonable to me because, as per C++ documentation, both arguments to std::basic_string::erase should either be of type iterator or const_iterator. So, when it works (e.g. here), what allows it to work?
Since C++11, both arguments to the two-iterator overload of std::string::erase() are const_iterator. See form #3 on this cppreference page (the one you linked in your question). Further, the C++11 Standard requires that a conatiner's iterator types are convertible to the equivalent const_iterator. From this Draft C++11 Standard, in §23.2.1 [container.requirements.general], Table 96 has the following entry (bold emphasis mine): Expression Return Type Operational Semantics Assertion/note … X::iterator iterator type whose value type is T any iterator category that meets the forward iterator requirements. convertible to X::const_iterator. … So, in your call to .erase(), the first argument is being converted to a string::const_iterator. Thus, the bug is in those compilers that don't accept your call, assuming you have set them also to use the C++11 (or later) standard.
73,797,480
73,811,522
How do I avoid LNK2005 and LNK1169 errors while compiling TetGen in my project?
I am trying to compile TetGen and use the code below to tetrahedralize a .ply file although I am getting these two linker errors: LNK2005 main already defined in tetgen.obj LNK1169 one or more multiply defined symbols found The files that are includes in my project solution are "tetgen.h", "predicates.cxx", and "tetgen.cxx", and the folder path that these three files are in is included in my Project Properties > C/C++ > General > Additional Include Directories. I did the same for the "monkey.ply" file as well. This is all the code in my main file: #include "tetgen.h" int main() { tetgenio in, out; in.firstnumber = 0; in.load_ply((char *)"monkey.ply"); tetgenbehavior* b = new tetgenbehavior(); tetrahedralize(b, &in, &out); } Here are the "tetgen.h", "predicates.cxx", and "tetgen.cxx" files I'm using : https://minhaskamal.github.io/DownGit/#/home?url=https://github.com/libigl/tetgen I researched these errors and looked around a great amount but can't see why this is occurring. Any help would be greatly appreciated.
For anyone who may have this issue in the future with TetGen: The problem was that the TETGEN_LIBRARY flag needed to be defined in tetgen.h. I knew this, but every time I defined the flag, it would cause memory errors without fail. So, I kept TETGEN_LIBRARY undefined to avoid the memory error. Turns out, with TETGEN_LIBRARY defined, it will work. The problem was that "monkey.ply" did not exist/was in the wrong folder. Because "monkey.ply" did not exist it threw an unhandled exception. Why TetGen does not have a simple handle to check if a file exists before it tries to load it or not is beyond me. But that fixed things.
73,797,579
73,797,841
Question about brace-initialization of data member array in constructor?
In the following class: struct S { S() : B{} {} const uint8_t B[32]; }; Are all 32 bytes of the B array guaranteed to be initialized to zero by the default constructor? Is there any way to create an object of type S such that any element of the B array is not zero? (without const casting or reinterpretting memory). Do all forms of initialization of S lead to a zeroed B array?
Are all 32 bytes of the B array guaranteed to be initialized to zero by the default constructor? Yes, B is value-initialized which for an array means each member is value-initialized - primitive types are value-initialized to 0. Is there any way to create an object of type S such that any element of the B array is not zero? Not as far as I know, although S still has the default copy constructor so if somehow you got an S with non-zero B, you can clone those objects. const member guarantees the values cannot be changed throughout the lifetime, so any non-zero value must be set at initialization which leads to the third question... Do all forms of initialization of S lead to a zeroed B array? Yes, S is not an aggregate (due to user-provided ctor) so there is no way how to initialize the members directly.
73,797,710
73,797,732
C++ string::rfind time complexicity
What is time complexity of string::rfind method in c++? From what I understood, rfind is reversing the string and then doing string::find. Am I correct? Then it should be O(n)
No, you are not correct. rfind searches from the back of the string without reversing the string. The complexity is the same as for a forward find. I haven't found anything in the standard requiring this, but any search algorithm that you can use for find (like a naive search or a Boyer-Moore / Boyer-Moore-Horspool search) can also be used for rfind - so I find it highly unlikely that any library implementors would choose a less effective algorithm for their rfind implementation.
73,797,874
73,798,063
"typedef iterator<const value_type> const_iterator;" results in: "error: expected member name or ';' after declaration specifiers"
I want to create a vector from Zero and this requires creating an iterator class as well, but I have this problem when I want to set a const iterator That's my vector template < class T, class Alloc = std::allocator<T> > class vector { public: typedef T value_type; typedef Alloc allocator_type; typedef T* pointer; typedef T const * const_pointer; typedef T& reference; typedef T const & const_reference; typedef iterator<value_type> iterator; typedef iterator<const value_type> const_iterator; typedef reverse_iterator<iterator> reverse_iterator; // typedef reverse_iterator<const_iterator> const_reverse_iterator; typedef typename allocator_type::size_type size_type; typedef typename allocator_type::difference_type difference_type; and that's my iterator class template <class T> class iterator { protected: T* m_ptr; public: typedef T value_type; typedef value_type* pointer; typedef value_type* const const_pointer; typedef value_type& reference; typedef value_type const & const_reference; typedef std::ptrdiff_t difference_type; iterator() : m_ptr(nullptr) {} iterator(pointer ptr) : m_ptr(ptr) {} iterator(const iterator &iter) {m_ptr = iter.m_ptr;} The error: ./vector.hpp:17:29: error: expected member name or ';' after declaration specifiers typedef iterator<const value_type> const_iterator; How can I fix this?
You're trying to redefine the template to a concrete type: typedef iterator<value_type> iterator; I suggest renaming the class template to something else, like iterator_impl: template <class T> class iterator_impl { protected: T* m_ptr; public: typedef T value_type; typedef value_type* pointer; typedef value_type* const const_pointer; typedef value_type& reference; typedef value_type const & const_reference; typedef std::ptrdiff_t difference_type; iterator_impl() : m_ptr(nullptr) {} iterator_impl(pointer ptr) : m_ptr(ptr) {} iterator_impl(const iterator_impl &iter) : m_ptr{iter.m_ptr} {} }; Then this'll work: template < class T, class Alloc = std::allocator<T> > class vector { public: typedef T value_type; typedef Alloc allocator_type; typedef T* pointer; typedef T const * const_pointer; typedef T& reference; typedef T const & const_reference; typedef iterator_impl<value_type> iterator; typedef iterator_impl<const value_type> const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; // typedef reverse_iterator<const_iterator> const_reverse_iterator; typedef typename allocator_type::size_type size_type; typedef typename allocator_type::difference_type difference_type; };
73,798,236
73,801,399
Explicit template instantiation vs concept constraints
Let's suppose that I've either a function or a class template that should work only for certains types, e.g. std::wstring and std::string. I know that concepts can be used to put a constraint on a template so I would use something like this: template <typename T> concept StringLike = std::convertible_to<T, std::wstring> || std::convertible_to<T, std::string>; template<StringLike S> class A { public: A(const S& data) : data_{data} {}; private: S data_; } However, I was also thinking about template (class, in this case) instantiation which should achieve the same goal. template<typename S> class A { public: A(const S& data) : data_{data} {}; private: S data_; } template class A<std::string>; template class A<std::wstring>; If I understood their exchangeability correctly, when should I use one instead of the other? PS. I know that std::convertible_to<T, std::string> is not exactly the same as template class A<std::string> since the first is less constrained than the latter but it's just for the sake of the example.
You have two things here and they are not interchangeable. Concepts are used to constrain template arguments. This is what you should use if you want to restrict the type arguments your A class should be instantiated with. Explicit template instantiation, that you show in the second example, is something different. Remember that templates are not classes or functions but blueprints from which the compiler generates code (with a particular set of template arguments). Typically, this would happen when the compiler encounters the use of a template in your code (in each translation unit). This is called implicit template instantiation. However, you can also tell the compiler to instantiate a template from a set of arguments. This is called explicit template instantiation. This is what you did here: template class A<std::string>; template class A<std::wstring>; With your example, this would make no difference, you could still instantiate A<int>. Example: #include <string> template<typename S> class A { public: A(const S& data) : data_{data} {}; private: S data_; }; template class A<std::string>; template class A<std::wstring>; int main() { A<std::string> a1("42"); A<std::wstring> a2(L"42"); A<int> a(42); } However, let's say you have this: A.h #pragma once template<typename S> class A { public: A(const S& data); private: S data_; }; A.cpp #include "A.h" #include <string> template <typename S> A<S>::A(const S& data) : data_{data} {} template class A<std::string>; template class A<std::wstring>; and finally: main.cpp #include "A.h" #include <string> int main() { A<std::string> a1("42"); A<std::wstring> a2(L"42"); A<int> a(42); // error } Since the definition of A's constructor is in another translation unit (A.cpp), you cannot use it in main.cpp. However, you explicitly instantiated A for std::string and std::wstring and that makes them available outside that translation unit. Explicit template instantiation has two forms: explicit instantiation declaration: this is used to suppress an implicit instantiation. Such a declaration is introduced with the extern keyword. This tells the compiler that the definition is found in another translation unit (or later in the same translation unit). The purpose is to reduce compilation time by generating a single instantiation in a single translation unit. See https://isocpp.org/wiki/faq/cpp11-language-templates#extern-templates. explicit instantiation definition: forces the instantiation of the type it refers to. This must occur is the namespace of the template.
73,798,572
73,798,684
How to pass a virtual function as an argument in C++?
I am trying to write this code below: // Type your code here, or load an example. #include <iostream> class A { public: virtual void virFunc1(int a) = 0; virtual void virFunc2(int a) = 0; void func1(int a) { onTempFunc(this->virFunc1, a); } void func2(int a) { onTempFunc(this->virFunc2, a); } private: template <typename ImplFunc, typename... Args> void onTempFunc(ImplFunc impl_func, Args&&... args) { impl_func(args...); } }; class B : public A { public: void virFunc1(int a) override { std::cout << "virFunc1: " << a << std::endl; } void virFunc2(int a) override { std::cout << "virFunc2: " << b << std::endl; } }; int main() { auto* A = new B(); A->func1(2); A->func2(3); } But the compilation is failing in godbolt: https://godbolt.org/z/dq4szorq7 with the error: error: invalid use of non-static member function 'virtual void'. Basically I want to pass a virtual method to a function template along with its arguments. The function template will call that virtual method inside it. The different virtual methods can have different function signatures, that is why I have made onTempFunc a function template. Is there a way in C++ to achieve this?
The correct syntax for passing virFunc1 and virFunc2 as arguments would be to write &A::virFunc1 and &A::virFunc2 respectively as shown below. Additionally, for calling/using the passed member function pointer we can use ->* as shown below: class A { public: virtual void virFunc1(int a) = 0; virtual void virFunc2(int a) = 0; void func1(int a) { //-----------------vvvvvvvvvvvv-------->changed this onTempFunc(&A::virFunc1, a); } void func2(int a) { //-----------------vvvvvvvvvvvv------->changed this onTempFunc(&A::virFunc2, a); } private: template <typename ImplFunc, typename... Args> void onTempFunc(ImplFunc impl_func, Args&&... args) { //-------vvvvvvvvvvvvvvvvvvvvvvvvvv------> used ->* for member function pointer (this->*impl_func)(args...); } }; Working demo. Also refer to Passing functions as parameters in C++
73,799,194
73,799,298
Why the parent's method should be called explicitly with the parent's prefix from the child object?
see please the code: #include <iostream> using namespace std; class A{ public: A() = default; virtual void foo() = 0; bool foo(int x) { cout<<"A::foo(int x)\n"; return true; } bool func(int x) { cout<<"A::func(int x)\n"; return true; } }; class B: public A { public: B() = default; void foo() { cout<<"B::foo()\n"; } }; int main() { B b; b.func(0); //b.foo(0); //it's not compiled b.A::foo(0); return 0; } It seems the parent's method should be called explicitly with the parent's prefix from the child object for any reason. b.foo(0) is not compiled but if I add A:: prefix like b.A::foo(0) it works. Why is b.foo(0) not compiled but b.func(0) is?
It is called 'name hiding'. You have a function called foo without parameters in your subclass. The compiler will hide any other function with the same name from the superclass, unless you declare it with the using A::foo; directive in the child class. To my knowledge, this is done to avoid confusion of the function calls. All non-overloaded functions will be inherited automatically. Your code should work, if you write it like this (untested): class B: public A { public: using A::foo; B() = default; void foo() { cout<<"B::foo()\n"; } }; Please note that the using syntax will move ALL functions called foo into your subclass, regardless of their prototype. For further information, see https://www.ibm.com/docs/en/zos/2.3.0?topic=scope-name-hiding-c-only or https://bastian.rieck.me/blog/posts/2016/name_hiding_cxx/
73,799,750
73,800,505
How create a JSON-file from my data? (with С++, boost json)
I wanted to create a Json-file that will be created from the data received earlier. I don't understand how to work with Json files at all. I want to use the Boost library, because I am using it in another part of this program. I need to create a Json-file with a specific structure which I have attached below. I need to get JSON: { "track": { "Wheels": { "Wheel": [ { "start_pos": "10", "end_pos": "25" }, { "start_pos": "22", "end_pos": "78" } ] }, "Brakes": { "Brake": [ { "start_pos": "10", "midl_pos": "25" } ] } } } C++: #include "boost/property_tree/ptree.hpp" #include "boost/property_tree/json_parser.hpp" #include <string> using namespace std; using boost::property_tree::ptree; struct wheel { string start_pos; string end_pos; }; struct brake { string start_pos; string midl_pos; }; int main() { string tr = "track"; string ws = "Wheels"; string bs = "Brakes"; struct wheel w1; w1.start_pos = "10"; w1.end_pos = "25"; struct wheel w2; w2.start_pos = "22"; w2.end_pos = "78"; struct brake b1; b1.start_pos = "10"; b1.midl_pos = "25"; return 0; }
Despite comments suggesting to use a different library, which they could, I think @Nindzzya wanted to specifically use the boost library. Using the boost library from How to use boost::property_tree to load and write JSON: #include "boost/property_tree/ptree.hpp" #include "boost/property_tree/json_parser.hpp" #include <string> #include <iostream> using namespace std; namespace pt = boost::property_tree; struct wheel { string start_pos; string end_pos; }; struct brake { string start_pos; string midl_pos; }; int main() { string tr = "track"; string ws = "Wheels"; string bs = "Brakes"; struct wheel w1; w1.start_pos = "10"; w1.end_pos = "25"; struct wheel w2; w2.start_pos = "22"; w2.end_pos = "78"; struct brake b1; b1.start_pos = "10"; b1.midl_pos = "25"; pt::ptree wheel1, wheel2, wheels, wheel; pt::ptree brake1, brakes, brake; pt::ptree track, root; wheel1.put("start_pos", w1.start_pos); wheel1.put("end_pos", w1.end_pos); wheel2.put("start_pos", w2.start_pos); wheel2.put("end_pos", w2.end_pos); wheels.push_back(make_pair("", wheel1)); wheels.push_back(make_pair("", wheel2)); wheel.add_child("Wheel", wheels); track.add_child(ws, wheel); brake1.put("start_pos", b1.start_pos); brake1.put("midl_pos", b1.midl_pos); brakes.push_back(make_pair("", brake1)); brake.add_child("Brake", brakes); track.add_child(bs, brake); root.add_child(tr, track); pt::write_json(std::cout, root); return 0; } results in: { "track": { "Wheels": { "Wheel": [ { "start_pos": "10", "end_pos": "25" }, { "start_pos": "22", "end_pos": "78" } ] }, "Brakes": { "Brake": [ { "start_pos": "10", "midl_pos": "25" } ] } } }
73,800,644
73,861,012
Algorithm intuition: transform but with possibly more output items than input items?
I want to escape a string. That is, I want to copy characters, but where the input has " or \, I want to prepend \ on the output. I can write that easily enough, even very generically: //! Given a range of code units (e.g., bytes in utf-8), transform them to an output range. //! If a code unit needs escaping (per the given predicate), insert esc before that code unit in the output. template <typename InRange, typename OutIter, typename NeedsEscapingPred, typename EscCodeUnit> OutIter transformEscapeCodeUnits(const InRange& in, OutIter out, NeedsEscapingPred needsEscaping, EscChar esc) { for (const auto& codeUnit : in) { if (needsEscaping(codeUnit)) { *out++ = esc; } *out++ = codeUnit; } return out; } //! Convenience overload for common case: template <typename InRange, typename OutIter> OutIter transformEscapeCodeUnits(const InRange& in, OutIter out, char esc = '\') { return transformEscapeCodeUnits(in, out, [](auto c) { return c == '\' || c == '"'; }, esc); } However, in the spirit of "no raw loops", I looked at the algorithm and numeric header in search of a generic algorithm to do this. There's replace_if and replace_copy_if and remove_if, but I'm not seeing any std algorithms that take a sequence and output a potentially-longer sequence. This would be basically insert_copy_if, or even more generically, something like transform_items: //! Like transform, but TransformItem takes an element and an iterator and writes zero or more output elements: template <typename InRange, typename OutIter, typename TransformItem> OutIter transform_items(InRange&& inRange, OutIter out, TxFn transformItem) { for (auto&& x : std::forward<InRange>(inRange)) { out = transformItem(std::forwrad<decltype(x)>(x), out); } return out; } Then the escaping case would call transform_items(in, out, [shouldEsc, esc](auto c, auto out) { if (shouldEsc(c)) { *out++ = esc; } *out++ = c; }). Am I missing something, or is there nothing quite like that in the standard library?
After asking on Twitter, I got some very satisfying answers, although it involves the M-word (monad). First, @atorstling suggests that this is flatMap in JavaScript: https://twitter.com/atorstling/status/1574097704098988033?s=20&t=jzS503R6fMOqCajReygzJg https://dmitripavlutin.com/javascript-array-flatmap/ So translating to C++, I think the answer to my question is that this should be called flat_transform. With pedantic use of forwarding, that's: //! Like transform, but TransformItem takes an element and an iterator and writes zero or more output elements: template <typename InRange, typename OutIter, typename TransformOne> OutIter flat_transform(InRange&& inRange, OutIter out, TransformOne transform_one) { for (auto&& x : std::forward<InRange>(inRange)) { out = transform_one(std::forwrad<decltype(x)>(x), std::move(out)); } return out; } and yes, this appears to be a "missing algorithm" from the STL. But additionally, @salociN001 pointed out that "It's basically the monadic bind operation: Transforming a Container of A with a function taking A and returning a container of A into a flat container of A." https://twitter.com/salociN001/status/1573918982557548545?s=20&t=jzS503R6fMOqCajReygzJg So there we have it: It's monadic bind. A reasonable C++ name is flat_transform. It is, in fact, a missing algorithm.
73,800,949
73,801,133
Why does this string concatenation loop not work?
I want to use the formatting capabilites of the cstring library together with std::string's ability to dynamically allocate. Consider the following debug-log (I wouldn't do it in production code this way but for debugs cstring is convenient): Demo #include <cstdio> #include <string> #include <array> #include <cstdint> #include <cstring> std::array<std::pair<uint32_t, double>, 3> list = {{{1,11.1}, {2,22.2}, {3, 33.3}}}; int main() { std::string start; int size = snprintf(NULL, 0, "array (size=%zu);", list.size()); start.resize(size+1); snprintf(&start.front(), size+1, "array (size=%zu);", list.size()); for (auto [a,b] : list) { std::string tmp; size = snprintf(NULL, 0, "array (size=%zu);", list.size()); tmp.resize(size+1); snprintf(&tmp.front(), size+1, "\n(%u, %.2f);", a, b); start += tmp; } printf("%s\n", start.c_str()); } This doesn't work. It just prints the following: array (size=3); .. Instead of additionally printing each element. The loop runs however and if you emit the contents of tmp it shows that tmp actually stores the string mentioned. However, it doesn't seem to get attached to the start string the right way. I suspect SSO gets in the way here, but I can't explain how. Afaik resize already preallocates on heap if buffer size is > 15 right? What am I overlooking?
Basically you have resized start more then it is needed. std::string is exception and actual buffer size is one item more then size() returns to contain terminating zero. So start contains "array (size=3);\0" just before entering loop. Now after each update (loop iteration) content is added after this extra \0. So when you do printf("%s\n", start.c_str()); it will stop printing on this zero. Extra content is there, but printf API is unable to reach it since encounters zero too soon. You have also a typo with inconsistent format string. Fixed version.
73,801,029
73,801,077
fstream std::ios::binary printing in ASCII ? is it working correctly?
i was trying to write some data to a file in binary, the following is the minimal reproducible example of the problem, i am trying to print two unsigned 64 bit integers to a binary file and read one of them again ... problem is that the data is not printed or read in binary. #inclue <fstream> #include <iostream> #include <stdint.h> #include <iomanip> int main() { uint64_t a = 1; uint64_t b = 2; uint64_t c; std::ofstream s("file.bin", std::ios::out | std::ios::binary); s << a << b; s.close(); std::ifstream in("file.bin", std::ios::in | std::ios::binary); in >> c; in.close(); std::cout << c << '\n'; std::cin >> c; return 0; } the ouput of the above code is 12, so i checked the file using notepad, and it had 12 written in it in ASCII, not in binary, i am using the latest version of msvc2017 on windows, i tried compiling it for x86 and x64, in debug and release mode and the error persists. so is this its intended behavior ? and do i need to cast every variable to an array of characters when printing and reading ?
The stream input and output operators >> and << are text-based. They will write the output as text, and read the input as text. Even for binary files. To write raw binary data use the write function. And to read the raw binary data use read: s.write(reinterpret_cast<char const*>(&a), sizeof a); s.write(reinterpret_cast<char const*>(&b), sizeof b); // ... in.read(reinterpret_cast<char*>(&c), sizeof c);
73,801,349
73,801,585
Is there any way to make this CRTP work with inheritance?
Pardon the very vague question but I am struggling with even finding the proper words to describe what I'm trying to do. Basically, when I write a class I like having: class A { public: using uptr = std::unique_ptr<A>; using sptr = std::shared_ptr<A>; using wptr = std::weak_ptr<A>; }; So I can use A::uptr and such. Now I am starting to have a lot of classes with this mechanism and I was wondering if it was posssible to generalize it, somehow like this: template <typename T> class Ptrs { public: using uptr = std::unique_ptr<T>; using sptr = std::shared_ptr<T>; using wptr = std::weak_ptr<T>; }; class A : public Ptrs<A> { }; This seems to work properly but as soon as I introduce inheritance, it breaks. For example: class B : public A { }; B::uptr b; // this is a unique_ptr<A> class B : public Ptrs<B>, public A // does not compile { }; So I was wondering if there was any way to do this. I am using C++20, I am just not very familiar with templates / concepts / SFINAE and such. I am also not sure if this is even a good idea, I just thought it would be nice to have a way to do this.
When you derive B from both Ptrs<B> and A you're introducing two sets of identical type aliases. Therefore, the compiler is not able to figure out which one you want. The use of the CRTP cannot help you here. However, it's opposite pattern, mixins, may help you. Mixins are small classes that are intended to add common functionality to (unrelated) classes. Instead of deriving A and B from Ptrs, you derive Ptrs from A or B. Here is an example: #include <memory> template <typename T> class Ptrs : public T { public: using uptr = std::unique_ptr<T>; using sptr = std::shared_ptr<T>; using wptr = std::weak_ptr<T>; }; class A { }; class B : public A { }; int main() { Ptrs<A>::uptr a; Ptrs<B>::uptr b; } I don't know if this suites your need but this is the closest I can find.
73,801,509
73,802,053
How to properly delete QWidget from layout QT?
I know, that I can delete QWidget from QLayout so: QLayoutItem*item = wlay->takeAt(0); wlay->removeItem(item); delete item; delete w; However, without deleting QWidget(delete w), the widget will be on the screen. However, I cant delete the widget, so the widget will be on the screen. How to delete the widget from screen after removing it from layout? For example, I have so code: class QTest: public QWidget{ Q_OBJECT QVBoxLayout* wlay; QPushButton* b; public: QTest(){ wlay = new QVBoxLayout(); b = new QPushButton("click"); for(int i = 0; i < 20; i++) wlay->addWidget(new QLabel( "TEST" + QString::number(i))); wlay->addWidget(b); this->setLayout(wlay); connect(b, &QPushButton::clicked, this, &QTest::doit); } public slots: void doit(); }; void QTest::doit(){ //Removing all QLabel from Layout for(int i =0; i < 20; i++){ QLayoutItem*item = wlay->takeAt(0); wlay->removeItem(item); delete item; } } After removing QLabels from layout, labels are showed on screen. How to remove them from main Widget(without deleting them)?
It seems the function you're looking for is QWidget::hide(). Moreover, once you've called QLayout::takeAt(), you don't have to call QLayout::removeItem() afterwards since the former already removes the item as mentioned in the documentation. You can see QLayout::takeAt() as a shorthand for QLayout::itemAt() + QLayout::removeItem().
73,801,523
73,803,399
boost asio, yield an awaitable function
I have several time-consuming computation jobs, which shall not block the executing thread while executing. I also want to use c++20 coroutines + asio::awaitable's to accomplish this. The asio::io_context's thread for example should still be responsive. Therefore, I want my Job to suspend/yield after some time, and then continue its own execution, when the executioner does not have other jobs to do. Also, here are other coroutines with want to await the result of the computations (1:n relation!). What is the best (nearly no overhead due to timers for example) way to achieve this with boost::asio? Other coro libraries support something like events. Here is a code snippet to show my intention: MyReturnType result; CoroEvent coro_event; auto long_func(asio::ExecutionCtx ctx) -> awaitable<void> { for (size_t i{}; i < 1000){ for (size_t j{}; i < 1000){ result.compute(i*1000+j); } ctx.yield(); } coro_event.send(); co_return; } auto get_job_value() -> awaitable<MyReturnType> { co_await coro_event.async_wait(use_awaitable); // continues if done, suspends if not. co_return result; }
You can use timers, they are lightweight. E.g. struct CoroEvent { using C = asio::steady_timer::clock_type; using T = C::time_point; void send() { _timer.expires_at(T::min()); } auto async_wait(auto&& token) { return _timer.async_wait(std::forward<decltype(token)>(token)); } asio::steady_timer _timer{asio::system_executor{}, T::max()}; }; Live On Coliru #include <boost/asio.hpp> #include <coroutine> #include <iostream> namespace asio = boost::asio; using asio::use_awaitable; using asio::awaitable; struct MyReturnType { void compute(size_t v) { counter += v; } intmax_t counter = 0; } result; struct CoroEvent { using C = asio::steady_timer::clock_type; using T = C::time_point; void send() { _timer.expires_at(T::min()); } auto async_wait(auto&& token) { return _timer.async_wait(std::forward<decltype(token)>(token)); } asio::steady_timer _timer{asio::system_executor{}, T::max()}; } coro_event; awaitable<void> long_func() { for (size_t i = 0; i < 1'000; ++i) { for (size_t j = 0; j < 1'000; ++j) { result.compute(i * 1'000 + j); } // co_await std::suspend_always{}; } coro_event.send(); co_return; } awaitable<MyReturnType> get_job_value() { co_await coro_event.async_wait( use_awaitable); // continues if done, suspends if not. co_return result; } awaitable<void> consumer(int id, auto output_executor) { auto r = co_await get_job_value(); // synchronize output to prevent a mess post(output_executor, [id, sum = r.counter] { std::cout << "Received in consumer #" << id << ": " << sum << std::endl; }); co_return; } int main() { asio::thread_pool ioc; asio::co_spawn(ioc, long_func(), asio::detached); auto output = make_strand(ioc); for (int id = 1; id < 10; ++id) asio::co_spawn(ioc, consumer(id, output), asio::detached); ioc.join(); } Prints e.g. Received in consumer #2: 499999500000 Received in consumer #3: 499999500000 Received in consumer #5: 499999500000 Received in consumer #6: 499999500000 Received in consumer #4: 499999500000 Received in consumer #7: 499999500000 Received in consumer #9: 499999500000 Received in consumer #1: 499999500000 Received in consumer #8: 499999500000
73,801,767
73,802,198
std::any object cast to reference type, change its value, but original object is not changed
I was trying to see if std::any object can cast to reference type, and see whether changing the casted reference means to change original object. As below: struct My { int m_i; My() : m_i(1) {} My(const My& _) : m_i(2) {} My(My&& m) : m_i(3) {}; My& operator = (const My& _) { m_i = 4; return *this; } My& operator = (My&& _) { m_i = 5; return *this; } }; int main() { any a = My(); My& b2 = any_cast<My&>(a); b2.m_i = 6; cout << any_cast<My>(a).m_i << endl; return 0; } It prints 2. For my I expected that, as long as b2 is a reference, I hope changing b2.m_i will effect a.m_i, right? But result seems not as my expectation. Where did I get wrong, is my expectation valid? Thanks!
Look at your example without any any: #include <any> #include <iostream> using std::cout; using std::endl; using std::any; using std::any_cast; struct My { int m_i; My() : m_i(1) {} My(const My& _) : m_i(2) {} My(My&& m) : m_i(3) {}; My& operator = (const My& _) { m_i = 4; return *this; } My& operator = (My&& _) { m_i = 5; return *this; } }; int main() { My a = My(); My& b2 = a; b2.m_i = 6; cout << static_cast<My>(a).m_i << endl; } Output is: 2 Because static_cast<My>(a) is creating a temporary copy of a and your copy assigns 2 to the member. You can use static_cast<My&>(a) to not make a copy. After removing your somewhat weird copy and assignment, you can also get the same result with any: struct My { int m_i = 1; }; int main() { any a = My(); My& b2 = any_cast<My&>(a); b2.m_i = 6; cout << any_cast<My>(a).m_i << endl; // copy cout << any_cast<My&>(a).m_i << endl; // no copy } Output: 6 6
73,802,126
73,802,777
Solving an uncomplete nonlinear system of equations with Z3
I am trying to make a solver for nonlinear system of equations using the Z3 library in c++. It will exists with multiple equations and variables. Depending on previous steps in my software, it could be that some variables are unknown. When too many variables are unknown and the system does not have a single solution, I want to be notified about this. I made a simple fictional system of equations for testing that looks as follows: Ax = 1 Ay = 1 Bx = 3 By = 2 Cx = 7 Cy = Ay + (By - Ay) / (Bx - Ax) * (Cx - Ax) I wrote the following code to solve the system, in this example fairly easy: context ctx; expr Ax = ctx.real_const("Ax"); expr Ay = ctx.real_const("Ay"); expr Bx = ctx.real_const("Bx"); expr By = ctx.real_const("By"); expr Cx = ctx.real_const("Cx"); expr Cy = ctx.real_const("Cy"); solver s(ctx); s.add(Ax == 1); s.add(Ay == 1); s.add(Bx == 3); s.add(By == 2); s.add(Cx == 7); s.add(Cy == Ay + (By - Ay) / (Bx - Ax) * (Cx - Ax)); std::cout << s.check() << "\n"; model m = s.get_model(); auto CySolution = m.eval(Cy, true); std::cout << CySolution << "\n"; As output I get the following: sat 4.0 When for example "Ax" would be unknown, this can be simulated using following code: context ctx; expr Ax = ctx.real_const("Ax"); expr Ay = ctx.real_const("Ay"); expr Bx = ctx.real_const("Bx"); expr By = ctx.real_const("By"); expr Cx = ctx.real_const("Cx"); expr Cy = ctx.real_const("Cy"); solver s(ctx); //s.add(Ax == 1); s.add(Ay == 1); s.add(Bx == 3); s.add(By == 2); s.add(Cx == 7); s.add(Cy == Ay + (By - Ay) / (Bx - Ax) * (Cx - Ax)); std::cout << s.check() << "\n"; model m = s.get_model(); auto CySolution = m.eval(Cy, true); std::cout << CySolution << "\n"; Now the output is: sat (/ 78.0 23.0) I have tried detect when this system of equations give an implicit solution using functions as "expr.get_sort()" or "expr.is_real", but there is never a difference between the complete solution and the implicit one. Now I have two questions: How can I interpret "(/ 78.0 23.0)"? Is there a proper way to detect if the solution is an implicit function or not? Thanks in advance for any help!
(/ 78.0 23.0) simply means 78/23, i.e., approx. 3.39. Z3 prints real-values in this format since they are infinitely precise; as the fraction might require an unbounded number of digits in general. Your question regarding "proper way to detect is an implicit function" is a bit ambiguous. I assume what you mean is if there's a unique solution? That is, if a variable's value is "forced" by all the other equations or not? If that's the case, i.e., to check that a solution is unique, you'd essentially get the first solution, then assert the negation of that solution and ask if there's some other solution with this additional constraint: If the solver comes back unsat then you know the solution was unique. See many questions on stack-overflow regarding how to get multiple solutions from the solver.
73,802,668
73,803,127
How to check if a `std::vector<bool>` is true at multiple indexes simultaneously?
I have a std::vector<bool> of size N and a std::vector<std::size_t> of variable size containing indexes in [0, N). What is an idiomatic way to check if the first vector is true at all indexes given by the second vector? My possibly naive solution is: auto all_true( std::vector<bool> const& bools, std::vector<std::size_t> const& indexes) -> bool { auto res = true; for (auto index : indexes) { res = res and bools[index]; } return res; }
An idiomatic (though not necessarily efficient) way to do this would be to use the std::all_of STL function, using a predicate that simply returns the value of the Boolean vector at the index specified by each value in the size_t vector. Here's an outline/demo: #include <iostream> #include <vector> #include <algorithm> #include <random> bool all_true(const std::vector<bool>& data, const std::vector<size_t>& test) { return std::all_of(test.begin(), test.end(), [&data](size_t n) { return data[n]; }); } int main() { std::vector<bool> bools{ true, true, true, true, false, false, true, false, true, false }; std::vector<size_t> test1{ 0, 1, 2, 3, 6, 8 }; // all true std::vector<size_t> test2{ 0, 1, 2, 4, 7, 9 }; // some false std::cout << "Test1: " << all_true(bools, test1) << "\n"; std::cout << "Test2: " << all_true(bools, test2) << "\n\n"; // Just to show that the order doesn't matter ... std::cout << "After shuffling ...\n"; std::random_device rdev; std::mt19937 rgen(rdev()); std::shuffle(test1.begin(), test1.end(), rgen); std::shuffle(test2.begin(), test2.end(), rgen); std::cout << "Test1: " << all_true(bools, test1) << "\n"; std::cout << "Test2: " << all_true(bools, test2) << "\n"; return 0; }
73,802,728
73,805,361
basic mathematics c++ code for moving left or moving right for same if condition (k*x<b*k); k =1 or -1
Below is a simple program. int main() { int x, b = 3; //size_t x; size_t b = 3; char const *c = "moving_left"; // "moving_right" int k, border; if (!strcmp(c,"moving_left")) { k = 1; // moving left border = 0; x = 5; } else { k=-1; // moving right border = 7; x = 1; } while(true) { if (k*x<b*k) { cerr<<c<<x<<'\n'; if (x==border){break;} } x-=k; } return 0; } When I'm moving left, i.e., x is decreasing, I want to print "moving_left" after x falls behind b (x<b). And when moving right, i.e., x is increasing, I want to print "moving_right" after x crosses b (x>b). The above program works fine when x & b are signed integers, but might fail when I declared them as unsigned integers (size_t) because of int promotion (when k = -1). I want to run the above code in a single while loop for unsigned x & b (I like to declared them as unsigned because they are indices of unmentioned arrays). Also, in the if condition (kx<bk), I want left than sign (<). Multiplying by negative one works only for signed integers. Is there any math trick to make the above code work for unsigned integers with said conditions?
It is not completely clear why you want to use unsigneds and why you want so much to keep the condition (k*x<b*k) rather than something along the line of if ( (moving_left && x<b) || (!moving_left && b<x). Anyhow if you want to use unsignds and you want to use a single condition for both cases, then you can add a level of indirection: size_t x; size_t b = 3; bool move_left = true; int border; size_t upper; size_t lower; if (move_left) { x = 5; border = 0; upper = b; lower = x; } else { x = 1; border = 0; upper = x; lower = b; } while(true) { if (lower < upper) { std::cerr<<x<<'\n'; if (x==border){break;} } x-=k; }
73,802,743
73,803,043
How can I use dynamic_cast to get objects with a user-specified type?
If there is a method, which aims to put objects with specific type into another list, how can I use a user-defined parameter in the dynamic_cast? I know, that I can not use the std::string parameter directly in dynamic_cast, but is there a better solution? std::list<Car*> GetCarsOfType(std::string type) { std::list<Car*> carsOfType; for (int i = 0; i < cars.size(); ++i) { if (dynamic_cast<type> cars[i]) // This is not possible, but how can I solve this in a better way? { carsOfType.push_back(cars[i]); } } return carsOfType; }
You could keep a central repository of the mapping between the named car type and the actual type if you wish. It could then be used to do the dynamic_cast test for you. Example: #include <algorithm> #include <unordered_map> std::list<Car*> GetCarsOfType(std::string type) { // map between the named type and the dynamic_cast test: static const std::unordered_map<std::string, Car*(*)(Car*)> cast_checkers{ {"SUV", [](Car* c) -> Car* { return dynamic_cast<SUV*>(c); }}, {"Limo", [](Car* c) -> Car* { return dynamic_cast<Limo*>(c); }} }; std::list<Car*> carsOfType; // a filter that only returns true for those you want auto flt = [&type](Car* c) { return cast_checkers.at(type)(c) != nullptr; }; std::ranges::copy_if(cars, std::back_inserter(carsOfType), flt); return carsOfType; } Or using a view: #include <ranges> #include <unordered_map> std::list<Car*> GetCarsOfType(std::string type) { static std::unordered_map<std::string, Car* (*)(Car*)> cast_checkers{ {"SUV", [](Car* c) -> Car* { return dynamic_cast<SUV*>(c); }}, {"Limo", [](Car* c) -> Car* { return dynamic_cast<Limo*>(c); }}}; // same filter as above: auto flt = [&type](Car* c) { return cast_checkers.at(type)(c) != nullptr; }; // a view over those you want auto matchview = cars | std::views::filter(flt); // populate the container using the view: return {matchview.begin(), matchview.end()}; }
73,803,277
73,803,561
Is it better for performance to use boost::reversed than accessing back to front?
Is it better for performance to use boost::adaptors::reverse to access elements in a vector in reversed order instead of the usual v[i-1]? I.E.: std::vector<int> v {1,2,3,4}; for (const auto& el : boost::adaptors::reverse(v)) print(el); vs std::vector<int> v {1,2,3,4}; for (size_t i = v.size(); i > 0; --i) print(v[i - 1]); My logic would say that is not because reverse has to reverse the vector and then access it one by one and the usual way would load the vector piece in cache and then access the elements in reverse order. I guess that depending on the size of the vector one would be better than the other one, but I don't see why it would as a general rule.
reverse has to reverse the vector No, it's only an adaptor, it doesn't do anything to the vector. What it does is provide begin as the vector's rbegin, and end as the vector's rend. So these two pieces of code are more or less equivalent.
73,803,363
73,803,852
C++ - Modify member function if argument (function) is given
I am creating a class which takes as input arguments either 1 or 2 functions. My goal is that if only one function func is given then the member function dfunc is calculated using num_dfunc (which is the numerical derivative of func and is hardcoded inside the class). If two functions are given func and analytical_dfunc then the derivative is calculated using the analytical version. What is the best way to achieve this? This is a portion of my code class MyClass { public: int dim = 2; vector<double> num_dfunc(vector<double> l0) { // Numerical gradient of the potential up to second order // #TODO This should be rewritten! vector<double> result(dim); double eps = 0.001; for (int i = 0; i < dim; i++) { vector<double> lp2 = l0; lp2[i] += 2 * eps; vector<double> lp1 = l0; lp1[i] += eps; vector<double> lm1 = l0; lm1[i] -= eps; vector<double> lm2 = l0; lm2[i] -= 2 * eps; result[i] = (-func(lp2) + 8 * func(lp1) - 8 * func(lm1) + func(lm2)) / (12 * eps); } return result; } double (*func)(vector<double>); // Potencial pointer vector<double> (*dfunc)(vector<double>); // Gradient pointer MyClass(double (*func)(vector<double>)) { this->func = func; // THIS IS WRONG this->dfunc = num_dfunc; } MyClass(double (*func)(vector<double>),double (*analytical_dfunc)(vector<double>)) { this->func = func; // THIS IS WRONG this->dfunc = analytical_dfunc; } This is a, somewhat, pythonic way of what I want to do. PS: This is not what I have so far, I tried many things but none of them worked. Edit : Error, on dfunc return type. Typo on analytical_dfunc
I would make num_dfunc either a static member function, or probably even better a free function, that has nothing to do with MyClass. I would modify it, such that it also takes the zeroth-order function as well as the dimension as an input. If your constructor is called with just one argument, you can create the second function from the static num_dfunc using a lambda. [=](auto const& arg){ return num_dfunc(func, dim, arg); } the notation [=] will capture all needed variables (func, dim) in the lambda body, that are not part of the argument list (auto const& arg). Also I would make your class a class template accepting any type of function F, C++ has many different kinds of callable objects, of which raw function pointers are just one (there are also functors, lambdas, std::function, ...). If you make your class a template, it will work with all kinds of function types. I haven't tested this, but basically your class would look like this: #include <vector> template <typename F> class MyClass { private: static std::vector<double> num_dfunc( F const& f, int dim, std::vector<double> const& l0 ) { // Numerical gradient of the potential up to second order // #TODO This should be rewritten! std::vector<double> result(dim); double eps = 0.001; for (int i = 0; i < dim; i++) { std::vector<double> lp2 = l0; lp2[i] += 2 * eps; std::vector<double> lp1 = l0; lp1[i] += eps; std::vector<double> lm1 = l0; lm1[i] -= eps; std::vector<double> lm2 = l0; lm2[i] -= 2 * eps; result[i] = (-f(lp2) + 8 * f(lp1) - 8 * f(lm1) + f(lm2)) / (12 * eps); } return result; } int dim; F func; // Potencial pointer F dfunc; // Gradient pointer public: MyClass(F const& fun) : dim(2) , func(fun) , dfunc( [=](auto const& arg){ return num_dfunc(func, dim, arg); } ) { } MyClass(F const& fun, F const& analytical_fun) : dim(2) , func(fun) , dfunc(analytical_fun) { } }; You can play around on compiler explorer with this: https://godbolt.org/z/EMxqr7KE4
73,803,533
73,805,024
printf all characters in a string using HEX i.e. printf("%X", string.c_str())
I'm on an embedded Linux platform which uses C++ but also printf for logging. I receive data in string type - "\241\242" - but they're unprintable characters. On the sender side, I type in a hex number in string format i.e. "A1A2" but the sender encodes it as the number 0xA1A2 so on the receiver, I cannot use printf("%s", thing.c_str()) I can use printf("%X") but only for one character at a time in a for loop printf("%X", thing[i]). The for-loop would be ok except that since I need to use the logging macro, each hex character comes out on a separate line. QUESTION Is there a way to use ONE printf("%X") to print all the characters in the string as hex? Something like printf("%X\n", uuid.c_str()); The output of below code. 500E00 A1A2 I think it's printing the pointer from .c_str() as a hex number. // Example program #include <iostream> #include <string> using namespace std; int main() { string uuid = "\241\242"; printf("%X\n", uuid.c_str()); for(int i=0; i < uuid.size(); i++) { printf("%hhX", uuid[i]); } }
Is there a way to use ONE printf("%X") to print all the characters in the string as hex? No. Is there a way You can write your own printf with your own specifier that will do whatever you want. You might be interested in printk used in linux kernel for inspiration, I think that would be %*pEn or %*ph or %*phN. On glibc you can add your own format specifier https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html .
73,803,717
73,820,786
How do I determine which GStreamer plugin decodebin3 selected?
I need to determine which decoder plugin decodebin3 has selected. I've found that I can't always link it to certain downstream elements after it spawns the source pad. But if I "disable" (change the rank) of a given unusable plugin, I can make my pipeline linkable/functional. I want to dynamically switch the selection, in the event the downstream elements can't link. The older decodebin had signals like autoplug-select, which looks to have been a means for figuring out the plugins in play. But decodebin3 doesn't have equivalent signals? When I have debug logging enabled, I have seen the name of the child plugin (which is how can manually disable a "bad" one in POC manner to test my concept). Is there a way to iterate through the children inside a decodebin3?
I figured it out myself. Basically, the element created by this plugin is a "bin" (which is why it's called decodeBIN3!), and therefore one can use gst_bin_iterate_elements to iterate through the child elements within it. Then, it's possible to get the factory an element was produced by, and from there check the type of factory e.g. being a decoder. You can can also get the unique id of the "factory type". Here are the major functions to use when formulating your own solution for a similar issue. (Sorry it would be a pain, and perhaps confusing, if I posted all the code for my exact use case...) gst_bin_iterate_elements( GST_BIN( decoder ) ); GstElement *element( GST_ELEMENT_CAST( g_value_peek_pointer( &value ) ) ); GstElementFactory *factory( gst_element_get_factory( element ) ); const gboolean isDecoder( gst_element_factory_list_is_type( factory, GST_ELEMENT_FACTORY_TYPE_DECODER ) ); const GType factoryType( gst_element_factory_get_element_type( factory ) );
73,803,967
73,805,733
zmq::message_t assign a string
I am trying to familiarize myself with ZeroMQ by creating a simple socket communication betwenn a publisher and a subscriber to send a test message. However, I can't find the information I want on how to put a string inside a zmq::message_t type message. Indications pointed to the use of "std::memcpy(message.data(), ms.data(), ms.size())" which I tried. However, by debuging the coding using Watchs, I see that the message is still empty after execution: WATCH IMAGE and it is also empty when I print it out using a cout: Cmd Is there another way to assign a string to a zmq::message_t message or is there something else wrong here? My entire code is: int main() { zmq::context_t context(1); zmq::socket_t pub(context, ZMQ_PUB); pub.bind("tcp://*:5555"); std::cout << "Pub Connected" << std::endl; zmq::socket_t sub(context, ZMQ_SUB); sub.connect("tcp://localhost:5555"); std::cout << "Sub Connected" << std::endl; std::stringstream s; s << "Hello World"; auto ms = s.str(); zmq::message_t message(ms.size()); memcpy(message.data(), ms.c_str(), ms.length()); pub.send(message, zmq::send_flags::none); std::cout << "message: " << message << std::endl; zmq_sleep(1); sub.set(zmq::sockopt::subscribe, "Hello World"); zmq::message_t rx_msg; sub.recv(rx_msg,zmq::recv_flags::none); std::string rx_str; rx_str.assign(static_cast<char*>(rx_msg.data()), rx_msg.size()); std::cout << "Message: " << rx_str << "received!" << std::endl; }
There is a constructor for zmq::message_t that has the signature (docs) message_t(const void *data_, size_t size) so you could use this like zmq::message_t message(static_cast<void*>(ms.data()), ms.size());
73,804,080
73,804,283
C++ partial template function specialization
I have a primary template function: template <typename T, int U> void print() { std::cout << "int is " << U << std::endl; } How to make a partial specialization for function print, so that U is inferred based on a type of T? For example: template <typename T> void print<T, 1>(); // If T is float template <typename T> void print<T, 2>(); // If T is Eigen::half print<float>(); // Prints "int is 1" print<Eigen::half>(); // Prints "int is 2"
You can't partially-specialize functions, and specializations are selected after all of the template's arguments are known, so you can't do this with partial specialization. What you can do is have a separate function template that has a single argument that simply calls through to the underlying function template: template <typename T> void print(); template <> void print<float>() { print<float, 1>(); } template <> void print<Eigen::half>() { print<Eigen::half, 2>(); } Demo This will do what you want, but it would still be possible to override the behavior by explicitly calling print<float, 42>(). If you don't want that to be possible, you can remove the second parameter from the base function and use a type trait to determine it: template <typename T> struct IntDeterminer; template <> struct IntDeterminer<float> : std::integral_constant<int, 1> {}; template <> struct IntDeterminer<Eigen::half> : std::integral_constant<int, 2> {}; template <typename T> void print() { std::cout << "int is " << IntDeterminer<T>::value << std::endl; } Demo
73,804,659
73,804,744
How to retrieve an enum index value based on char array? in C++ (cpp)
Disclaimer: New to programming, learning on the fly. This is my first post and apologize if the question is not written clearly. I am trying to go through a tutorial on building a chess engine, but it is written in C and I am attempting to convert it to C++ code. The idea of the code is to enter a char and retrieve the index value of an enum. I am getting a compile error because of this code. How do I approach this as it isn't clear to me after trying different ideas. E.g. std::cout << CHAR_TO_PIECE['k']; with expected output of 11. in "typedefs.h" enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k}; in "board.h" extern const int CHAR_TO_PIECE[]; and in board.c // convert ASCII character pieces to encoded constants int CHAR_TO_PIECE[] = { ['P'] = P, ['N'] = N, ['B'] = B, ['R'] = R, ['Q'] = Q, ['K'] = K, ['p'] = p, ['n'] = n, ['b'] = b, ['r'] = r, ['q'] = q, ['k'] = k };
You can write a function to return specific enum for you char input . enum Piece {P, N, B, R, Q, K, p, n, b, r, q, k}; Piece charToPiece(char ch) { switch (ch) { case 'P': return P; case 'N': return N; case 'B': return B; case 'R': return R; case 'Q': return Q; case 'K': return K; case 'p': return p; case 'n': return n; case 'b': return b; case 'r': return r; case 'q': return q; case 'k': return k; } }
73,804,726
73,810,117
Getting the PowerShell::Create.AddScript.Invoke return value in c++
With reference to Would like to run PowerShell code from inside a C++ program, I have created a program to execute the PowerShell script in C++ using System.Management.Automation.dll. But, I wasn't able to retrieve the return data from the Invoke() function. I can create individual PSObject, but I couldn't create the collection of PSObject. Attached the the code: #include <vcclr.h> #include<Windows.h> #include<iostream> #using <mscorlib.dll> #using <System.dll> #include<vector> #using <System.Management.Automation.dll> using namespace std; using namespace System; using namespace System::Management::Automation; void RunPowerShell( ) { Collection<PSObject> powObject= PowerShell::Create()->AddScript(gcnew String("get-wmiobject -query \"select * from win32_bios\""))->Invoke(); PSObject k; String ^s=PowerShell::Create()->AddCommand("(Get-Variable PSVersionTable -ValueOnly).PSVersion")->ToString(); printf("%s\n", s); } int main() { RunPowerShell(); return 0; } Errors: E0020 identifier "Collection" is undefined E0254 type name is not allowed E0020 identifier "powObject" is undefined C2065 'Collection': undeclared identifier C2275 'System::Management::Automation::PSObject': expected an expression instead of a type C2065 'powObject': undeclared identifer
You need to either import the proper namespaces, like this: #include <Windows.h> #include <vcclr.h> #include <iostream> #include <vector> #using <mscorlib.dll> #using <System.dll> #using <System.Management.Automation.dll> using namespace std; using namespace System; using namespace System::Collections::ObjectModel; // you need this one using namespace System::Management::Automation; void RunPowerShell() { // or simply use C++ auto! Collection<PSObject^>^ powObject = PowerShell::Create()->AddScript(gcnew String("get-wmiobject -query \"select * from win32_bios\""))->Invoke(); for (int i = 0; i < powObject->Count; i++) { Console::WriteLine(powObject[i]); } } int main() { RunPowerShell(); return 0; or just use the cool C++ auto keyword, like this: auto powObject = PowerShell::Create()->AddScript(gcnew String("get-wmiobject -query \"select * from win32_bios\""))->Invoke(); And as a bonus, Visual Studio's magic will show the namespace for you if you hover the mouse around the auto keyword:
73,804,774
73,949,897
boost::asio async operations handler not called
i would like to use a very similar pattern to the boost::asio example here, so i first ran the example on windows 10 running boost 1.71.0, and it executed properly. Dropped the unchanged client code in my project with main() replaced by: [EDIT] boost::asio::io_context io_context; auto c = std::make_unique<test_async::tcp_client>(io_context); work_guard_ = std::make_unique<work_guard_type>(io_context.get_executor()); worker_result_ = std::async(std::launch::async, [&]() { io_context.run(); }); io_context.post([&]() { c->start(argv[1], argv[2]) }); ... // at end of program work_guard_.reset(); worker_result_.wait(); and the async_handlers were not called. hmmm... My question is: what could be going on to cause the tcp_client code to not work properly when used in my application, but it works fine in the example demo? When trying to figure out why this wasn't working in my app, I replaced the async_connect with blocking connect, async_write with blocking write, and it worked. So, synchronous calls work, but async calls don't. Not clear what's the issue.
Yep, pilot error. The code worked, but it was called from a member function in a templated class. Put the code in the header file and it works. Feeling a bit silly right about now. Thanks @sehe for a good answer
73,804,801
73,805,487
Implement a PID control in C++ for a motor with absolute encoder
Sorry if my question is too stupid, but I can't figure out how to solve my problem. I have a motor with a gearbox and I also have an absolute encoder mounted on the gearbox shaft. I need to make the output shaft rotate in a range from -90 to +90 and it is centered in 0°. Now, when the shaft is in 0°, then the encoder outputs 1010, when it is at -90°, the encoder outputs 1120 and when it is in +90° it outputs 900. When the shaft is in 0° and has to reach +90°, the motor must rotate clockwise and when it needs to reach -90°, it needs to rotate counterclockwise. I would like to command the motor by only giving it the position in degree. For example, I'd like to have a function like: move_motor(1, 45°) int move_motor(id_motor, pos){ read current motor position // motor is at 0° make motor #1 spins clockwise until encoder returns 955 } I think that a PID controller would be a smart solution, but I really do not know how to implement it in C++, sorry, I'm not a developer. Or do you suggest just to use if/else statements? EDIT: In order to make the motor move, I use this function: void move_motor(motor_id, direction) and it makes the motor spin in counterclockwise or clockwise depending on the second parameter To stop the motors: void stop_motor(motor_id, 0) and this other function: int get_enc(encoder1) returns an integer depending on the encoder1 readings. So for example, to reach the desired position it should be: while (get_enc != desired_position){ move_motor(motor_id, direction) } but the direction should be handled, too.
Here you go: unsigned angle2pid(double angle_in_degrees) { return 1010 - angle_in_degrees * 55 / 45; } void move_motor_to_angle(int motor_id, double angle) { static const int CLOSE_ENOUGH = 10; int currentPosition = get_enc(motor_id); int desiredPosition = angle2pid(angle); // IF WE ARE CLOSE ENOUGH, DO NOTHING... if(std::abs(currentPosition - desiredPosition) <= CLOSE_ENOUGH) { return; } if(desiredPosition > currentPosition) { move_motor_in_dir(motor_id, CLOCKWISE); while(desiredPosition > currentPosition) { currentPosition = get_enc(motor_id); } stop_motor(motor_id); } else if(desiredPosition < currentPosition) { move_motor_in_dir(motor_id, COUNTER_CLOCKWISE); while(desiredPosition < currentPosition) { currentPosition = get_enc(motor_id); } stop_motor(motor_id, 0); } } Note that the motor_id might be a different type which you'll have to slightly adjust. And perhaps the get_enc requires a different argument, but this is the idea. Credit goes to @TedLyngmo who provided the angle2pid function.
73,805,510
73,805,591
Does new int[] return the address of the first element in the array or the address of the entire array?
int *a = new int[16]; How do I access the array afterwards? Does a hold the address of the entire array or just the first element in the array? Basically, I have this code, struct student { string name; int age; }; int num_students = get_number_of_students(); struct student *students = new student[num_students]; Now, how do I access the elements in that array?
a is simply a pointer to an int. It points to the beginning of the block of memory you have allocated. It does not carry any information about the size of the array. As advised in comments, best practice in C++ is to use a std::vector for this, letting it handle the memory allocation (and importantly de-allocation) and provide convenient functions (via STL) for determining size and iterating over its elements. std::vector<student> students(num_students);
73,805,807
73,807,557
How to use the QGraphicsItem::setPos() function
I can't figure out how the setPos() function of the QGraphicsItem class works. My Rect class has no parent, so its origin is relative to the scene. I try to put the rectangle back at (0, 0) after it is moved with the mouse but it is placed in a different place depending on where I had moved it. I suppose that means that the origin of the scene moves but what causes this change? class Rect : public QGraphicsItem { public: Rect(): QGraphicsItem() { setFlag(ItemIsMovable); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override { painter->drawRect(0, 0, 20, 20); } void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override { setPos(0, 0); update(); QGraphicsItem::mouseReleaseEvent(event); } QRectF boundingRect() const { return QRectF(0, 0, 20, 20); } private: }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QGraphicsScene scene; QGraphicsView view(&scene); Rect obj; scene.addItem(&obj); view.show(); return a.exec(); }
When you create a QGraphicsView you initially accept the default settings. A standard setting is, for example, that it is horizontally centered. Another factor is that the default area size is probably up to the maximum size. what you can do set a custom size for the scene. You do that with graphicsView->setSceneRect(0,0,300,300); (for example) scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); ui->graphicsView->setRenderHint(QPainter::Antialiasing); ui->graphicsView->setSceneRect(0,0, 300,300); rectItem = new QGraphicsRectItem(0,0, 100, 100); rectItem->setPen(QPen(Qt::darkMagenta, 2)); rectItem->setBrush(QGradient(QGradient::SaintPetersburg)); rectItem->setPos(190,10); scene->addItem(rectItem); So in summary: if you want to work with fixed values. maybe it is better to know the total size. (that was not clear from your code, that's why I gave this example)
73,805,831
73,807,099
Does DirectX11 Have Native Support for Rendering to a Video File?
I'm working on a project that needs to write several minutes of DX11 swapchain output to a video file (of any format). I've found lots of resources for writing a completed frame to a texture file with DX11, but the only thing I found relating to a video render output is using FFMPEG to stream the rendered frame, which uses an encoding pattern that doesn't fit my render pipeline and discards the frame immediately after streaming it. I'm unsure what code I could post that would help answer this, but it might help to know that in this scenario I have a composite Shader Resource View + Render Target View that contains all of the data (in RGBA format) that would be needed for the frame presented to the screen. Currently, it is presented to the screen as a window, but I need to also provide a method to encode the frame (and thousands of subsequent frames) into a video file. I'm using Vertex, Pixel, and Compute shaders in my rendering pipeline.
Found the answer thanks to a friend offline and Simon Mourier's reply! Check out this guide for a nice tutorial on using the Media Foundation API and the Media Sink to encode a data buffer to a video file: https://learn.microsoft.com/en-us/windows/win32/medfound/tutorial--using-the-sink-writer-to-encode-video Other docs in the same section describe useful info like the different encoding types and what input they need. In my case, the best way to go about rendering my composite RTV to a video file was creating a CPU-Accessible buffer, copying the composite resource to it, then accessing the CPU buffer as an array of pixel colors, which media sink understands.
73,805,926
73,806,053
How to change textout() when it's already drawn?
I'm trying to move static TCHAR greeting[] = _T("123"); by using arrows, but it doesn't move at all. MessageBox is used as a confirmation of getting keyboard input. void move(HWND hWnd, WPARAM wParam, LPARAM lParam, unsigned int *x, unsigned int * y) { RECT rt; if (wParam == VK_LEFT) { GetClientRect(hWnd, &rt); x = x - 5; InvalidateRect(hWnd, &rt, FALSE); MessageBox(hWnd, LPCSTR("123"), LPCSTR("123"), MB_OK); } if (wParam == VK_DOWN) { GetClientRect(hWnd, &rt); y = y - 5; InvalidateRect(hWnd, &rt, FALSE); } if (wParam == VK_UP) { GetClientRect(hWnd, &rt); y = y + 5; InvalidateRect(hWnd, &rt, FALSE); } if (wParam == VK_RIGHT) { GetClientRect(hWnd, &rt); x = x + 5; InvalidateRect(hWnd, &rt, FALSE); } } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; static TCHAR greeting[] = _T("123"); unsigned int x = 50; unsigned int y = 50; switch (message) { case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); TextOut(hdc, x, y, greeting, 3); EndPaint(hWnd, &ps); break; } case WM_KEYDOWN: move(hWnd, wParam, lParam, &x, &y); break; case WM_DESTROY: { PostQuitMessage(0); break; default: { return DefWindowProc(hWnd, message, wParam, lParam); break; } } return 0; } } Can somebody explain, what is wrong here? I'm still trying to learn about <Windows.h> so pls don't try to make the code much more complicated.
The x and y variables you are using to draw the text with are local to WndProc and are always reset to the initial values whenever a new message is received. You need to move their declarations outside of WndProc() (or at least make them static) so that their values can persist between messages. You can then update their values in your WM_KEYDOWN handler, and use their current values to draw the text in your WM_PAINT handler. Also, your move() function is updating the pointers that are pointing at the x and y variables, it is not updating the values of the x and y variables themselves. Try this instead: void move(HWND hWnd, WPARAM wParam, LPARAM lParam, unsigned int *x, unsigned int * y) { switch (wParam) { case VK_LEFT: *x -= 5; InvalidateRect(hWnd, NULL, FALSE); break; case VK_DOWN: *y -= 5; InvalidateRect(hWnd, NULL, FALSE); break; case VK_UP: *y += 5; InvalidateRect(hWnd, NULL, FALSE); break; case VK_RIGHT: *x += 5; InvalidateRect(hWnd, NULL, FALSE); break; } } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { static TCHAR greeting[] = _T("123"); static unsigned int x = 50; static unsigned int y = 50; switch (message) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); TextOut(hdc, x, y, greeting, 3); EndPaint(hWnd, &ps); break; } case WM_KEYDOWN: move(hWnd, wParam, lParam, &x, &y); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
73,806,073
73,806,120
Using "CreateProcess()" gives error C2664
I am trying to open an application from my .cpp file. I did some research and found that using CreateProcess() would be the best option. Doing this resulted in the following code: //Below has the purpose of starting up the server: ----------------------------------------------- LPWSTR command = (LPWSTR)"C:\\Users\\CCRT\\Documents\\UPDATED\\FINALSERVER\\FINALSERVER\\Debug\\FINALSERVER.exe"; // Start the child process. LPSTARTUPINFOA si; PROCESS_INFORMATION pi; if (!CreateProcess(NULL, // No module name (use command line) command, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi) // Pointer to PROCESS_INFORMATION structure ) { printf("CreateProcess failed (%d).\n", GetLastError()); } else { std::cout << "Command success\n"; } However, i get the following error when i try to build my solution: cannot convert argument 9 from 'LPSTARTUPINFOA *' to 'LPSTARTUPINFOW'  The error is on the CreateProcess() function. I am wondering if anybody can explain the error to me and tell me how to fix it as i am so confused about what is going wrong.
cannot convert argument 9 from 'LPSTARTUPINFOA *' to 'LPSTARTUPINFOW' You are giving the function a pointer to a STARTUPINFOA pointer but the function expects a STARTUPINFOW pointer (which is what LPSTARTUPINFOW is typedefined as). The correct way is therefore to define si like so: STARTUPINFOW si{sizeof(STARTUPINFOW)}; // not LPSTARTUPINFOW The sizeof(STARTUPINFOW) part sets the cb member of si to the size of the structure. Also: LPWSTR command = (LPWSTR)"C:\\U... is wrong. It should be wchar_t command[] = L"C:\\U..."; // ^ The L makes the string literal a const wchar_t[N] (where N is the length of the string + 1), but since the command may be altered by CreateProcessW, you need to put it in a mutable wchar_t array. It's also best to be consistent. Use the "wide" functions explicitly, like CreateProcessW, unless you plan on building for Ansi too, then be consistent and use STARTUPINFO (without A or W) and use the TEXT macro to define strings.
73,806,642
73,806,732
Converting cv::Mat to Eigen::Matrix gives compilation error from opencv2/core/eigen.hpp file (OpenCV + Eigen)
In my code, I have to convert cv::Mat to Eigen::Matrix so that I can use some of the functionalities of the Eigen library. I believe a straightforward option would be to manually copy+paste each element of cv::Mat into Eigen::Matrix. However, I stumbled upon this question on SO and found out about the cv::cv2eigen function. It's located in opencv2/core/eigen.hpp file. Here is the sample code: #include <iostream> #include <opencv2/core.hpp> #include <opencv2/core/eigen.hpp> #include <Eigen/Core> int main(int argc, char const *argv[]) { cv::Mat cv_mat = cv::Mat::eye(3, 3, CV_64FC1); std::cout << cv_mat << std::endl; Eigen::Matrix3d eigen_mat; cv::cv2eigen(cv_mat, eigen_mat); std::cout << eigen_mat << std::endl; return 0; } However, weirdly enough, upon trying to build, I get way too many compilation errors from opencv2/core/eigen.hpp file: /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:63:22: error: ‘Eigen’ does not name a type; did you mean ‘eigen’? void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst ) ^~~~~ eigen /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:63:35: error: expected unqualified-id before ‘<’ token void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst ) ^ /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:63:35: error: expected ‘)’ before ‘<’ token /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:63:35: error: expected initializer before ‘<’ token /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:81:22: error: ‘Eigen’ does not name a type; did you mean ‘eigen’? void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, ^~~~~ eigen . . . /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:234:6: error: redefinition of ‘template<class _Tp> void cv::cv2eigen(const cv::Mat&, int)’ void cv2eigen( const Mat& src, ^~~~~~~~ /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:141:6: note: ‘template<class _Tp> void cv::cv2eigen(const cv::Mat&, int)’ previously declared here void cv2eigen( const Mat& src, ^~~~~~~~ /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:259:16: error: ‘Eigen’ has not been declared Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) ^~~~~ /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:259:29: error: expected ‘,’ or ‘...’ before ‘<’ token Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) ^ /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp: In function ‘void cv::cv2eigen(const cv::Matx<_Tp, 1, _cols>&, int)’: . . . /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp:262:23: error: ‘Eigen’ has not been declared if( !(dst.Flags & Eigen::RowMajorBit) ) ^~~~~ This is quite strange, right? Because I'm getting errors for the OpenCV functions that I'm not even touching. So, how can I fix this weird issue? P.S. I'm using OpenCV 4.2.0 I've modified some explicit paths with <string>
Actually, I found the root cause: As per line 78 & 79 of opencv/modules/core/include/opencv2/core/eigen.hpp on 4.x branch: @note Using these functions requires the Eigen/Dense or similar header to be included before this header. So, surprisingly enough, all I had to do was change the #include order from #include <opencv2/core.hpp> #include <opencv2/core/eigen.hpp> #include <Eigen/Core> to #include <opencv2/core.hpp> #include <Eigen/Core> #include <opencv2/core/eigen.hpp> On the other hand, I checked the existing /usr/local/<blah_blah>/include/opencv4/opencv2/core/eigen.hpp file (OpenCV 4.2.0) on my machine, and sadly, it does not say anything about the #include order! ¯\_(ツ)_/¯
73,806,740
73,806,776
Parsing a text file with a tab delimiter
I need to parse this text file that has essentially four strings separated by a tab. I've been researching and trying different methods and I can't quite figure out how to do it. For example, I would need to parse this data: Sandwiches (tab) Ham sandwich (tab) Classic ham sandwich (tab) Available (newline) Sandwiches (tab) Cheeseburger (tab) Classic cheeseburger (tab) Not available (newline) And I would read "sandwiches," "Ham sandwich," "Classic ham sandwich," and "available" all into separate variables for each line in the .txt file. I've tried using string.find() and string.substr() to find the tab delimiter and then read the characters up until that delimiter but it all goes wrong and either throws an out of range error, prints nothing, or just prints the entire line into one variable. Any help would be appreciated. EDIT: So I tried @john 's idea with the basic approach to test if it would work. I printed just category to see if it had read the right variable into it and it prints the whole file instead. My Code: #include <fstream> #include <iostream> #include <string> using namespace std; int main() { ifstream inFS; string category, name, desc, avail; inFS.open("food.txt"); if (!inFS.is_open()) { cout << "food.txt." << endl; } getline(inFS, category, '\t'); getline(inFS, name, '\t'); getline(inFS, desc, '\t'); getline(inFS, avail, '\n'); cout << category; //cout << name << " (" << category << ") " << " -- " << desc << " -- " << //avail << endl; inFS.close(); return 0; } Results from printing "category":
Simple way is getline(in, a, '\t'); getline(in, b, '\t'); getline(in, c, '\t'); getline(in, d, '\n'); where a, b, c, and d are std::string variables and in is your input stream. Better would be a little rudimentary error handling if (getline(in, a, '\t') && getline(in, b, '\t') && getline(in, c, '\t') && getline(in, d, '\n')) { // ok } else { // something went wrong }
73,807,728
73,807,762
Get quotient and residue from a division executing just one operation
I need to know how can i get quotient and residue from a division executing just one operation, using python or c++.
quotient, reminder = divmod(10, 3) print(quotient, reminder) # 3 1 https://docs.python.org/3/library/functions.html#divmod
73,808,479
73,834,333
Can I use C++20 `std::atomic<T>::wait()` or `std::atomic_flag::wait()` in shared memory?
My project involves a plugin, and a GUI for said plugin which is isolated into a separate process. The data I'm sharing may be updated by the GUI, and when it is, it should be processed by the plugin. To do this, I'm considering putting this in my shared-memory block: std::atomic_bool event_flag; // insert mutex... some_data_struct data; In essence, the GUI does the following when it wants to change the data: // acquire mutex // write data... // release mutex event_flag = true; event_flag.notify_one(); Then the plugin does the following: event_flag.wait(true); event_flag = false; // acquire mutex // read data... // release mutex
The C++ standard never specified how C++ code interacts with shared memory and processes, so much of this is implementation-defined. However, it seems that implementations are not cross-process: libstdc++ seems to use futexes and/or condition variables with tables. Condition variables are likely not shared across processes, but I haven't bothered to check. Microsoft's STL uses futexes, which cannot work across processes. libc++ is likely similar, and I have not bothered checking. There is a proposal for process management, but that hasn't gone too far, given that the C++ standard doesn't have a concept of "processes". I will edit this answer if such behaviour is eventually specified.
73,808,816
73,808,848
Thread-safe stack implementation
"C++ Concurrency in Action second edition" has an example of thread-safe stack implementation, and the following is the code for pop: template <typename T> std::shared_ptr<T> threadsafe_stack<T>::pop() { std::lock_guard<std::mutex> lock(m); // `data` is a data member of type `std::stack<T>` if(data.empty()) throw empty_stack(); // <--- 2 std::shared_ptr<T> const res( std::make_shared<T>(std::move(data.top()))); // <--- 3 data.pop(); // <--- 4 return res; } The book has the following explanation for this code: The creation of res (3) might throw an exception, though, for a couple of reasons: the call to std::make_shared might throw because it can’t allocate memory for the new object and the internal data required for reference counting, or the copy constructor or move constructor of the data item to be returned might throw when copying/moving into the freshly- allocated memory. In both cases, the C++ runtime and Standard Library ensure that there are no memory leaks and the new object (if any) is correctly destroyed. Because you still haven’t modified the underlying stack, you’re OK. Does this explanation correct? If data item's move constructor throws, and the data item is corrupted. Although this implementation avoid memory leak, the state of the stack has been damaged/modified (not strong exception safe), and latter read will get corrupted data. Right? So it seems that this implementation works, only if the move constructor doesn't throw (or at least, even if it throws, it keeps the data item unmodified)?
It is assumed that the if the move constructor of T throws an exception it will make sure that the original object remains in its original state. That is a general exception guarantee that move operations should satisfy, otherwise it is trivially impossible to make any guarantees about exception safety when the move operation is used. If that is not supposed to be a precondition on the element type, the copy constructor can be used instead of the move constructor if the move constructor is not noexcept. The copy constructor should never modify the original object. There is std::move_if_noexcept as a replacement for std::move in the standard library to implement this behavior. Obviously if the type is not copyable and the move constructor not noexcept we are back again at the original problem and then it will simply be impossible to make exception guarantees if T's move constructor doesn't make any.
73,809,029
73,809,214
C++ Major syntax error? (12 Duplicate Symbols for architecture x86_64)
Apologies for my ignorance. I'm relatively new to C++ from another language. I'm making a program to rank poker hands for an assignment and I'm hitting an error that I don't understand but I'm assuming is a major syntax error. Please be nice, I'm trying to learn. This will not build in Xcode. When I try, I get the following error message: 12 Duplicate Symbols for architecture x86_64 I am really confused by this error. Here is my code: poker.hpp #ifndef poker_hpp #define poker_hpp #include <stdio.h> #include <iostream> #include <array> #include <string> #include <algorithm> #include <vector> using namespace std; const size_t HAND_ARRAY_SIZE = 5; const size_t CARD_ARRAY_SIZE = 2; //just in case, might not use it typedef array<string, HAND_ARRAY_SIZE> hand_t; //typedef for poker hands typedef array<string, CARD_ARRAY_SIZE> card_t; //just in case, might not use it const size_t SUIT_ARRAY_SIZE = 4; static array<string, SUIT_ARRAY_SIZE> suits = {"C", "D", "H", "S"}; const size_t VALUE_ARRAY_SIZE = 13; static array<string, VALUE_ARRAY_SIZE> ranks_ace_high = {"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"}; static array<string, VALUE_ARRAY_SIZE> ranks_ace_low = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}; const size_t HAND_RANK_ARRAY_SIZE = 10; //EDIT: added static static array<string, HAND_RANK_ARRAY_SIZE> handRanks = { "high card", "pair", "two pair", "three of a kind", "straight" "flush", "full house", "four of a kind", "straight flush", "royal flush" }; class Hand { private: hand_t cards; string type(); float value(); bool acesLow(); public: Hand(hand_t cards); }; #endif /* poker_hpp */ test_hands.cpp #include "poker.hpp" hand_t test0 {"TC", "9C", "8C", "7C", "6C"}; hand_t test1 {"8H", "7H", "6H", "5H", "4H"}; hand_t test2 {"8H", "7H", "6H", "5H", "4H"}; hand_t test3 {"6S", "5S", "4S", "3S", "2S"}; hand_t test4 {"7D", "6D", "5D", "4D", "3D"}; hand_t test5 {"7S", "6S", "5S", "4S", "3S"}; hand_t test6 {"KS", "KH", "KC", "KD", "3H"}; hand_t test7 {"7H", "7D", "7S", "7C", "QH"}; hand_t test8 {"7H", "7D", "7S", "7C", "QH"}; Hand.cpp #include "poker.hpp" Hand::Hand(hand_t cards){ this->cards = cards; } main.cpp #include "poker.hpp" #include "test_hands.cpp" int main() { Hand hand(test0); };
There are/were two problems. When you include a file the include directive is effectively replaced with the contents of the named file during the preprocessing phase. This makes one big file containing the contents of the source file and all of the included headers and all of the headers included by other headers that is compiled. This means you have to be careful when you define something in a header file: Everyone including the header will have its own copy of the definition and this will violate the One Definition Rule unless you take extra steps to lock the definition in the translation unit being compiled (static linking or anonymous namespaces) or tell the compiler that all of the duplicates will be identical (inline functions). In the poker.hpp, array<string, HAND_RANK_ARRAY_SIZE> handRanks = { ... }; was not static or bound inside an anonymous namespace so every including source file all had a handRanks object defined and when the linker put everything together it found all of the handRanks and refused to proceed. The second problem was main.cpp included test_hands.cpp. This duplicated everything in test_hands.cpp in main.cpp. The IDE sent test_hands.cpp and main.cpp to the compiler and the output of each source contained everything defined in test_hands.cpp leading to more multiple definitions. Do not include a cpp file. Compile and link them instead. Anything in test_hands.cpp that needs to be exposed to or shared by other files should be declared in a header that is included by other source files. extern will help here. That said in this case, just build the test data into main.cpp. There is no good reason to separate the test data from the test driver unless it's huge or complicated and you want to compile it as little as possible. Tactical note: All class members and base classes are fully initialized before entering the body of the constructor. This means that in Hand::Hand(hand_t cards){ this->cards = cards; } member cards is default initialized (which in turn default initializes HAND_ARRAY_SIZE strings) and then the member cards is overwritten with the parameter cards, rendering the initialization wasted effort. A good optimizing compiler may spot this waste and eliminate it, but instead you can take advantage of the Member Initializer List and make life easier for the compiler by stating exactly the behaviour you want. Hand::Hand(hand_t cards): cards(cards){ } Member cards is now copy-initialized with parameter cards. Note we also get to reuse the name cards without ambiguity. This is important when you have a data structure with expensive default initialization that a compiler cannot easily eliminate and it utterly vital when a base class or member variable cannot be default initialized.
73,810,105
73,818,662
npm config set msvs_version does not work? (node-gyp)
npm config set msvs_version does not work and I still get msvs_version not set from command line or npm config. I have all the necessary paths set and I have Visual Studio 2017, 2019 and 2022 installed with the necessary C++ thingys. Full error: gyp info using node-gyp@6.1.0 gyp info using node@16.17.0 | win32 | x64 gyp info find Python using Python version 3.10.7 found at "C:\Python310\python.exe" gyp ERR! find VS gyp ERR! find VS msvs_version not set from command line or npm config gyp ERR! find VS running in VS Command Prompt, installation path is: gyp ERR! find VS "C:\Program Files\Microsoft Visual Studio\2022\Community" gyp ERR! find VS - will only use this version gyp ERR! find VS unknown version "undefined" found at "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools" gyp ERR! find VS unknown version "undefined" found at "C:\Program Files\Microsoft Visual Studio\2022\Community" gyp ERR! find VS checking VS2019 (16.11.32901.82) found at: gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community" gyp ERR! find VS - found "Visual Studio C++ core features" gyp ERR! find VS - found VC++ toolset: v142 gyp ERR! find VS - found Windows SDK: 10.0.19041.0 gyp ERR! find VS - does not match this Visual Studio Command Prompt gyp ERR! find VS checking VS2019 (16.11.32901.82) found at: gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools" gyp ERR! find VS - found "Visual Studio C++ core features" gyp ERR! find VS - found VC++ toolset: v142 gyp ERR! find VS - found Windows SDK: 10.0.18362.0 gyp ERR! find VS - does not match this Visual Studio Command Prompt gyp ERR! find VS checking VS2017 (15.9.28307.2094) found at: gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community" gyp ERR! find VS - found "Visual Studio C++ core features" gyp ERR! find VS - found VC++ toolset: v141 gyp ERR! find VS - missing any Windows SDK gyp ERR! find VS checking VS2017 (15.9.28307.2094) found at: gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools" gyp ERR! find VS - found "Visual Studio C++ core features" gyp ERR! find VS - found VC++ toolset: v141 gyp ERR! find VS - found Windows SDK: 10.0.17763.0 gyp ERR! find VS - does not match this Visual Studio Command Prompt gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use gyp ERR! find VS looking for Visual Studio 2015 gyp ERR! find VS - not found gyp ERR! find VS looking for Visual Studio 2013 gyp ERR! find VS - not found gyp ERR! find VS gyp ERR! find VS ************************************************************** gyp ERR! find VS You need to install the latest version of Visual Studio gyp ERR! find VS including the "Desktop development with C++" workload. gyp ERR! find VS For more information consult the documentation at: gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows gyp ERR! find VS ************************************************************** gyp ERR! find VS gyp ERR! configure error gyp ERR! stack Error: Could not find any Visual Studio installation to use
Fixed I found the dependency that was causing this error uninstalled it using npm uninstall <dependency-name> I redownloaded it as a devDependency with the npm install <dependency-name> -save-dev. This fixed my issue for now but I do not know if this is a long term solution, I'll probably update this answer when I get to the phase of packaging the app.
73,810,381
73,810,443
Visual Studio - Create exe inclusive of ssh.dll
I have built a simple program in Visual Studio, as per the below. #define LIBSSH_STATIC 1 #include <libssh/libssh.h> #include <iostream> #include <stdlib.h> int main() { std::cout << "Hello World!\n"; ssh_session my_ssh_session; int verbosity = SSH_LOG_PROTOCOL; int port = 22; my_ssh_session = ssh_new(); if (my_ssh_session == NULL) exit(-1); ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "10.10.10.100"); ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity); ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port); ssh_free(my_ssh_session); } For the Lisssh library, I have downloaded the code from here: https://github.com/ShiftMediaProject/libssh/releases ...and added the library to Visual Studio, following the instructions here How to manually add a library to a visual studio 2017 project? The library works and the program compiles, my only issue is that in order for it to work I have to manually copy a file called ssh.dll into the folder where the program executes from. I have tried in Visual Studio setting C/C++, Code Generation -> Multi-threaded (/MT) to statically link the library, but the DLL is not getting included. How can I create a single executable, that includes the ssh.dll? Thanks
A .dll is a Dynamic Link Library; it's not meant to be included in an .exe. There are ways, but they are ugly and difficult. The "proper" and easier way is to build libssh as a static library instead; this will give you a .lib file that you can add to your .exe easily. It looks like the downloads you used already contain these .lib files. Just add the libssh.lib file to your project, and omit the ssh.lib (which is just an import library for the .dll, as you can tell from the size of the file).
73,810,611
73,814,980
Modification of objects in constant expression contexts
Consider the following code: struct S { constexpr S(){}; constexpr S(const S &r) { *this = r; }; constexpr S &operator=(const S &) { return *this; }; }; int main() { S s1{}; constexpr S s2 = s1; // OK } The above program is well-formed but I'm expecting it to be ill-formed, because [expr.const]/(5.16) says: An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following: [..] (5.16) a modification of an object ([expr.ass], [expr.post.incr], [expr.pre.incr]) unless it is applied to a non-volatile lvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of E; [..] Given the expression E is s1. The expression E evaluates a modification of the object *this. The modification is applied to the non-volatile lvalue *this which is of literal type, and this lvalue refers to a non-volatile object which is s1 but the lifetime of s1 does not begin within the evaluation of E: That's the lifetime of the object s1 began before the evaluation of the expression E. So I'm expecting the program is ill-formed because the "unless" part does not satisfy which means, to me, that the expression E is not a core constant expression. So what I'm missing here? Am I misreading (5.16)?
As Language Lawyer points out, there are no modifications in your program, however even if the constructor did modify s2, this wouldn't necessarily make the program ill-formed, because: In any constexpr variable declaration, the full-expression of the initialization shall be a constant expression ([expr.const]). -- [dcl.constexpr]/7 The constructor is allowed to modify s2 because the lifetime of s2 begins within the full-expression of the initialization, and only the full-expression of the initialization is required to be a constant expression (not the initializer in isolation). Addendum: The only modifications that are relevant for [expr.const]/5.16 are modifications to scalar objects. This is because only modifications to scalar objects actually result in accesses to the memory of the abstract machine (see also defns.access). When I say the constructor is allowed to modify s2, I mean the constructor is allowed to modify scalar subobjects of s2.
73,812,404
73,813,524
Confused on which variables should be shared or private in nested OpenMP loop
I have a nested loop and im confused on which variables should be shared or private. I believe that i and j should be private but im confused on whether other variables also need to be shared or privated in my code: y = p->yMax; #pragma omp parallel for private(i,j) for (i = 0; i < p->height; i++) { x = p->xMin; for (j = 0; j < p->width; j++) { p->carray[i * p->width + j] = x + y * I; x += p->step; } y -= p->step; } for (i = 0; i < p->maxIter; i++) { p->histogram[i] = 0; } } Cheers
Assuming that you do not need the values of i and j after the loops and observing that you reset i and j to zero at the beginning of the loops, I would simply define the i and j within the loop. If so, you don't have to state the behaviour of i and j when entering and exiting the loop (because it is automatically private). I think that the value of x before entering the loop is not needed as well, so you can also go for private here or define x as a local varieble. If y is treated similar as x and has to be reset to p->yMax in every step, you can either declare y as private and move into the loop, same as x. Or you have to declare y as firstprivate such that the previous value is not lost when entering the parallel region. Using shared is not an option for both x and y since you += and -= change the value of these variables. p should be shared, as you need the values of p->xMin, p->step and p->yMax and you probably also want to use the values of p->carray after exiting the loop. `` #pragma omp parallel for shared(p) for (size_t i = 0; i < p->height; i++) { auto x = p->xMin; auto y = p->yMax; for (size_t j = 0; j < p->width; j++) { p->carray[i * p->width + j] = x + y * I; x += p->step; } y -= p->step; } //This one isn't in the parallel region for (size_t i = 0; i < p->maxIter; i++) { p->histogram[i] = 0; }
73,812,999
73,813,564
There is no byte type in c. But I found byte type in programming
I am trying to learn I2C from this website https://forum.dronebotworkshop.com/arduino/i2c-part-one-tutorial-and-slave-demo-sketch-for-platformio/. In the website section "Slave Demo Sketch" (Arduino), there is one line code that I don't understand. What is type of Byte? What does the byte inside the brackets mean? for (byte i=0; i<ANSWERSIZE; i++) { response[i] = (byte)answer.charAt(i); }
First of all, type naming is somewhat subjective, though wide consensus exists. Various sketchy, home-brewed types tend to exist in some libraries. byte, BYTE, U8 and other such non-standard types. These are almost always just some flavour of typedef unsigned char slop;, which is a completely useless typedef. Some of the cornerstones of good programming practices: follow formal ISO standards or at least industry "de facto" standards and don't invent your personal non-standard don't complicate things just for the heck of it Weird typedefs like byte go against both of these practices. In addition "I don't like typing" isn't a valid argument - programming is all about typing, those who don't like it or who can't figure out how copy/paste or code completion works picked the wrong trade. Besides, if you can't type uint8_t in around 1 second, it might be an indication that you need to practice typing on a keyboard way more, at least if you are serious about the programmer trade. The only time when you should be using such non-standard types is when the existing code base is truly hellbent on using them and a lot of code like that has already been written. Using a different, although more correct type might just make the code more confusing at that point. Good practice is to use the standardized types whenever possible, instead of inventing your own non-standard. Some rules of thumb of below: Acceptable byte types: uint8_t (highly recommended) unsigned char Acceptable boolean types: bool with false and true (highly recommended) _Bool with false and true (C only, not C++)
73,813,011
73,813,110
train_test_split function in C++
I would like to create a train_test_split function that splits a matrix (vector of vectors) of data into two other matrices, similar to what sklearn's function does. This is my attempt in doing so: #include <iostream> #include <cstdlib> #include <fstream> #include <time.h> #include <vector> #include <string> using namespace std; vector<vector<float>> train_test_split(vector<vector<float>> df, float train_size = 0.8){ vector<vector<float>> train; vector<vector<float>> test; srand(time(NULL)); for(int i = 0; i < df.size(); i++){ int x = rand() % 10 + 1; if(x <= train_size * 10){ train.push_back(df[i]); } else{ test.push_back(df[i]); } } return train, test; } int main(){ vector<vector<float>> train; vector<vector<float>> test; vector<vector<float>> df = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}}; train, test = train_test_split(df); cout << "training size: " << train.size() << ", test size: " << test.size() << endl; return 0; } This approach sends data only in the test matrix. After some research, I have discovered that C++ cannot output two values in the same function. I am very new in C++, and I am wondering what would be the best way to approach this. Any help will be appreciated.
A function can only return one value. Though look at your function declaration: It is declared to return a vector<vector<float>>, and thats a container of many vector<float>s. Containers can contain many elements (of same type) and custom types can contain many members: struct train_test_split_result { vector<vector<float>> train; vector<vector<float>> test; }; train_test_split_result train_test_split(vector<vector<float>> df, int train_size = 0.8) { train_test_split_result result; // ... // result.train.push_back(...) // result.test.push_back(...) // ... return result; } int main(){ vector<vector<float>> df = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}}; train_test_split_result result = train_test_split(df); cout << "training size: " << result.train.size() << ", test size: " << result.test.size() << endl; } PS: You should turn up your compilers warnings and read them! Then read this: How does the Comma Operator work PPS: A nested vector is a terrible data structure for a matrix. std::vector benefits a lot from memory locality, but because its elements are dynamically allocated, the floats in a std::vector<std::vector<float>> are scattered around in memory. If the size is known at compile time and not too big (that it would require dynamic allocation) you can use a nested array. Alternatively use a flat std::vector<float> to store the matrix. PPPS: There are also "out paramters": The function can have arguments by non-const reference, the caller passes them and the function modifies them. Though generally out-parameters are not recommended.
73,813,309
73,813,405
C++ Only accept a set of types for template parameter pack
To limit a template parameter pack to a certain type, this can be done in the following way: std::enable_if_t<std::conjunction_v<std::is_same<int32_t, Ts>...>> send(bool condition, Ts...); I would actually allow int32_t and std::string and any order. How can this be expressed? I had a workaround using a variant, but this does not look so nice to me: using allowed_types = std::variant<int32_t, std::string>; template<typename... Ts> std::enable_if_t<std::conjunction_v<std::is_assignable<allowed_types, Ts>...>> send(bool condition, Ts...); And this does not compile: std::enable_if_t<std::conjunction_v<std::is_same<int32_t, Ts> || std::is_same<std::string, Ts>...>> // <- does not compile! send(bool condition, Ts...);
You are using std::conjunction as a replacement for && on the std::bool_constant level correctly, but then you should in the same way replace || with std::disjunction: std::enable_if_t<std::conjunction_v<std::disjunction<std::is_same<int32_t, Ts>, std::is_same<std::string, Ts>>...>> or with C++17 you can use fold expressions on the level of bool values instead: std::enable_if_t<((std::is_same_v<int32_t, Ts> || std::is_same_v<std::string, Ts>) && ...)>> (Outer parentheses are required by the fold expression syntax.) Of course with C++20 this can be done much nicer with the help of concepts: template<typename T> concept Int32OrString = std::same_as<T, int32_t> || std::same_as<T, std::string>; void send(bool condition, Int32OrString auto...); or even template<typename T, typename... Ts> concept AnyOf = (std::same_as<T, Ts> || ...); void send(bool condition, AnyOf<int32_t, std::string> auto...);
73,813,349
73,813,908
C++ 2d array using vectors returns a consistent incorrect result on the second query
I'm doing a coding challenge where the aim is to take x arrays and query it y times. Each array is given a size (N) and a list of values and each query wants a specific value (b) from a specific array (a). The input is given as follows: X Y N n n n ... N n n n ... a b a b Here is all of my code: #include <vector> #include <iostream> using namespace std; int main() { int numArrays; int numQueries; scanf("%d %d", &numArrays, &numQueries); vector<int*> arrays; for (int i = 0; i < numArrays; i++) { int size; scanf("%d", &size); int arr[size]; for (int j = 0; j < size; j++) { scanf("%d", &arr[j]); } arrays.push_back(arr); } for (int i = 0; i < numQueries; i++) { int arr, ind; scanf("%d %d", &arr, &ind); printf("%d\n", arrays.at(arr)[ind]); } return 0; } The test input is 2 arrays and 2 queries given as follows: 2 2 3 1 2 3 5 9 8 7 6 5 0 1 1 3 The expected output should give 2 for the first query (which seems to be working fine) and then 6 for the second query however my actual output is this: 2 32767 Does anybody know why the second output comes out as 32767. This seems to be a consistent value no matter what the arrays contain or what the second query is looking for. I think it's likely something to do with my vector declaration but I'm still relatively new to C++ so I'm not sure.
The problem has been already described in comments by others: You are storing a pointer to an array on the stack that will be undefined outside the for loop. Just use vectors for both array dimensions and let them handle pointers and memory allocations for you: #include <iostream> #include <utility> #include <vector> int main() { size_t numArrays, numQueries; std::cin >> numArrays >> numQueries; std::vector<std::vector<int>> arrays; arrays.reserve(numArrays); for (size_t i = 0; i < numArrays; ++i) { size_t size; std::cin >> size; std::vector<int> array; array.reserve(size); for (size_t j = 0; j < size; ++j) { int number; std::cin >> number; array.push_back(number); } arrays.push_back(std::move(array)); } for (size_t i = 0; i < numQueries; ++i) { size_t arr, ind; std::cin >> arr >> ind; std::cout << arrays[arr][ind] << std::endl; } } Admittedly, this lacks even the most basic error checking and error handling; it is simply a rewrite of the code from the question. Of course you can handle the memory allocations yourself, but in that case you also need to make sure things get properly deallocated. (Again, the following example lacks error checking.) #include <iostream> #include <memory> #include <utility> int main() { size_t numArrays, numQueries; std::cin >> numArrays >> numQueries; const auto arrays{ std::make_unique_for_overwrite<std::unique_ptr<int[]>[]>(numArrays)}; for (size_t i = 0; i < numArrays; ++i) { size_t size; std::cin >> size; arrays[i] = std::make_unique_for_overwrite<int[]>(size); for (size_t j = 0; j < size; ++j) std::cin >> arrays[i][j]; } for (size_t i = 0; i < numQueries; ++i) { size_t arr, ind; std::cin >> arr >> ind; std::cout << arrays[arr][ind] << std::endl; } }
73,813,446
73,983,335
apt.llvm.org clang-15 is not able to compile with C++17 feature std::execution::par
for cross-reference: i asked also at llvm-bug-tracker: https://github.com/llvm/llvm-project/issues/57898 Steps to reproduce: Ubuntu with clang from apt.llvm.org and with potential pstl backends installed via libtbb2-dev and clang-15-openmp is not able to compile with C++17 feature std::execution::par. Dockerfile: FROM ubuntu:22.04 RUN apt-get update && apt-get -y install \ software-properties-common gpg wget \ make libssl-dev RUN apt-get install -y build-essential libthrust-dev libtbb2-dev libtbb2 # https://apt.llvm.org/ RUN wget https://apt.llvm.org/llvm.sh && \ chmod +x llvm.sh && \ ./llvm.sh 15 all ENV PATH=$PATH:/usr/lib/llvm-15/bin RUN echo "\ \n#include <execution> \n \ \n#include <algorithm> \n \ \n#include <vector> \n \ int main(void) { \n \ std::vector<float> images = {1,2,3,4,5}; \n \ std::vector<float> results; \n \ results.resize(images.size()); \n \ std::transform(std::execution::par, images.begin(), images.end(), results.begin(), [](const auto &input){ return input; }); \n \ }" > hello.cpp RUN clang -std=c++17 -stdlib=libc++ hello.cpp -o hello && ./hello produces following error: hello.cpp:11:26: error: no member named 'execution' in namespace 'std'; did you mean 'exception'? std::transform(std::execution::par, images.begin(), images.end(), results.begin(), [](const auto &input){ return input; }); ~~~~~^~~~~~~~~ exception /usr/lib/llvm-15/bin/../include/c++/v1/exception:100:29: note: 'exception' declared here class _LIBCPP_EXCEPTION_ABI exception ^ hello.cpp:11:37: error: no member named 'par' in 'std::exception' std::transform(std::execution::par, images.begin(), images.end(), results.begin(), [](const auto &input){ return input; }); ~~~~~~~~~~~~~~~~^ 2 errors generated. The command '/bin/sh -c clang -std=c++17 -stdlib=libc++ hello.cpp -o hello && ./hello' returned a non-zero code: 1 Nevertheless, godbold shows that clang-15 should be possible to compile so: https://godbolt.org/z/3TxoWEMxb Am i am missing something ubuntu specific here, or do i really have to compile the llvm-stack myself because of potentially missing pstl flag of apt.llvm.org shipped packages?
The problem is not related to compilers, but to implementations of the C++ standard library. According to the compiler suppor table as well as libc++ documentation, libc++ is still missing the support for C++17 parallel algorithms and execution policies. On Godbolt, Clang uses libstdc++ by default. That's why it compiles, even with Clang. With using libc++ instead, the compilation will fail. Live demo: https://godbolt.org/z/dMPP7sssa.
73,813,667
73,931,350
Valgrind detects memory leaks in MKL/LAPACK STEVR function for eigenvalue problems with matrix sizes above a threshold
I am working on software that uses the Intel MKL implementation of LAPACK functions for eigenvalue problems. When I ran Valgrind to check the code for memory leaks it reported errors only when using the function 'STEVR', or more precisely the C-funtion LAPACKE_dstevr. In order to find out if my interface is the problem or the called function, I wrote an isolated test application. The code looks like this: #include <mkl/mkl.h> #include <random> int main() { // Tolerance double absTol = 1e-12; // Problem size lapack_int n = 64; // Generate random tridiagonal symmetric matrix std::mt19937 randomGen; std::normal_distribution<double> normal(1., 1.); double *mainDiagonal = new double[n]; double *subDiagonal = new double[n-1]; for (int i=0; i<n-1; i++) { mainDiagonal[i] = normal(randomGen); subDiagonal[i] = normal(randomGen); } mainDiagonal[n-1] = normal(randomGen); // Allocate memory for results double *eigenValues = new double[n]; double *eigenVectors = new double[n*n]; // Resulting integer array and integer for leading dimension // allocated/initialized according to MKL/LAPACK documentation lapack_int *isuppz = new lapack_int[2*n](); lapack_int ldz = n; // Eigenvectors shall be computed char job = 'V'; // All pairs of eigenvalues and -vectors shall be computed char range = 'A'; // These values can remain uninitialized (irrelevant it range=='A') lapack_int lowerIndex, upperIndex, upperBound, lowerBound; // Number of eigenvalues found (output parameter) lapack_int m; // Solve problem using MKL/LAPACK function LAPACKE_dstevr(LAPACK_ROW_MAJOR, job, range, n, mainDiagonal, subDiagonal, lowerBound, upperBound, lowerIndex, upperIndex, absTol, &m, eigenValues, eigenVectors, ldz, isuppz); // Free memory delete[] mainDiagonal; delete[] subDiagonal; delete[] eigenValues; delete[] eigenVectors; delete[] isuppz; return 0; } Compiling it with g++ -fopenmp -ggdb3 -Wall -Wextra test_dstevr.cpp -lmkl_intel_lp64 -lmkl_core -lmkl_gnu_thread -lpthread -lm -ldl -lmkl_rt -o test_dstevr and running valgrind with the command valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind.out ./test_dstevr gives me 0 errors. If I change the size of the matrix to n = 65 or any number greater than 64, however, Valgrind reports ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) and ==48382== 960 bytes in 3 blocks are possibly lost in loss record 10 of 12 ==48382== at 0x483DD99: calloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) ==48382== by 0x40149DA: allocate_dtv (dl-tls.c:286) ==48382== by 0x40149DA: _dl_allocate_tls (dl-tls.c:532) ==48382== by 0xB549322: allocate_stack (allocatestack.c:622) ==48382== by 0xB549322: pthread_create@@GLIBC_2.2.5 (pthread_create.c:660) ==48382== by 0xB320DEA: ??? (in /usr/lib/x86_64-linux-gnu/libgomp.so.1.0.0) ==48382== by 0xA08AA10: mkl_trans_mkl_domatcopy2_par (in /usr/lib/x86_64-linux-gnu/libmkl_gnu_thread.so) ==48382== by 0xCF5D5F4: mkl_trans_avx2_mkl_domatcopy (in /usr/lib/x86_64-linux-gnu/libmkl_avx2.so) ==48382== by 0x4D76FBC: LAPACKE_dge_trans (in /usr/lib/x86_64-linux-gnu/libmkl_intel_lp64.so) ==48382== by 0x4DB57DB: LAPACKE_dstevr_work (in /usr/lib/x86_64-linux-gnu/libmkl_intel_lp64.so) ==48382== by 0x4DB5430: LAPACKE_dstevr (in /usr/lib/x86_64-linux-gnu/libmkl_intel_lp64.so) ==48382== by 0x10951C: main (test_dstevr.cpp:45) Of course, being a power of two, the number 64 does not seem random to me, but I have absolutely no idea what the problem might be. Does anybody here? I am using Ubuntu 20.04 LTS and GCC 9.4.0.
Here is the solution for anyone else with a similar issue. Try using the latest oneMKL version 2022.2.0 which is now available for download and here is the command with Intel oneAPI compilers icpx -ggdb3 -I"${MKLROOT}/include" test_dstevr.cpp -L${MKLROOT}/lib/intel64 -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread -lm -ldl -o test_dstevr After compiling, try running Valgrind with the below command and we see no issues now valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind.out ./test_dstevr
73,813,823
73,814,440
Postgres: How to use variables in create functions constructions?
I want to load functions from my shared library. To do this, I specify the path to the library after AS and I want to do it using a variable. But the value is not substituted in this way. How can this be done ? DO $$ DECLARE pathToLib text := '/path/to/lib/myPostgresFunctionsLib.so'; BEGIN CREATE OR REPLACE FUNCTION someFunction() RETURNS text AS pathToLib, 'someFunction' LANGUAGE C; END $$; It returns: ERROR: syntax error at or near "pathToLib" LINE 6: AS pathToLib, 'someFunction'
You need dynamic SQL: DO $$DECLARE pathToLib text := '/path/to/lib/myPostgresFunctionsLib.so'; BEGIN EXECUTE format( $_$CREATE OR REPLACE FUNCTION someFunction() RETURNS text AS %L, 'someFunction' LANGUAGE C$_$, pathToLib ); END;$$; format() will replace %L with the value of pathToLib, correctly escaped as a string literal.
73,813,836
73,814,409
return a reference to an array with templated size
I am trying a function's return value to be to a reference to an array whose size is variable (i.e. templated). The code I have is: const char *strarr[] = { "one", "two", "three" }; template <std::size_t T> const char* (&GetArr())[T] { return strarr; } The reason I want to do it this way: it would be convenient in my case to then use in a a loop such that: for (const auto& s : GetArr()) { std::cout << s << std::endl; } but this wouldn't compile. the only way to use it is to specify the size in GetArr(); but I was wondering why it can't deduce the size by itself, as it would have if I passed a reference to this array as a parameter to a templated function, as in: template <std::size_t T> void PrintArray(const char* (&arr)[T]) { for (const auto& s : arr) { std::cout << s << std::endl; } } which does work.
There is no template argument deduction from return statements and T cannot be deduced from any function parameter/argument pair. So you will have to specify the size manually, but that is not a problem, since you need to specify the array that is returned anyway, so that the only possible choice is const char* (&GetArr())[std::size(strarr)] { return strarr; } That said, there is return type deduction via type placeholders which you can make use of here easily: auto& GetArr() { return strarr; } Note that in both cases the function is not a function template. There aren't multiple different instantiations that would make sense for it. There is only one possible size that makes sense, one possible return type and one possible function body. Therefore template <std::size_t T> doesn't really make sense to begin with. However, it is much simpler to just use std::array instead of built-in arrays. The former doesn't require you to take care of special language rules or weird declaration syntax as in the first example. There is also no need to write PrintArray so restrictively. You can instead write template <typename R> void PrintRange(const R& r) { for (const auto& s : r) { std::cout << s << std::endl; } } and now you have a function that will work with any range, whether built-in array, std::array, std::vector, std::list, etc.
73,813,868
73,814,104
printing the bits of float
I know. I know. This question has been answered before, but I have a slightly different and a bit more specific question. My goal is, as the title suggest, to cout the 32 bits sequence of a float. And the solution provided in the previous questions is to use a union. union ufloat{ float f; uint32_t u; }; This is all good and well. And I have managed to print the bits of a floating number. union ufloat uf; uf.f = numeric_limits<float>::max(); cout << bitset<32>(uf.f) << "\n"; // This give me 0x00000000, which is wrong. cout << bitset<32>(uf.u) << "\n"; // This give me the correct bit sequence. My question is why does bitset<32>(uf.f) doesn't work, but bitset<32>(uf.u) does? The green-ticked anwser of this question Obtaining bit representation of a float in C says something about "type-punning", and I presume it's got something to do with that. But I am not sure how exactly. Can someone please clearify? Thanks
The constructor of std::bitset you are calling is: constexpr bitset( unsigned long long val ) noexcept; When you do bitset<32>(uf.f), you are converting a float to an unsigned long long value. For numeric_limits<float>::max(), that's undefined behavior because it's outside the range of the destination type, and in your case it happened to produce zero. When you do bitset<32>(uf.u), you are again relying on undefined behavior, and in this case it happens to do what you want: convert a uint32_t that contains the bits of a float to an unsigned long long value. In C++, what you should do instead is use memcpy: uint32_t u; std::memcpy(&u, &uf.f, sizeof(u)); std::cout << std::bitset<32>(u) << "\n";
73,814,012
73,814,508
Override a base class member in derived class C++
I can't seem to overwrite the base class member (Painting) value for the derived class FamousPainting. Things I have tried: virtual function creating new setter function in derived class change derived class constructor signature I am at a loss of what to do now #include <iostream> #include <string> #include <vector> using namespace std; class Painting { protected: string title; string artist; int value; public: Painting(); Painting(string, string); // copy constructor Painting(string,string,int); void showPainting(); void setData(); string getTitle(); string getArtist(); int getValue(); //virtual void setValue(); }; Painting::Painting() { } Painting::Painting(string name, string painter) { name = title; artist = painter; value = 400; } Painting::Painting(string _title,string _artist, int _value) { title = _title; artist = _artist; value = _value; } void Painting::setData() { cout << "Enter painting's title: "; cin >> title; cout << "Enter artist: "; cin >> artist; value = 400; } /* void Painting::setValue() { value = 400; } */ void Painting::showPainting() { cout << title << " done by " << artist << " cost $" << value << endl; } string Painting::getTitle() { return title; } int Painting::getValue() { return value; } string Painting::getArtist() { return artist; } class FamousPainting: public Painting { private: Painting painting; public: FamousPainting(string, string,int); //void setValue(); }; FamousPainting::FamousPainting(string name, string painter, int val) : painting(name,painter,val) {} /* void FamousPainting::setValue() { this->value = 25000; } */ bool isPaintingFamous(Painting &p) { bool isFamous = true; const int NUM = 4; string artists[NUM] = {"Degas","Monet","Picasso","Rembrandt"}; int x; for(x = 0; x < NUM; x++) if(p.getArtist() != artists[x]) isFamous = false; return isFamous; } int main() { vector<Painting> listofpainting; vector<FamousPainting> listoffpainting; for(int i = 0; i < 2; i++) { Painting temp; temp.setData(); if(isPaintingFamous(temp)) { FamousPainting tempF(temp.getTitle(),temp.getArtist(),25000); listoffpainting.push_back(tempF); } listofpainting.push_back(temp); } for(Painting paint: listofpainting) { paint.showPainting(); } for(FamousPainting fpaint: listoffpainting) { fpaint.showPainting(); } return 0; } The output: Enter painting's title: Hime Enter artist: Mary Enter painting's title: Sophistry Enter artist: Monet Hime done by Mary cost 400 Sophistry done by Monet cost 400 For FamousPainting, I cannot overwrite the value to 25000 which is the requirement of the Lab.
Several issues: class FamousPainting: public Painting // <- Inherits from Painting { private: Painting painting; // <- Contains a Painting called "painting" You should pick one of the two. Either FamousPainting IS a Painting and should inherit, or it CONTAINS a Painting and should not inherit. I suspect you want the inheritance and not the member. This also bites you later in the FamousPainting constructor: FamousPainting::FamousPainting(string name, string painter, int val) : painting(name,painter,val) {} This is a nice delegating constructor, unfortunately it does not actually initialize the FamousPainting itself - instead it only initializes the Painting member it contains. Change it to: : Painting(name,painter,val) {} // <- delegates to the parent class It is a bit subtle because you named the Painting member painting. Next the logic in the isPaintingFamous function is wrong. This is one of the situations where it helps to step through the code with a debugger, so you can see how the variable values change at every step. But basically you start off saying: "This is famous", then you check the names, and as soon as any of them fail, you change your mind and set it to not famous. So a Rembrandt fails the Monet check and then forever stays "not famous".
73,814,832
73,892,602
Could not initialize my i2c_config_t structure
According to the i2C.h as follows: /** * @brief I2C initialization parameters */ typedef struct{ i2c_mode_t mode; /*!< I2C mode */ gpio_num_t sda_io_num; /*!< GPIO number for I2C sda signal */ gpio_pullup_t sda_pullup_en; /*!< Internal GPIO pull mode for I2C sda signal*/ gpio_num_t scl_io_num; /*!< GPIO number for I2C scl signal */ gpio_pullup_t scl_pullup_en; /*!< Internal GPIO pull mode for I2C scl signal*/ union { struct { uint32_t clk_speed; /*!< I2C clock frequency for master mode, (no higher than 1MHz for now) */ } master; struct { uint8_t addr_10bit_en; /*!< I2C 10bit address mode enable for slave mode */ uint16_t slave_addr; /*!< I2C address for slave mode */ } slave; }; }i2c_config_t; I wrote the following assignment: const i2c_port_t i2c_master_port = (i2c_port_t)I2C_MASTER_NUM; i2c_config_t conf = { .mode = I2C_MODE_MASTER, .sda_io_num = I2C_MASTER_SDA_IO, .scl_io_num = I2C_MASTER_SCL_IO, .sda_pullup_en = (gpio_pullup_t)GPIO_PULLUP_ENABLE, .scl_pullup_en = (gpio_pullup_t)GPIO_PULLUP_ENABLE, .master = {.clk_speed = I2C_MASTER_FREQ_HZ}, }; Which reports 2 errors (sorry its in French so I added my own translation into English): At line .sda_pullup_en (translated as: "Out-of-order initializers are not standard in C++"): [{ "code": "2904", "severity": 8, "message": "les initialiseurs hors service ne sont pas standard en C++", "source": "C/C++", "startLineNumber": 103, "startColumn": 9, "endLineNumber": 103, "endColumn": 9 } At line .master (translated as: "a designator for an anonymous union member can only appear between braces that match that anonymous union"): "owner": "C/C++", "code": "2358", "severity": 8, "message": "un désignateur pour un membre d'union anonyme peut uniquement apparaître entre des accolades qui correspondent à cette union anonyme", "source": "C/C++", "startLineNumber": 105, "startColumn": 9, "endLineNumber": 105, "endColumn": 9 }] [UPDATE] My initial code writings was as follows: i2c_config_t conf = { .mode = I2C_MODE_MASTER, .sda_io_num = I2C_MASTER_SDA_IO, .scl_io_num = I2C_MASTER_SCL_IO, .sda_pullup_en = (gpio_pullup_t)GPIO_PULLUP_ENABLE, .scl_pullup_en = (gpio_pullup_t)GPIO_PULLUP_ENABLE, .master.clk_speed = I2C_MASTER_FREQ_HZ }; And were producing those two errors: At .sda_pullup_en = line (109) (translated as: "out of order initializers are not standard in C++"): [{ "owner": "C/C++", "code": "2904", "severity": 8, "message": "les initialiseurs hors service ne sont pas standard en C++", "source": "C/C++", "startLineNumber": 109, "startColumn": 3, "endLineNumber": 109, "endColumn": 3 }] At .master.clk_speed = line (111), translated as: a designator for an anonymous union member can only appear between braces that match that anonymous union expected primary-expression before '.' token class "i2c_config_t" has no "clk_speed" field [{ "owner": "C/C++", "code": "2358", "severity": 8, "message": "un désignateur pour un membre d'union anonyme peut uniquement apparaître entre des accolades qui correspondent à cette union anonyme", "source": "C/C++", "startLineNumber": 111, "startColumn": 3, "endLineNumber": 111, "endColumn": 3 },{ "owner": "cpp", "severity": 8, "message": "expected primary-expression before '.' token", "startLineNumber": 111, "startColumn": 3, "endLineNumber": 111, "endColumn": 3 },{ "owner": "C/C++", "code": "136", "severity": 8, "message": "classe \"i2c_config_t\" n'a pas de champ \"clk_speed\"", "source": "C/C++", "startLineNumber": 111, "startColumn": 10, "endLineNumber": 111, "endColumn": 10 }] How to fix my code?
@hcheung gave the right answer about the order of the members. But regarding the anonymous union, his solution does not work. I finally came up with the solution: i2c_config_t conf = { .mode = I2C_MODE_MASTER, .sda_io_num = I2C_MASTER_SDA_IO, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_io_num = I2C_MASTER_SCL_IO, .scl_pullup_en = GPIO_PULLUP_ENABLE, { {I2C_MASTER_FREQ_HZ}} }; Anonymous union are not standard but compiler extension and should actually be named. But here, the struct belongs to a third-party lib I cannot update. So the solution is that I need to put an open curry braces to catch the first member of the union and then provide the value I am interested in. Very important to note that it sounds we can only reach the first union member as we can't name it. Additional note: You can also be explicit about the clock speed as follows: i2c_config_t conf = { .mode = I2C_MODE_MASTER, .sda_io_num = I2C_MASTER_SDA_IO, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_io_num = I2C_MASTER_SCL_IO, .scl_pullup_en = GPIO_PULLUP_ENABLE, {{.clk_speed = I2C_MASTER_FREQ_HZ}} };
73,815,195
73,815,313
Create class based on variadic templates
Lets imagine that we have several data flows and we need unite them to one. Capacity of flows (and type) is known at application level. So we need class that incapsulates all other classes that relates to each data flow and produces common frame based on return type of data flows. Each data flow class have next interface: // note that there are several classes with similar interface class FlowOne { using return_type = some_data; return_type get(); }; Main flow class will look like: template <typename... Args> class Main { using return_type = *based on Args::return_type*; return_type get(); }; So, here is a question: how to define Main::return_type - that should be a tuple of return_type-s from its Args? Is it possible? Thanks
You can expand Args... to be std::tuple<Args...> and declare a member of that type. Now your Main class has a tuple of all Flow types: template <typename... Args> struct Main { using tuple_type = std::tuple<Args...>; tuple_type members; the next step is to make a get() function that returns the .get() of all members. This can be achieved with std::apply to iterate over the tuple, and call .get() on each object. Keep in mind that, if your final get() functions return a reference, this get() should also return one (meaning auto& or auto&&). auto get() { return std::apply([](auto&&... member) { return std::make_tuple(member.get()...); }, this->members); } As you can see, if we say decltype(get) on the member function, it will be equal to the std::tuple of Flow types: struct FlowOne { using return_type = int; return_type get() { return {}; } }; struct FlowTwo { using return_type = double; return_type get() { return {}; } }; int main() { Main<FlowOne, FlowTwo> main; auto get = main.get(); static_assert(std::is_same_v<decltype(get), std::tuple<int, double>>); } if you still wish to define a Main::return_type, you can use this using statement: using return_type = std::tuple<typename Args::return_type...>; we have to add typename here, because return_type is a dependant type of Args. You can read more about this on this post Try out the full code on godbolt.
73,815,252
73,815,894
How do I solve this Array question of Sorting Positive and negative digits in C++?
An array of length L is given. Elements are '–ve' and +ve integers. Make a function that figure out all positive numbers in the array that have their opposites in it as well. Input : 4,5,8,3,2,-5,-8,-4,-2,-3,-5,8,-8 Output : 2,-2,3,-3,4,-4,5,-5,8,-8 I copied this code from the web but couldn't understand it, is there some other easier way. #include <bits/stdc++.h> using namespace std; void printPairs(int arr[], int n) { vector<int> v; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // If absolute values are equal print pair. if (abs(arr[i]) == abs(arr[j])) v.push_back(abs(arr[i])); if (v.size() == 0) return; for (int i = 0; i < v.size(); i++) cout << -v[i] << " " << v[i] << " "; } int main() { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0; }
Using standard algorithms does not always immediately make code easier, but standard algorithms are well documented. If you do not understand application of a standard algorithm you can find plenty of documentation. That isnt the case for self-written algorithms. Know your algorithms! I will use a simpler example: 2,1,-2,2, and I will use a std::vector. std::sort can be used to sort the vector to 1,2,2,-2 by using a custom comparator that compares the elements absolute values and places positive elements before negative ones ( to achive that you can compare std::pairs of {abs(element),element<0}). std::unique can be used to move adjacent duplciates to the end of the vector, resulting in 1,2,-2,2. The returned iterator refers to the 2 because thats the end of the vector that has only the unique elements. (Here it is not actually needed to erase the duplicates from the vector) std::adjacent_find can be used to find pairs of adjacent elements for which abs(a) == abs(b). Thats all you need. #include <iostream> #include <vector> #include <utility> #include <algorithm> int main() { std::vector<int> x{4,5,8,3,2,-5,-8,-4,-2,-3,-5,8,-8}; std::sort(x.begin(),x.end(),[](auto a,auto b){ return std::make_pair(std::abs(a),a<0) < std::make_pair(std::abs(b),b<0);}); auto last = std::unique(x.begin(), x.end()); //x.erase(last, x.end()); // no need to actually erase auto it = x.begin(); while (it != last) { it = std::adjacent_find(it,last,[](auto a,auto b){ return std::abs(a) == std::abs(b);}); if (it != last) { std::cout << *it << " " << *std::next(it) << "\n"; it += 2; } } } I am not expecting that you find this code much simpler to read compared to the original, but if you just spend some time on the documentation of the used algorithms it should become clear how it works.
73,815,697
73,816,403
Is there a way to expect global exception in GTest?
I have a scenario where a call SendFeedback() sends a message and returns successfully. The message is received by another thread which throws. EXPECT_THROW doesn't work because SendFeedback() does not throw itself. Is there a way to expect this kind of exceptions? pseudo-code: auto listener = Listener(); auto sender = Sender(); ... sender.SendFeedback(); // listener throws due to unexpected feedback. This exception is to be expected
It is not exactly what you asked for, but GTest have for mechanism for death tests, where you can assert that given invocation would crash the program. Uncaught exception invokes std::terminate, which by default invokes std::abort, thus will pass the assertion. I've made small proof of concept to verify it works: void delayed_uncaught_exception() { using namespace std::chrono_literals; std::thread thread([] { throw std::runtime_error("Error"); }); std::this_thread::sleep_for(50ms); } TEST(MyDeathTest, DelayedException) { ASSERT_DEATH(delayed_uncaught_exception(), ""); } Although, I strongly agree with discussion under the question, that death tests maybe not the best fit for this test scenario and in long-run I'd recommend redesigning the flow.
73,816,170
73,816,569
Why implement specific functions to retrieve data rather than retrieving directly when overloading a * operator for a iterator class nested in a ADT
C++ newbie here. I'm reading the book Data Structures and Algorithm Analysis in C++(M. A. Weiss), where the implementation of const_iterator and iterator class nested in a user-defined List class of <typename Object> was given. Here's a snippet of it. class const_iterator { public: const Object& operator* () const { return retrieve(); } protected: Node* current_; Object& retrieve() const { return current_->data_; } }; class iterator : public const_iterator { public: Object& operator* () { return const_iterator::retrieve(); } const Object& operator* () const { return const_iterator::operator*(); } }; I really don't get why did the author bother to write the retrieve function just to retrieve the data, whose body is exactly all it takes to do so. If I were to implement the three overload functions, I would naturally write return current_->data_ or return *this->current_->data_. I mean, even if it's equivalent, I wouldn't come up with this kind of idea either. This question seems trivial, and I'm asking out of pure curiosity. In my limited knowledge of C++, calling functions has a performance cost. Though this could be optimized out by the compiler, I prefer the code to be logically the most efficient at least on paper. It gets even stranger that for const return values, the author used operator* instead of retrieve in consistency. What's the benefit of jumping between retrieve functions rather than a simple return expression?
I think the usage of intermediary function may just be due to the preference of the author. Usually such style is used in order to perform some validation in the intermediary function(for example, checking if data_ is nullptr, or if data_ satisfies some condition which is imposed by the problem the code tries to solve). But I have seen some people who even if there is no need for some kind of validation, still use this style. For example when you write Object& operator* () { return const_iterator::retrieve(); } you expect that retrieve function will not return you corrupted data. And even when you get a corrupted value, you immediately know that there is a problem in retrieve function, and you can just solve the issue by investigating it. If you didn't have an intermediary function, you had to investigate every place where you written the alternative code of retrieve. Also, it is much better to have a function which deals with all the raw data, and you don't deal with them anymore.
73,816,266
73,816,442
consume element from std::set
I try to directly consume elements from a set, which i cannot get to work from the outside getting an error binding reference of type ‘int&&’ to ‘std::remove_reference<const int&>::type’ {aka ‘const int’} discards qualifiers Consuming from a vector works perfectly fine. I really do not understand where syntactic the difference would be between consuming from the set or the vector, as they work similar cocerning their iterators. I can make a Workaround pops(), however, I do not neccessarily see this as a intuitive solution. #include <vector> #include <set> #include <iostream> class A { public: std::vector<int> intv_{1,2,3}; std::set<int> ints_{1,2,3}; int pops() { auto rslt = std::move(*ints_.begin()); ints_.erase(ints_.begin()); return rslt; } }; using namespace std; void consume_int(bool dummy, int&& i) { cout << i << endl; } using namespace std; int main() { A a; consume_int(true, std::move( *(a.intv_.begin()) )); //OK! a.intv_.erase(a.intv_.begin()); consume_int(true, std::move( *a.ints_.begin() )); //FAIL to compile a.ints_.erase(a.ints_.begin()); consume_int(true, std::move(a.pops())); //Workaround OK! return 0; }
The point is: You are not allowed to change the objects within a set, as this would require to move their location within the set. This is why the iterator only returns a const reference even for non-const std::set! Now r-value references are intended to be used to modify the object (moving the contents away – which would be such an illegal change of the set entry! – at that point the set cannot know that you are going to erase the entry anyway), and you cannot assign const references to, which would open doors to all such illegal modifications (of set members, objects in non-writable memory sections, etc). Edit: Still you actually can move elements out of a std::set, provided you have at least C++17 available, in this case you can profit from the extract function: int pops() { auto handle = ints_.extract(ints_.begin()); auto rslt = std::move(handle.value()); // for DEMONSTRATION purposes! return rslt; } with the handle getting discarded on exiting the function – though, actually you don't need to explicitly move anything at all, you can simply write: int pops() { auto handle = ints_.extract(ints_.begin()); return handle.value(); // or as a one-liner: return ints_.extract(ints_.begin()).value(); }
73,816,371
73,816,468
error C2312 is thrown for ifstream::failure and ofstream::failure exceptions
I am writing a small application that modifies a text file. It first creates a copy of the file in case something goes wrong. The following function creates this copy in the same directory. It takes the file's name as an argument and returns true if the copy is successfully created, and false if it fails. #include <iostream> #include <filesystem> #include <fstream> #include <string> using std::ifstream; using std::ofstream; using std::string; using std::cerr; using std::cin; using std::cout; using std::endl; bool backupFile(string FileName) { cout << "Creating backup for " << FileName << "..." << endl; try { // for debugging purposes string NewName = "bkp_" + FileName; string CurLine; ifstream FileCopy(FileName); ofstream FileBackup(NewName); if (FileCopy.fail()) { // Could specify how file copy failed? cerr << "Error opening file " << FileName << "."; return false; } while (getline(FileCopy, CurLine)) { // Copy lines to new file //cout << "Copying " << CurLine << "\" to " << NewName << "." << endl; FileBackup << CurLine << "\n"; } cout << "File successfully backed up to " << NewName << endl; return true; } catch (const ifstream::failure& iE) { cerr << "Exception thrown opening original file: " << iE.what() << endl; return false; } catch (const ofstream::failure& oE) { cerr << "Exception thrown outputting copy: " << oE.what() << endl; } catch (...) { cerr << "Unknown exception thrown copying file." << endl; return false; } } I've used a few catch statements to indicate if there is an issue with the input (ifstream::failure), the output (ofstream::failure), or neither. During compilation, however, the following error appears: error C2312: 'const std::ios_base::failure &': is caught by 'const std::ios_base::failure &' on line 42 To me, the error implies that both ifstream::failure and ofstream::failure are caught on ifstream::failure, which seems strange. When I remove the catch for ofstream::failure, it runs fine. Why is this the case?
ifstream::failure and ofstream::failure are both the same type defined in the std::ios_base base class std::ios_base::failure, you can't catch the same type in two separate catch clauses. Note that neither of your streams will actually throw any exceptions, by default std::fstream doesn't throw any exceptions. You have to turn exceptions on by calling exceptions: FileCopy.exceptions(f.failbit); FileBackup.exceptions(f.failbit); The above will cause an std::ios_base::failure to be thrown when the stream enters the failed state. As you are already checking for FileCopy.fail() you could just expand that checking to cover other failure cases (e.g. check that FileCopy doesn't fail during getline and that FileBackup also doesn't fail) rather than enabling exceptions.
73,816,562
73,816,629
Can't use vector::assign with 1 parameter on vs code mac
At first I thought there was something wrong with my code, but even this gets compiler errors and says that I need to provide 2 arguments: #include<iostream> #include<vector> std::vector<int>v; int main() { int m; std::cin>>m; v.assign(m); } If I use v.assign(m,-1); instead of v.assign(m);, it compiles and runs just fine. Here are the error messages: error: no matching member function for call to 'assign' v.assign(m); ~~^~~~ ~~ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:623:9: note: candidate function template not viable: requires 2 arguments, but 1 was provided assign(_InputIterator __first, _InputIterator __last); ^ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:633:9: note: candidate function template not viable: requires 2 arguments, but 1 was provided assign(_ForwardIterator __first, _ForwardIterator __last); ^ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:635:10: note: candidate function not viable: requires 2 arguments, but 1 was provided void assign(size_type __n, const_reference __u); What should I do?
See the documentation for std::vector.assign(). assign(n, e) will fill the vector with n copies of e. There is no 1 argument call to assign.
73,816,713
73,852,577
cppyy OPENMP error: nullptr result where temporary expected
I've been trying to run some parallelised code in C++ from Python through cppyy but am facing an error. The executable (compilted through GCC with -fopenmp -O2) runs without errors and shows the expected drop in runtime from parallelisation. When the #pragma omp parallel for is commented out of the C++ code, cppyy doesn't raise any errors. However, when the pragma is part of the code I get the error below: IncrementalExecutor::executeFunction: symbol '__kmpc_for_static_fini' unresolved while linking symbol '__cf_4'! IncrementalExecutor::executeFunction: symbol '__kmpc_for_static_init_4' unresolved while linking symbol '__cf_4'! IncrementalExecutor::executeFunction: symbol '__kmpc_fork_call' unresolved while linking symbol '__cf_4'! IncrementalExecutor::executeFunction: symbol '__kmpc_global_thread_num' unresolved while linking symbol '__cf_4'! Traceback (most recent call last): File "...../SO_troubleshooting/example_pll_cppyy_code.py", line 8, in <module> output = cppyy.gbl.pll_somelinalgeb() ValueError: std::vector<std::vector<Eigen::Matrix<double,-1,-1,0,-1,-1> > > ::pll_somelinalgeb() => ValueError: nullptr result where temporary expected Here is the short Python script: import cppyy cppyy.add_include_path('../np_vs_eigen/eigen/') cppyy.include('easy_example.cpp') vector = cppyy.gbl.std.vector import datetime as dt print('Starting the function call now ') start = dt.datetime.now() output = cppyy.gbl.pll_somelinalgeb() stop = dt.datetime.now() print((stop-start), 'seconds') The C++ toy code is below. It generates a random matrix with Eigen, calculates its pseudo-inverse, and then sleeps for 1 ms. #include <omp.h> #include <iostream> #include <Eigen/Dense> #include <chrono> #include <vector> #include <thread> using Eigen::VectorXd; using Eigen::MatrixXd; std::vector<MatrixXd> some_linearalgebra(){ std::vector<MatrixXd> solutions; std::srand((unsigned int) time(0));//ensures a new random matrix each time MatrixXd arraygeom(5,3); arraygeom = MatrixXd::Random(5,3); VectorXd row1 = arraygeom.block(0,0,1,3).transpose(); arraygeom.rowwise() -= row1.transpose(); MatrixXd pinv_arraygeom(3,5); // calculate the pseudoinverse of arraygeom pinv_arraygeom = arraygeom.completeOrthogonalDecomposition().pseudoInverse(); //std::cout << pinv_arraygeom << std::endl; solutions.push_back(pinv_arraygeom); solutions.push_back(pinv_arraygeom); std::this_thread::sleep_for(std::chrono::milliseconds(1)); return solutions; } std::vector<std::vector<MatrixXd>> pll_somelinalgeb(){ int num_runs = 5000; std::vector<std::vector<MatrixXd>> all_solns(num_runs); #pragma omp parallel for for (int i=0; i<num_runs; i++){ all_solns[i] = some_linearalgebra(); } return all_solns; } int main(){ std::vector<MatrixXd> main_out; main_out = some_linearalgebra(); auto start = std::chrono::system_clock::now(); std::vector<std::vector<MatrixXd>> main2_out; main2_out = pll_somelinalgeb(); auto end = std::chrono::system_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " ms" << std::endl; return 0; } System + OS specs: Ubuntu 18.04.2 LTS,Intel® Core™ i7-10700 CPU @ 2.90GHz × 16 , 64Bit Python 3.9.0 cppyy 2.4.0 (pip install) Eigen 3.4.0 Non-default precompiled cppyy header used: As per this link I ran the following commands on terminal export EXTRA_CLING_ARGS='-fopenmp' and then ran the code with cppyy_backend.loader, and then finally added the CLING_STANDARD_PCH environment variable with another export. C++ Executable compiled with g++-11 easy_example.cpp -fopenmp -O2 -I <path_to_Eigen_library here>
The problem was linking the OpenMP library file to the Cling compiler that runs cppyy. I encountered the same problem in Linux Mint and Windows 11 too - which made me realise it is not an OS-specific problem. What ended up working was the following: Add the -fopenmp flag to your EXTRA_CLING_ARGS environmental variable (export EXTRA_CLING_ARGS='-fopenmp' in Unix, and in Windows go through the start menu and add a new environmental variable). Compile a new precompiled header with the code in the docs here, and define the path to the precompiled header with Find the libiomp5 library in your OS ($ locate libiomp5 in Unix, or search for libiomp5 in the File Explorer in Windows). The Unix file should be libiomp5.so and the Windows version is libiomp5md.dll In your Python module add the libiomp5 library with the cppyy.load_library(<insert path to .so or .dll file here>) You should now have parallelised code! This gets you to working code, but is admittedly a rather manual approach - would be happy to hear a more automated approach.
73,816,992
73,817,023
Is it safe to use c_str() as a parameter in std::exception?
Is it safe to pass c_str() as a parameter when constructing std::exception? Please let me know if handling exceptions like this is a bad idea. In my project all error messages are returned from a function as std::string and then thrown as a std::exception. #include <iostream> int main() { try { std::string message="! Something went wrong."; throw std::exception(message.c_str()); } catch (std::exception ex) { std::cerr << ex.what() << std::endl; } }
std::exception does not have a contructor that takes a const char* or a std::string. std::runtime_error (and its descendants) does have constructors for both. And yes, it is perfectly safe (well, provided that memory is not low) to pass the message.c_str() pointer to this constructor. std::runtime_error will copy the character data into its own internal memory, allowing message to be destroyed after the exception is thrown. If you want to throw std::exception itself with a string message, you will have to derive a custom class from it and implement your own string buffer for what() to return a pointer to. In which case, you have to be careful not to return an invalid const char* pointer from what(). std::runtime_error handles that for you, so you should derive from that instead.
73,817,020
73,817,757
Why is there no built-in way to get a pointer from an std::optional?
Things like the following happen all to often when using std::optional: void bar(const Foo*); void baz(const std::optional<Foo>& foo) { // This is clunky to do every time. bar(foo.has_value() ? &foo.value() : nullptr); // Why can't I do this instead? bar(foo.as_ptr()); } This is the sort of thing that makes it annoying to adopt std::optional, because then it's extremely inconvenient to use it with existing code that expects pointers instead. So why isn't something like .as_ptr() provided with std::optional? It seems like a pretty obvious convenience function.
To be pedantically correct, you need to use one of these instead: // `Foo` might have an overloaded `operator&` foo.has_value() ? std::addressof(foo.value()) : nullptr // You can shorten it to foo ? std::addressof(*foo) : nullptr // Or you can use `operator->()` foo ? foo.operator->() : nullptr // Which in C++20 can be accessed with a more readable utility function foo ? std::to_address(foo) : nullptr As for the "why", let's look at the proposal to add std::optional to the standard library, "A proposal to add a utility class to represent optional objects (Revision 5)". It's based on Boost.Optional, which does provide foo.get_ptr() with the exact semantics that you want. In fact, the original proposal has get_pointer(foo), but it was removed in the second revision. The change is described as "Removed duplicate interface for accessing the value stored by the optional.", as it was removed along with std::get(std::optional<T>&). You can simply use boost::optional instead, but it is not too hard to reimplement it yourself: // If you want it as a member namespace my { template<typename T> struct optional : std::optional<T> { using std::optional<T>::optional; T* get_ptr() noexcept { return has_value() ? std::addressof(value()) : nullptr; } const T* get_ptr() const noexcept { return has_value() ? std::addressof(value()) : nullptr; } }; } // Or as a free function template<typename T> T* get_ptr(std::optional<T>& opt) noexcept { return opt.has_value() ? std::addressof(opt.value()) : nullptr; } template<typename T> const T* get_ptr(const std::optional<T>& opt) noexcept { return opt.has_value() ? std::addressof(opt.value()) : nullptr; } Or using the C++23 monadic operations on optionals, this can be foo.and_then([](auto& x) { return std::addressof(x); }).
73,817,544
73,817,779
C++ constexpr function parameters
With this nice simplified compile time string class. There are no constexpr/consteval function parameters in C++ but the point of this question is: Can I get a function call style for passing of non-type template parameters ? With the suffix I can get pretty close. But can it be done better ? I do not want to use this syntax test_normal_function2<"asd">(x); How can I get rid of _fs suffix in the invocation of test_normal_function ? #include <algorithm> struct no_init_fixed_string {}; template <std::size_t N> struct fixed_string { constexpr fixed_string(const char (&foo)[N + 1]) { std::copy_n(foo, N + 1, data.begin()); } std::array<char, N + 1> data{}; constexpr fixed_string(no_init_fixed_string) : data{} { } }; template <std::size_t N> fixed_string(const char (&str)[N]) -> fixed_string<N - 1>; template<fixed_string s> struct fixed_string_type { }; template<fixed_string s> constexpr auto operator"" _fs() { return fixed_string_type<s>{}; } template<fixed_string s> void test_normal_function(fixed_string_type<s>, int x ) { //use s as consexpr parameter } template<fixed_string s> void test_normal_function2( int x ) { } int main() { int x = 3; test_normal_function("asd"_fs,x); //this works test_normal_function2<"asd">(x); // this works but its ugly //test_normal_function("asd",x); //this doesn't compile but its pretty. } How can I make call to test_normal_function work without _fs suffix ?
Preprocessor macro trickery aside, it is impossible to do it with the exact syntax you want, because a usual string literal (not a user-defined literal) does never encode its value in its type (only its length). A value passed to a function via a function parameter can never be used by the function in a constant expression. Only information in the type can be used that way. However, you can pass a value via a template parameter and make use of it in a constant expression: test_normal_function<"asd">({},x);
73,819,293
73,828,023
Finding current connected network interface/adaptor Windows
I'm thinking there must be a way to ask windows for information about the network adaptor of the current connected network (available unicast/multicast, is it Wi-Fi, the name, etc) When I say connected, I mean like the current Wi-Fi connection like windows shows you in the Wi-Fi options - the definition of connected is probably different in the networking world Even if it's just possible the interface index, because It's easy to look up most other things using GetAdaptersAddresses() etc In case this is an x/y problem: I'm trying to do this as part of writing an mdns client (for academic purposes, I know windows has an mdns api). I'd like to only broadcast and receive on the current Wi-Fi network (for which I think you need to set the IP_ADD_SOURCE_MEMBERSHIP flag in setsockopt) and I also need to then know which IP address to return to the mdns response I could set IP_ADD_MEMBERSHIP but then I would still need to find out which IP to return and everything just becomes conceptually easier if things work on a single network (or so I thought)
The GetAdaptersAddresses will give you the list of network interfaces on the system and will tell you what type of interface each of them is. In the returned IP_ADAPTER_ADDRESSES list, the IfType field tells you the type of the interface, which for wireless will be IF_TYPE_IEEE80211. Then when you find an interface of this type, you can iterate through the list of assigned addresses via the FirstUnicastAddress member to join the relevant multicast groups. IP_ADAPTER_ADDRESSES *head, *curr; IP_ADAPTER_UNICAST_ADDRESS *uni; int buflen, err, i; buflen = sizeof(IP_ADAPTER_UNICAST_ADDRESS) * 500; // enough for 500 interfaces head = malloc(buflen); if (!head) exit(1); if ((err = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, head, &buflen)) != ERROR_SUCCESS) { char errbuf[300]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, errbuf, sizeof(errbuf), NULL); printf("GetAdaptersAddresses failed: (%d) %s", err, errbuf); free(head); exit(1); } for (curr = head; curr; curr = curr->Next) { if (curr->IfType != IF_TYPE_IEEE80211) continue; for (uni = curr->FirstUnicastAddress; uni; uni = uni->Next) { if (curr->OperStatus == IfOperStatusUp) { char addrstr[INET6_ADDRSTRLEN]; inet_ntop(uni->Address.lpSockaddr->sa_family, uni->Address.lpSockaddr, addrstr, uni->Address.iSockaddrLength); printf("interface name: %s\n", curr->AdapterName); printf("interface address: %s\n", addrstr); } } } free(head); An important note here is that there may be more that one wireless interface active.
73,820,256
73,821,701
Vector of queues of different types
I have a type, let's call it T. It can be of different types, and I do not know them in advance: int, double, bitmap pointer... Now, I have a class, let's call it C. It should maintain a vector of queues of T. Each queue has its unique type of elements, but it is possible that C has a vector (or whatever other way of maintaining multiple queues) with few queues of different types: queue, queue, ... So my question is: is there a way to pass variable number types to a class? Example: I need to get <int, double, double, int> and in a constructor, to create corresponding queues, plus I will need a function to get/put data to a particular queue (say, queue No 3 in a list). I know about variadic templates, but can not figure how to use it: it looks like I have to do it recursively, and I am not that advanced... I can do it using "any", but then get/put will have "any" as well, and I do not know how to do a type check, so the user doesn't send a double instead of string, or something like that. Any ideas? Thanks.
It's actually not that complicated. You don't even need recursion. Just std::tuple #include <tuple> #include <queue> template <class... Args> struct C { std::tuple<std::queue<Args>...> queues_; template <std::size_t I> auto& queue_at() { return std::get<I>(queues_); } }; auto test() { C<int, double, bool> c; std::queue<int>& q1 = c.queue_at<0>(); std::queue<double>& q2 = c.queue_at<1>(); }
73,820,417
73,820,534
Lazy Evaluation on condition variables
In the following code snippet, would compiler do lazy evaluation on condition variables and also do short circuit evaluation? const bool condition1 = calcCondition1(...); const bool condition2 = calcCondition2(...); const bool condition3 = calcCondition3(...); if (condition1 && condition2 && condition3) return true; return false Such that the actual flow would be something like the following? if(!calcCondition1(...)) return false; if(!calcCondition2(...)) return false; if(!calcCondition3(...)) return false; return true; Thank you!
Yes, if compiler is sure that such a optimization does not change any visible semantic of the program (see __attribute__((pure)) example below). No in other cases. Note that function bodies from different compilation units (different .cpp file) are unknown: they are linked into binary after compilation process. The compiler must assume worst-case scenarios such as calcCondition1 throws an exception or executes exit(). Or mutate some global state. And in such cases, the semantics must be preserved and everything must be invoked in the written order That code bool calcCondition1(); bool calcCondition2(); bool calcCondition3(); bool foo() { const bool condition1 = calcCondition1(); const bool condition2 = calcCondition2(); const bool condition3 = calcCondition3(); if (condition1 && condition2 && condition3) return true; return false; } and example assembly output: foo(): # @foo() push rbp push rbx push rax call calcCondition1()@PLT mov ebp, eax call calcCondition2()@PLT mov ebx, eax call calcCondition3()@PLT and bl, bpl and al, bl add rsp, 8 pop rbx pop rbp ret Notice that all functions are called one by one If compiler is sure that it is not a case (I am using a gcc extension): __attribute__((pure)) bool calcCondition1(); __attribute__((pure)) bool calcCondition2(); __attribute__((pure)) bool calcCondition3(); bool foo() { const bool condition1 = calcCondition1(); const bool condition2 = calcCondition2(); const bool condition3 = calcCondition3(); if (condition1 && condition2 && condition3) return true; return false; } Then the generated code use the short circuit evaluation foo(): # @foo() push rbx call calcCondition1()@PLT test al, al je .LBB0_4 call calcCondition3()@PLT mov ebx, eax call calcCondition2()@PLT test bl, bl je .LBB0_4 mov ecx, eax mov al, 1 test cl, cl je .LBB0_4 pop rbx ret .LBB0_4: xor eax, eax pop rbx ret , because compiler is sure that functions are pure, so there is a more rooms for optimizations.
73,820,519
73,821,900
Why does gcc 12.2 not optimise divisions into shifts in this constexpr function
I have been playing around with the Godbolt Compiler and typed this code: constexpr int func(int x) { return x > 3 ? x * 2 : (x < -4 ? x - 4 : x / 2); } int main(int argc) { return func(argc); } The code is somewhat straight forward. The important part here is the final division by 2 inside func(int x). Since x is an integer, basically any compiler would simplify this to a shift to avoid division instructions. The assembly from x86-64 gcc 12.2 -O3 (for Linux, thus System V ABI) looks like this: main: cmp edi, 3 jle .L2 lea eax, [rdi+rdi] ret .L2: cmp edi, -4 jge .L4 lea eax, [rdi-4] ret .L4: mov eax, edi mov ecx, 2 cdq idiv ecx ret You can see the final idiv ecx command which is not a shift but an actual division by 2. I also tested clang and clang does actually reduce this to a shift. main: # @main mov eax, edi cmp edi, 4 jl .LBB0_2 add eax, eax ret .LBB0_2: cmp eax, -5 jg .LBB0_4 add eax, -4 ret .LBB0_4: mov ecx, eax shr cl, 7 add cl, al sar cl movsx eax, cl ret Could this be due to inlining maybe? I am very curious about whats going on here.
GCC treats main specially: implicit __attribute__((cold)) So main gets optimized less, as it's usually only called once in most programs. __attribute__((cold)) isn't quite the same as -Os (optimize for size), but it's a step in that direction which sometimes gets the cost heuristics to pick a naive division instruction. As GCC dev Marc Glisse commented, don't put your code in a function called main if you're benchmarking it or looking at how it optimizes. (There can be other special things besides cold, e.g. MinGW GCC puts in an extra call to an init function, and gcc -m32 adds code to align the stack by 16. All of which are noise you don't want for the code you're looking at. See also How to remove "noise" from GCC/clang assembly output?) Another Q&A shows GCC putting main in the .text.startup section, along with other presumed "cold" functions. (This is good for TLB and paging locality; hopefully a whole page of init functions can get evicted after process startup). This is a bad heuristic for toy programs with all their code in main, but it's what GCC does. Most real programs people run regularly aren't toys and have enough code in some other function that it doesn't inline into main. Although it would be nice if the heuristic was a little smarter and removed the cold if it turned out that the whole program or all the functions in a loop did optimize into main, since some real programs are pretty simple. You can override the heuristic with a GNU C function attribute. __attribute__((hot)) int main(){ ... optimizes the way you expect (Godbolt from Sopel's comment, with attribute added). __attribute__((cold)) on a function not called main produces idiv. __attribute__((optimize("O3"))) doesn't help. int main(int x, char **y){ return x/2; } does still use shifts with gcc -O2, so main being cold doesn't always have that effect (unlike -Os). But perhaps with your division already being conditional, GCC guesses that basic block doesn't even run every time so that's more reason to make it small instead of fast. Insanely, GCC -Os for x86-64 (Godbolt) does use idiv for signed division a constant 2, not just for arbitrary constants (where GCC normally uses a multiplicative inverse even at -O0). It doesn't save much if any code size vs. an arithmetic right shift with a fixup to round towards zero (instead of -inf), and can be much slower, especially for 64-bit integers on Intel before Ice Lake. Same for AArch64, where it's 2 fixed-size instructions either way, with sdiv almost certainly being much slower. sdiv does save some code size on AArch64 for higher powers of 2 (Godbolt), but still so much slower that it's probably not a good tradeoff for -Os. idiv doesn't save instructions on x86-64 (as cdq or cqo into RDX is required), although maybe a couple bytes of code size. So probably only good for -Oz where it would also use push 2 / pop rcx to get a small constant into a register in 3 bytes of x86-64 machine code instead of 5.
73,820,660
73,820,856
Why doesn't ISO c++17 permit a structured binding declaration in a condition?
Clang emits a warning if I use a structured binding declaration as a condition: $ cat hello.cc int main() { struct A { int i; operator bool() { return true; } }; if (auto [i] = A{0}) { return i; } return -1; } $ clang++-10 -std=c++17 hello.cc hello.cc:3:12: warning: ISO C++17 does not permit structured binding declaration in a condition [-Wbinding-in-condition] if (auto [i] = A{0}) { ^~~ 1 warning generated. I don't see this in dcl.struct.bind or stmt.select; where would I see that this is forbidden? Furthermore: what is the rationale behind forbidding this?
The grammar for the if statement is if constexpr(opt) ( init-statement(opt) condition) statement and as you can see condition is required while the init-statement is optional. That means in if (auto [i] = A{0}) that auto [i] = A{0} is the condition, not the init-statment. condition is defined as condition: expression attribute-specifier-seq(opt) decl-specifier-seq declarator brace-or-equal-initializer and that does not allow for a structured binding as the grammar for that is attribute-specifier-seq(opt) decl-specifier-seq ref-qualifier(opt) [ identifier-list ] initializer ; Good news is you can get what you want by adding a condition to your if statement like if (auto [i] = A{0}; i)
73,820,693
73,822,378
Choose std::queue or std::priority_queue, depending on whether "<" is defined
Inspired by SFINAE to check if std::less will work, I come to this: template <typename F, typename S, typename = void> struct QueueImpl { using type = std::queue<std::pair<F, S>>; }; template <typename F, typename S> struct QueueImpl<F, S, decltype(std::declval<F>() < std::declval<F>())> { using type = std::priority_queue<std::pair<F, S>>; }; template <typename F, typename S> using Queue = typename QueueImpl<F, S>::type; with the intention that if < has been defined for type F, Queue will be std::priority_queue and otherwise std::queue. But it seems always to match the std::queue case: class C {}; int main() { Queue<int, char> q1; Queue<C, char> q2; std::cout << typeid(q1).name() << std::endl; std::cout << typeid(q2).name() << std::endl; return 0; } which shows both Queue's are std::queue: St5queueISt4pairIicESt5dequeIS1_SaIS1_EEE St5queueISt4pairI1CcESt5dequeIS2_SaIS2_EEE My second attempt uses std::conditional: template <typename F, typename S> using Queue = typename std::conditional_t< std::is_same_v<bool, decltype(std::declval<F>() < std::declval<F>())>, std::priority_queue<std::pair<F, S>>, std::queue<std::pair<F, S>>>; For q1, it successfully chooses std::priority_queue and prints St14priority_queueISt4pairIicESt6vectorIS1_SaIS1_EESt4lessIS1_EE. But when q2 is defined in the same way as the first attempt, the code cannot compile: error: no match for ‘operator<’ (operand types are ‘C’ and ‘C’) So how to make the code work?
Your first attempt fails for the following reason. When you use the template, you don't specify the third argument. Hence, it is supplied from the default type in the primary template, namely void. Then, the specialization can only match the argument types if the decltype results in void, whereas when F is int, the type is bool. Fixing this is as simple as casting the argument to decltype to void: template <typename F, typename S, typename = void> struct QueueImpl { using type = std::queue<std::pair<F, S>>; }; template <typename F, typename S> struct QueueImpl<F, S, decltype(void(std::declval<F>() < std::declval<F>()))> { using type = std::priority_queue<std::pair<F, S>>; }; template <typename F, typename S> using Queue = typename QueueImpl<F, S>::type; Demo.
73,820,707
73,820,798
Are preprocessor directives allowed in a function-like macro's argument?
This question regards the legality of using a preprocessor directive within a function-like macro's argument. Consider the following code. #ifdef is used inside MY_MACRO's argument : #include <iostream> // Macro to print a message along with the line number the macro appears at #define MY_MACRO( msg ) { std::cerr << "Line " << __LINE__ << "\t- "<< msg << '\n'; } int main() { // Print the current build configuration MY_MACRO( #ifdef NDEBUG // <-- preprocessor directive in macro argument "Release" #else "Debug" #endif ) } gcc 12 is fine with it, msvc 19 does not allow it : https://godbolt.org/z/G8j4aTG6j What does the standard have to say about it?
Short answer: No [cpp.replace.general]: The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments. If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives, the behavior is undefined.
73,820,932
73,821,087
Observer Design pattern - Getting a segfault
I am writing an Observer design pattern where Subject knows what Observer it has (same as the original design) and Observer also knows what Subject it's attached to, mainly to tackle scenarios like Observer going out of scope and Subject has a reference to a destroyed object. So if an Observer watches a Subject, both know about each other. This is handled via observer->removeSubject and observer->addSubject. In the following snippet, I am testing a case where Observers go out of scope, meaning ~Observer() gets invoked first however I seem to be getting a segfault on the following line when I debug in an online gdb tool in the second iteration of ~Observer() std::cout << "Observers size = " << _observers.size() << "\n"; template<typename T> class Subject; template<typename T> class Observer { std::set<Subject<T>*> _subjects; public: virtual void update(T val) = 0; void addSubject(Subject<T>* subject) { printf ("[Observer] Adding Subject to observer - "); _subjects.insert(subject); std::cout << "Subject size = " << _subjects.size() << "\n\n"; } void removeSubject(Subject<T>* subject) { printf ("[Observer] Removing Subject from observer - "); _subjects.erase(subject); std::cout << "Subject size = " << _subjects.size() << "\n"; } virtual ~Observer() { printf ("\n~Observer\nSubject Size = %ld\n", _subjects.size()); for (auto& subject : _subjects) { subject->detach(this); } } }; template<typename T> class Subject { std::set<Observer<T>*> _observers; protected: Subject() = default; public: void attach(Observer<T>* observer) { printf ("~~ [Subject] Attaching observer ~~\n"); _observers.insert(observer); observer->addSubject(this); } void detach(Observer<T>* observer) { printf ("~~ [Subject] Detaching observer ~~\n"); std::cout << "Observers size = " << _observers.size() << "\n"; _observers.erase(observer); observer->removeSubject(this); } void notify(const T& val) { for (auto& observer : _observers) { observer->update(val); } } virtual ~Subject() { printf ("\n~Subject\n"); printf ("Observer size = %ld\n", _observers.size()); for (auto& obs : _observers) { obs->removeSubject(this); } } }; template<typename T> class ConcreteSubject : public Subject<T> { T _value; public: void set(const T& value) { _value = value; this->notify(value); } }; template<typename T> class ConcreteObserver : public Observer<T> { public: void update(T value) { std::cout << "Observer Notified: " << value << "\n"; } }; int main() { ConcreteSubject<int> sub; { ConcreteObserver<int> obs; ConcreteObserver<int> obs1; sub.attach(&obs); sub.attach(&obs1); sub.set(5); } } One part that I am concerned about is the following where subject is removed from _subjects while _subjects is being iterated over. Should a copy of _subjects be made to be iterated over in ~Observer() instead? void removeSubject(Subject<T>* subject) { printf ("[Observer] Removing Subject from observer - "); _subjects.erase(subject); std::cout << "Subject size = " << _subjects.size() << "\n"; } virtual ~Observer() { printf ("\n~Observer\nSubject Size = %ld\n", _subjects.size()); for (auto& subject : _subjects) { subject->detach(this); } }
There may be more problems in your code but I can see at last this one: When Observer is being destroyed in destructor, it iterates over _subjects collection. You call Subject::detach() on each subject. Subject::detach() in turn calls Observer::removeSubject() on the very same observer and Observer::removeSubject() removes the subject from the very same _subjects collection which you are currently iterating upon. This is undefined behaviour which later probably leads to the segfault you are having. Solution 1 In Observer::~Observer() you can make a copy of the _subjects collection and iterate on this copy. This seems to be the simplest solution. Solution 2 virtual ~Observer() { while (!_subjects.empty()) { (*_subjects.begin())->detach(this); } } Solution 3 This solution may actually be the most performant one. If you are destroying the Observer you do not need to clear the _subjects collection one by one because the observer object will be destroyed anyway. Therefore you may introduce a private bool _destroying member variable. Its default value will be false but in the destructor it would be set to true. And when true, it would prevent removing from _subjects collection in removeSubject(). void removeSubject(Subject<T>* subject) { if (!_destroying) { _subjects.erase(subject); } } virtual ~Observer() { _destroying = true; for (auto& subject : _subjects) { subject->detach(this); } }
73,820,966
73,821,028
`std::is_same_v<size_t, uint64_t>` evaluates to `false` when both types are 8 bytes long
Code: #include <iostream> #include <type_traits> int main() { std::cout << "sizeof(size_t): " << sizeof(size_t) << std::endl; std::cout << "sizeof(uint64_t): " << sizeof(uint64_t) << std::endl; if constexpr (std::is_same_v<size_t, uint64_t>) { std::cout << "size_t == uint64_t" << std::endl; } else { std::cout << "size_t != uint64_t" << std::endl; } } Result: sizeof(size_t): 8 sizeof(uint64_t): 8 size_t != uint64_t Compiler Info: Apple clang version 14.0.0 (clang-1400.0.29.102) Target: arm64-apple-darwin21.6.0 Thread model: posix Is there a reason why size_t doesn't equal uint64_t? If so, is there a particular mention in the standard of why this is so?
Usually the type size_t is an alias for the type unsigned long. From the C Standard (7.19 Common definitions <stddef.h>) 4 The types used for size_t and ptrdiff_t should not have an integer conversion rank greater than that of signed long int unless the implementation supports objects large enough to make this necessary. Pay attention to that the rank of the type unsigned long int is equal to the rank of the type signed long int. On the other hand, the type uint64_t usually is defined as an alias for the type unsigned long long int. Though that is implementation defined. As for your code then the shown output means that sizeof( unsigned long int ) also is equal to 8 on the used system.
73,821,149
73,964,096
CPU inference in libtorch causes OOM with repeated calls to forward
I have some libtorch code that is doing inference on the cpu using a model trained in pytorch that is then exported to torchscript. The code below is a simplified version of a method that is being repeatedly called. void Backend::perform(std::vector<float *> in_buffer, std::vector<float *> out_buffer) { c10::InferenceMode guard; at::Tensor tensor_out; at::Tensor tensor_in = torch::zeros({ 1, 16, 2 }); std::vector<torch::jit::IValue> inputs = { tensor_in }; // calling forward on the model "decode," this is where // the memory leak happens tensor_out = m_model.get_method("decode")(inputs).toTensor(); auto out_ptr = tensor_out.contiguous().data_ptr<float>(); for (int i(0); i < out_buffer.size(); i++) { memcpy(out_buffer[i], out_ptr + i * n_vec, n_vec * sizeof(float)); } } m_model is the .ts file loaded via: m_model = torch::jit::load(path); m_model.eval(); Every call it seems that more of the torch graph is being allocated, and it isn’t being freed causing the program to eventually OOM and crash. Commenting out the forward call causes the the memory usage to stabilize. My understanding is that InferenceMode guard should turn off autograd memory buildup which seems to be the normal cause of these issues. I tried mimicking this in pytorch (by repeatedly calling forward from a loop), and there’s no memory issues which seems to point to this being a libtorch issue rather than an issue with the model itself. My system: OS: Windows 10/11 pytorch version: 1.11.0 libtorch version: 1.11.0
This ended up being a bug in the windows implementation of libtorch. Memory leaks can happen when calling forward on a separate thread from the main thread (https://github.com/pytorch/pytorch/issues/24237), and moving the forward call to the main thread fixed the issue. Even though the issue is marked closed the bug is still present.
73,821,535
73,821,607
program to verify a number by two requirements
I'm trying to make a program that verifies if a number meets two requirements: the number has 4 digits not all the digits are the same I've been made it, and it looks good, but the code fails in a specific case. When the user enters a number with all of the digits equal, like 1111, the first time the program will say that this number isn't correct and will ask for a new number, but if the user enters another invalid number with all digits equal, like 2222, the verification fails and accepts this new number as a valid number. I don't know what the problem could be, can someone help? This is the code: #include <iostream> using namespace std; int main(){ int n; // number cout << "enter a 4-digit number with at least one different digit number: "; cin >> n; int m = 0, o = 0, u = n, z = 0; // variables int counter, counter1, counter2 = 5; //counters int x[4], y[4]; // vectors //--------------------------- verification ------------------------------------- while(counter != 4 && counter2 > 3){ // ======= number size verification ======= while (u > 0){ u = u/10; counter = counter + 1; // number digit counter } if(counter != 4){ // if the number has less than 4 digits cout << "the number has less than 4 digits, enter a valid number: "; cin >> n; u = n; } // ================================================= // ========= check repetead numbers ================ if(counter == 4){ // if the number has 4 digits u = n; z = n; for(int i = 3; i >= 0; i--){ // convert the number into two vectors u = u % 10; x[i] = u; y[i] = u; z = z / 10; u = z; } counter2 = 0; // repetition counter 2 (reset counter value) // traversal of the vector in search of repeated numbers for(int j = 0; j < 4; j++){ counter1 = 0; // repetition counter 1 (reset counter value) m = x[j]; for(int k = 0; k < 4; k++){ o = y[k]; if(m == o){ counter1 = counter1 + 1; // if there are repeated numbers counter increases y[k] = 0; // delete that vector position } } if(counter1 == 1 || counter1 == 0){ // if only found the repetition of the same box counter1 = 0; // reset counter1 }else{ counter2 = counter2 + counter1; // if not, its value is assigned to counter2 } } } if(counter2 == 4){ // if the number has all its digits the same n = 0; cout << "the number has all its digits the same, enter a valid number: "; cin >> n; } } cout << "valid number"; return 0; } image of the failure:
To check if your number is 4 digits you can simply compare it: if( n < 1000 or n > 9999 ) // not 4 digits number To check if all digits are the same, just check if it is divisible by 1111 (thanks to @SamVarshavchik ) if( n % 1111 == 0 ) // all digits are the same
73,821,619
73,821,669
Using Variadic Function to pass args into a vector
I am trying to make a function that adds an unknown amount of objects to a vector. I am trying to accomplish it here by just passing ints, but I cannot get it to work. Does any one know how this can be done? Code #include <iostream> #include <vector> class Entity { public: std::vector<int> Ints; template <typename T, typename ... pack> void AddToVector(T first, pack ... argPack) { Ints.push_back(argPack...); for(auto& i : Ints) std::cout << i << "\n" << std::endl; }; }; int main() { Entity e1; e1.AddToVector(1, 2, 3, 4, 5); return 0; } Error: main.cpp: In instantiation of ‘void Entity::AddToVector(T, pack ...) [with T = int; pack = {int, int, int, int}]’: main.cpp:32:33</span>: required from here main.cpp:20:9: error: no matching function for call to ‘std::vector::push_back(int&, int&, int&, int&)’
In C++11 and C++14, You can use something like this: private: void Internal_AddToVector() { } template <typename T, typename ... pack> void Internal_AddToVector(T first, pack... argPack) { Ints.push_back(first); Internal_AddToVector(argPack...); } public: template <typename ... pack> void AddToVector(pack ... argPack) { Internal_AddToVector(argPack...); for(auto& i : Ints) std::cout << i << "\n" << std::endl; } Alternatively: public: template <typename ... pack> void AddToVector(pack ... argPack) { for (auto& elem : {argPack...}) Ints.push_back(elem); for(auto& i : Ints) std::cout << i << "\n" << std::endl; } In C++17 and later, you can use a fold expression instead: public: template <typename ... pack> void AddToVector(pack... argPack) { (Ints.push_back(argPack), ...); for(auto& i : Ints) std::cout << i << "\n" << std::endl; }
73,822,721
73,822,873
Reverse right angle triangle pattern with numbers and asterisks using for-loops in C++
first time posting here, I'd like help with getting the output of the code upside down while still using the for commands, below is the best I can put in a clarification. Desired Output: Actual Output: 123456 1***** 12345* 12**** 1234** 123*** 123*** 1234** 12**** 12345* 1***** 123456 Code: #include <iostream> using namespace std; int main() { int num, row, integ; cout << "Please enter size: "; cin >> integ; for (row = 1; row <= integ; row++) { for (num = 1; num <= row; num++) { cout << num; } for (; num <= integ; num++) { cout << "*"; } cout << endl; } }
first time answering here :). change num <= row to num <= integ - row + 1
73,822,766
73,823,829
How to extract rotation and translation from Eigen::Affine
Since each Eigen::Affine3d object indicates a special linear transformation, I want extract the rotation part and translation part separately. And I want to save the rotation part into an Eigne::Quaterniond and the translation part into an Eigen::Vector3d. How to realize that?
Use the rotation() and translation() methods, like this. Eigen::Affine3d a; ... Eigen::Quaterniond q(a.rotation()); Eigen::Vector3d t(a.translation());
73,823,025
73,865,813
Libssh - Can't connect to Windows host
I have some code that initiates a simple SSH client session using Libssh, but its failing at ssh_connect int main() { ssh_session my_ssh_session; int rc; int port = 22; const char* password; int verbosity = SSH_LOG_FUNCTIONS; // Open session and set options my_ssh_session = ssh_new(); if (my_ssh_session == NULL) exit(-1); ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "10.10.10.100"); ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port); ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "user"); ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity); // Connect to server rc = ssh_connect(my_ssh_session); if (rc != SSH_OK) { fprintf(stderr, "Error connecting to localhost: %s\n", ssh_get_error(my_ssh_session)); ssh_free(my_ssh_session); exit(-99); } I have changed the verbosity on the logging, and it looks like it might be something to do with a PKI signature, but I am trying to authenticate using a username and password and I am not sure how to resolve. [2022/09/23 05:27:38.440674, 2] ssh_packet_newkeys: Received SSH_MSG_NEWKEYS [2022/09/23 05:27:38.440674, 4] ssh_pki_signature_verify: Going to verify a ssh-ed25519 type signature [2022/09/23 05:27:38.440674, 4] pki_verify_data_signature: ED25519 error: Signature invalid [2022/09/23 05:27:38.440674, 3] ssh_packet_socket_callback: Processing 276 bytes left in socket buffer [2022/09/23 05:27:38.440674, 3] ssh_packet_socket_callback: Packet: processed 0 bytes [2022/09/23 05:27:38.471928, 3] ssh_packet_socket_callback: Packet: processed 0 bytes [2022/09/23 05:27:38.471928, 3] ssh_connect: current state : 9 I can connect to the SSH server using Putty with no issues. Any help greatly appreciated Update I have check the SSH logs and I can see the following: sshd[22105]: debug1: rekey in after 134217728 blocks [preauth] sshd[22105]: debug1: KEX done [preauth] sshd[22105]: debug1: Connection closed by 10.10.10.1 port 49917 [preauth] It very much looks like my program can't read the server host key file or that for some reason it doesn't like the format. I have also tried changing to RSA, but to no avail. I have also tried running ssh-keyscan on the client to verify a key is returned. C:\Users\admin>ssh-keyscan 10.10.10.100 # 10.10.10.100:22 SSH-2.0-OpenSSH_8.4p1 Debian-5+deb11u1 # 10.10.10.100:22 SSH-2.0-OpenSSH_8.4p1 Debian-5+deb11u1 # 10.10.10.100:22 SSH-2.0-OpenSSH_8.4p1 Debian-5+deb11u1 10.10.10.100 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHMq2kcCJ/hfdkxoDORhh9BfiLZ3IbGGyQ0xgBXYRgVi Update I build a Dropbear SSH box and it behaves exactly the same on there
If you build libssh statically, you must call ssh_init() early, and in a "main" context. From the manual: If libssh is statically linked, threading must be initialized by calling ssh_init() before using any of libssh provided functions. This initialization must be done outside of any threading context. Don't forget to call ssh_finalize() to avoid memory leak
73,823,210
73,823,465
template parameter incompatible with declaration
I have a function that should generate a random integer or a random floating point value. For that I want to use concepts. Since integers and floating points need different distributions, namely std::uniform_int_distribution and std::uniform_real_distribution respectively, I use a separate struct to select the correct type - also with a concept overload. The "selector" looks like this: template<std::integral I> struct distribution_selector { using type = std::uniform_int_distribution<I>; }; template<std::floating_point F> struct distribution_selector { using type = std::uniform_real_distribution<F>; }; You see that I use using to have a different type selected, depending on whether I use an integer type or a floating point type. Now my actual function: template<typename T = float, random_mode quality = random_mode::high_quality> requires std::integral<T> || std::floating_point<T> constexpr inline T rand(random& r, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()) { using distribution = distribution_selector<T>::type; if constexpr(quality == random_mode::low_quality) { return distribution<T>(min, max)(r.low_quality_engine); } else { return distribution<T>(min, max)(r.high_quality_engine); } } demo I receive the following errors (msvc): Error (active) E3244 template constraint not satisfied Runtime C:\...\rand.h 35 type constraint failed for "float" atomic constraint evaluates to false detected during instantiation of "T raid::rand(raid::random &r, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()) [with T=float, quality=raid::random_mode::low_quality]" at line 34 Error (active) E0519 type "distribution" may not have a template argument list Runtime C:\...\rand.h 37 detected during instantiation of "T raid::rand(raid::random &r, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()) [with T=float, quality=raid::random_mode::low_quality]" at line 34 What am I missing?
Use the concepts in the specialization but not in the declaration of the primary template. Also, distribution is not a template, its type is determined at its context. template <typename T> struct distribution_selector; template<std::integral I> struct distribution_selector<I> { using type = std::uniform_int_distribution<I>; }; template<std::floating_point F> struct distribution_selector<F> { using type = std::uniform_real_distribution<F>; }; template<typename T = float, random_mode quality = random_mode::high_quality> requires std::integral<T> || std::floating_point<T> constexpr inline T rand(random& r, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()) { using distribution = distribution_selector<T>::type; if constexpr(quality == random_mode::low_quality) { return distribution(min, max)(r.low_quality_engine); } else { return distribution(min, max)(r.high_quality_engine); } } Demo
73,823,283
73,823,386
Why i am getting No associated state error in below example. Could anyone tell any reason?
In below program i am getting error std::future_error: No associated state error.could anyone help why i am facing this error #include <iostream> #include <thread> #include <future> #include <chrono> #include <functional> void task(int& var, std::future<int>& refFuture) { std::packaged_task<int()> mytask{ [&](){var = 25; return var;}}; auto future = mytask.get_future(); mytask.make_ready_at_thread_exit(); refFuture = std::move(future); } int main() { int variable = 10; std::future<int> future; std::thread t1(task, std::ref(variable), std::ref(future)); std::future_status status = future.wait_for(std::chrono::seconds(0)); if(status == std::future_status::ready) { int myOutput = future.get(); std::cout << "Myoutput :" << myOutput << std::endl; } t1.join(); }
You are not waiting for the thread to actually execute refFuture = std::move(future); before you wait on future in the main thread, so the future in main does not have any associated state to wait on at that point. I am not sure what you are intending to do here, but you are supposed to prepare the std::packaged_task in the main thread, obtain the future from it in the main thread as well and then move the std::packaged_task into the thread to execute it there (per operator() or per make_ready_at_thread_exit). See e.g. the example at https://en.cppreference.com/w/cpp/thread/packaged_task/packaged_task.
73,824,767
73,825,922
stbi_write_png external symbol not solved
I can use stbi_load correctly and have the next code in a .cpp file: #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" When trying to use stbi_write_png I got a compiling error saying thats unsolved symbol. This is the code where I call the function. void FeatherGUI::saveImage() { //save the current image using stb write stbi_write_png(this->CurrentImage->name.c_str(), this->CurrentImage->width, this->CurrentImage->height, this->CurrentImage->channels, this->CurrentImage->data, this->CurrentImage->width * this->CurrentImage->channels); } What can I do?
Adding #define STBI_MSC_SECURE_CRT #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" Fixed the problem also has to change the sprintf call inside the stb_image_write to sprintf_s.
73,824,975
73,825,071
Does declaring a constexpr object marks the constructor as constexpr
I just a have a problem in understanding when the compiler marks the constructor as constexpr. If I write the following program: struct S{ S() {}; } constexpr S s{ }; Does this mean that the default constructor is marked as constexpr?
An implicitly-defined constructor is a constructor defined by the compiler implicitly when some contexts are encountered (see below). But, an explicitly-defined constructor is a constructor defined by the user, not by the compiler. Now per [class.default.ctor]/4: A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used ([basic.def.odr]) to create an object of its class type ([intro.object]), when it is needed for constant evaluation ([expr.const]), or when it is explicitly defaulted after its first declaration. The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-initializer and an empty compound-statement. If that user-written default constructor would be ill-formed, the program is ill-formed. If that user-written default constructor would satisfy the requirements of a constexpr constructor ([dcl.constexpr]), the implicitly-defined default constructor is constexpr [..] This paragraph just tells you that the non-deleted defaulted default constructor is implicitly-defined when it's odr-used or needed for constant evaluation or explicitly-defaulted after its first declaration. Also, it tells you that that implicitly-defined constructor is the same as the user-written default constructor with an empty body and no member-initializer-list. Then, it tells you that it's defined as constexpr if its corresponding user-written default constructor satisfies all of the [dcl.constexpr]/3 conditions. That's, an implicitly or explicitly defaulted constructor will be implicitly-defined as constexpr if all requirements of [dcl.constexpr]/3 are met. On other hand, neither explicitly-defined nor explicitly-declared constructor is implicitly-defined as constexpr even if it satisfies all of [dcl.constexpr]/3 that's because you explicitly defined it. But if you explicitly mark it as constexpr, it will be a constexpr constructor, meanwhile, it shall satisfy all of [dcl.constexpr]/3 conditions. So in your example: struct S{ S() {}; } constexpr S s{ }; That's ill-formed just because S is not a literal type and you're trying to call a non-constexpr constructor in a constant expression context which is not allowed per [const.expr]/(5.2)
73,825,006
73,825,180
iterate char by char through vector of strings
I want to iterate char by char in a vector of strings. In my code I created a nested loop to iterate over the string, but somehow I get an out of range vector. void splitVowFromCons(std::vector<std::string>& userData, std::vector<std::string>& allCons, std::vector<std::string>& allVows){ for ( int q = 0; q < userData.size(); q++){ std::string userDataCheck = userData.at(q); for ( int r = 0; r < userDataCheck.size(); r++){ if ((userDataCheck.at(r) == 'a') || (userDataCheck.at(r) == 'A') || (userDataCheck.at(r) == 'e') || (userDataCheck.at(r) == 'E') || (userDataCheck.at(r) == 'i') || (userDataCheck.at(r) == 'I') || (userDataCheck.at(r) == 'o') || (userDataCheck.at(r) == 'O') || (userDataCheck.at(r) == 'u') || (userDataCheck.at(r) == 'U')){ allVows.push_back(userData.at(r)); } else if ((userDataCheck.at(r) >= 'A' && userDataCheck.at(r) <= 'Z') || (userDataCheck.at(r) >= 'a' && userDataCheck.at(r) <= 'z')){ allCons.push_back(userData.at(r)); } else { continue;; } } } }
The error here is in these lines: allVows.push_back(userData.at(r)); allCons.push_back(userData.at(r)); the r variable is your index into the current string, but here you're using it to index into the vector, which looks like a typo to me. You can make this less error prone using range-for loops: for (const std::string& str : userData) { for (char c : str) { if (c == 'a' || c == 'A' || ...) { allVows.push_back(c); } else if (...) { .... } } } which I hope you'll agree also has the benefit of being more readable due to less noise. You can further simplify your checks with a few standard library functions: for (const std::string& str : userData) { for (char c : str) { if (!std::isalpha(c)) continue; // skip non-alphabetical char cap = std::toupper(c); // capitalise the char if (cap == 'A' || cap == 'E' || cap == 'I' || cap == 'O' || cap == 'U') { allVows.push_back(c); } else { allCons.push_back(c); } } }
73,825,663
73,825,870
why can I not use break?
I have written the following code for the problem: Alice has an array of NN integers — A_1, A_2, ..., A_N. She wants the product of all the elements of the array to be a non-negative integer. That is, it can be either 00 or positive. But she doesn't want it to be negative. To do this, she is willing to remove some elements of the array. Determine the minimum number of elements that she will have to remove to make the product of the array's elements non-negative. Code : #include <iostream> using namespace std; int main() { // your code goes here int t;cin>>t; while(t--){ int n;cin>>n; int res=0; bool flag=false; for(int i=0;i<n;i++){ int f;cin>>f; if(f<0){ res++; } if(f==0){ flag=true; break; } } if(res%2==0 || flag==true){ cout<<0<<endl; } else{ cout<<1<<endl; } } return 0; } I know that if I remove the break statement, the code will get correct answer for all test cases. But why can I not use break, as it will only terminate the for loop?
You need to read all input even if you do know the answer already: for(int i=0;i<n;i++){ int f;cin>>f; // ^^ ----------- !!! If you break from that loop then the numbers for the current test case are still in the stream, waiting to be read. And you do read them for the next test case. Consider this input for two test cases 0 1 2 3 2 4 0 5 1 2 3 4 But your code with the break will read for the two test cases this: 0 1 2 3 2 4 0 When you know the answer already you can continue the loop after reading input: for(int i=0;i<n;i++){ int f; cin>>f; if (flag) continue; // ...