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,174,457
73,174,566
Unresolved external symbol "enum days __cdecl operator++(enum days)" (??E@YA?AW4days@@W40@@Z) referenced in function main
I write a small program to encounter the next day by giving day. I write a program in day_enum.cpp file:- #include <ostream> #include "AllHeader.h" using namespace std; inline days operator++(days d) { return static_cast<days>((static_cast<int>(d) + 1) % 7); } ostream& operator<< (ostream& out,const days& d) { switch (d) { case SUN: out <<"SUN"; break; case MON: out <<"MON"; break; case TUE: out<<"TUES"; break; case WED: out <<"WED"; break; case THUS: out <<"THUS"; break; case FRI: out <<"FRI"; break; case SAT: out << "SAT"; break; default: break; return out; } } Now allheader.h file look like this:- #pragma once #ifndef AllHeader #define AllHeader typedef enum days { SUN, MON, TUE, WED, THUS, FRI, SAT } days; inline days operator++(days d); ostream& operator<< (ostream& out, const days& d) ; #endif In main function:- days d = MON, e; e = ++d; cout << d << '\t' << e << endl; I am getting error :- LNK2019 unresolved external symbol "enum days __cdecl operator++(enum days)" (??E@YA?AW4days@@W40@@Z) referenced in function main. As per my understanding I already declare it in allheader.h file.
According to the C++ Standard An inline function or variable shall be defined in every translation unit in which it is odr-used outside of a discarded statement. It seems in the translation unit with main there is no definition of your inline function (operator). Place the definition of the function in the header.
73,174,678
73,174,771
c++ ofstream doesn't modify files. Even the tutorial examples
I am writing a program that needs to read from one file and write to another. Using fstream, I implemented the reading part, but the writing part didn't work no matter what I tried. I tried the 'example programs' from all sorts of websites, but none of them worked. I tried changing things like file.isOpen() == false to !file and all that, but still nothing. It doesn't matter if file exists or not, ofstream functions just don't seem to work. From what I read, it seems to be a permissions issue? Besides that, I have no other clue. There are no errors or abnormal statuses reported. Everything before and after works fine while ofstream functions are just ignored. I am using Visual Studio Code, windows 10. Snippet from w3schools I tried. #include <iostream> #include <fstream> using namespace std; int main() { // Create and open a text file ofstream MyFile("filename.txt"); // Write to the file MyFile << "Files can be tricky, but it is fun enough!"; // Close the file MyFile.close(); }
@timebender I tried following code using g++.exe(cygwin windows) #include <string.h> #include <sys/errno.h> #include <iostream> #include <fstream> using namespace std; int main() { // Create and open a text file ofstream MyFile("filename.txt", ios::app|ios::out); if ( MyFile.is_open() ) { cout << "is_open pass\n"; // Write to the file MyFile << "Files can be tricky, but it is fun enough!\n"; // Close the file MyFile.close(); cout << "closed file\n"; } else { cout << "ofstream filename.txt failed\n"; cout << strerror(errno) << "\n"; } return 0; } $ g++ 73174678.cpp -o ./a.out;a.out $ ./a.out is_open pass closed file $ cat "filename.txt" Files can be tricky, but it is fun enough! $ g++.exe 73174678.cpp -o ./a.exe;./a.exe $ ./a.exe is_open pass closed file I tried your updated program.<BR> #include <string.h> #include <iostream> #include <fstream> using namespace std; int main() { ofstream ofs; system( "echo Before;cat filename.txt"); ofs.open("filename.txt", std::ofstream::out | std::ofstream::trunc); ofs<<"aaaaaaaaaaaaaaaa"; ofs.close(); system( "echo After;cat filename.txt"); return 0; } Sample output: $ a.exe Before Files can be tricky, but it is fun enough! After aaaaaaaaaaaaaaaa$ ./a.exe Before aaaaaaaaaaaaaaaaAfter aaaaaaaaaaaaaaaa$ a.exe Before aaaaaaaaaaaaaaaaAfter aaaaaaaaaaaaaaaa Hence need your expected output here ? I tried compiling your program using g++.exe at my local host.
73,174,777
73,175,178
C++ - Cannot See Created Mutex Using WinObj
I am using this really simple code to try to create a mutex int main(){ HANDLE hMutex = ::CreateMutex(nullptr, FALSE, L"SingleInstanceMutex"); if(!hMutex){ wchar_t buff[1000]; _snwprintf(buff, sizeof(buff), L"Failed to create mutex (Error: %d)", ::GetLastError()); ::MessageBox(nullptr, buff, L"Single Instance", MB_OK); return 0x1; } else { ::MessageBox(nullptr, L"Mutex Created", L"Single Instance", MB_OK); } return 0x0; } And I get the message "Mutex Created" like if it is correctly created, but when I try to search it using the tool WinObj of SysInternals I can't find it. Also if I restart the program many times while another instance is running I always get the message "Mutex Created" and never an error because the mutex already exists. I'm trying it on a Windows 7 VM. What I'm doing wrong? Ah I'm compiling on Linux using: i686-w64-mingw32-g++ -static-libgcc -static-libstdc++ Mutex.cpp Thank you!
In order to use a Windows mutex (whether a named one like yours or an unnamed one), you need to use the following Win APIs: CreateMutex - to obtain a handle to the mutex Windows kernel object. In case of a named mutex (like yours) multiple processes should succeed to get this handle. The first one will cause the OS to create a new named mutex, and the others will get a handle referring to that same mutex. In case the function succeeds and you get a valid handle to the named mutex, you can determine whether the mutex already existed (i.e. that another process already created the mutex) by checking if GetLastError returns ERROR_ALREADY_EXISTS. WaitForSingleObject - to lock the mutex for exclusive access. This function is actually not specific to mutex and is used for many kernel objects. See the link above for more info about Windows kernel objects. ReleaseMutex - to unlock the mutex. CloseHandle - to release the acquired mutex handle (as usual with Windows handles). The OS will automatically close the handle when the process exists, but it is good practice to do it explicitly. A complete example: #include <Windows.h> #include <iostream> int main() { // Create the mutex handle: HANDLE hMutex = ::CreateMutex(nullptr, FALSE, L"SingleInstanceMutex"); if (!hMutex) { std::cout << "Failed to create mutex handle." << std::endl; // Handle error: ... return 1; } bool bAlreadyExisted = (GetLastError() == ERROR_ALREADY_EXISTS); std::cout << "Succeeded to create mutex handle. Already existed: " << (bAlreadyExisted ? "YES" : "NO") << std::endl; // Lock the mutex: std::cout << "Atempting to lock ..." << std::endl; DWORD dwRes = ::WaitForSingleObject(hMutex, INFINITE); if (dwRes != WAIT_OBJECT_0) { std::cout << "Failed to lock the mutex" << std::endl; // Handle error: ... return 1; } std::cout << "Locked." << std::endl; // Do something that required the lock: ... std::cout << "Press ENTER to unlock." << std::endl; std::getchar(); // Unlock the mutex: if (!::ReleaseMutex(hMutex)) { std::cout << "Failed to unlock the mutex" << std::endl; // Handle error: ... return 1; } std::cout << "Unlocked." << std::endl; // Free the handle: if (!CloseHandle(hMutex)) { std::cout << "Failed to close the mutex handle" << std::endl; // Handle error: ... return 1; } return 0; } Error handling: As you can see in the documentation links above, when CreateMutex,ReleaseMutex and CloseHandle fail, you should call GetLastError to get more info about the error. WaitForSingleObject will return a specific return value upon error (see the documentation link above). This should be done as a part of the // Handle error: ... sections. Note: Using a named mutex for IPC (interprocess communication) might be the only good use case for native Windows mutexes. For a regular unnamed mutex it's better to use one of the available standard library types of mutexes: std::mutex,std::recursive_mutex,std::recursive_timed_mutex (the last 2 support repeated lock by a thread, similarly to Windows mutex).
73,175,240
73,175,405
C++ Fibonacci number generator not working. Why?
I just wanna know why does this method to get the fibonacci number not work thanks. #include <iostream> #include <cctype> #include <cmath> using namespace std; int fibonacci() { cout << "enter sequence num: " << endl; int num; cin >> num; int list[num] = {0, 1}; int x; if (num == 1) { cout << "the " << num << " fibo num is " << 0 << endl; } else if (num == 2) { cout << "the " << num << " fibo num is " << 1 << endl; } else { for (int y = 0; y < num - 2; y++) { // get new fibo value x = list[y] + list[y + 1]; for (int z = 2; z < num; z++) { // will append new value to the list list[z] = x; } } cout << "the " << num << " fibo num is " << list[-1] << endl; // get the last value which is the fibo value } } int main() { fibonacci(); return 0; }
There is some inconsistent indexing here. If num = 1, the fibonacci number is 0, and if num=2, the fibonacci number is 1... but this does not quite match the declaration int list[num] = {0,1}, as indexes start with 0. I have rewritten the code so that the first number has an index of 1 (list[1]=0 and list[2]=1) A nested-for loop is not needed to append the new sum at the end of the array. Just a simple for loop will do. I have modified your code below, see below. #include <iostream> #include <cctype> #include <cmath> using namespace std; int fibonacci(){ cout<<"enter sequence num: "<<endl; int num; cin>>num; int list[num]; list[1] = 0; list[2] = 1; int x; if(num==1){ cout<<"the "<<num<<" fibo num is "<<0<<endl; }else if(num==2){ cout<<"the "<<num<<" fibo num is "<<1<<endl; }else{ for(int y=3;y<=num;y++){ list[y]=list[y-1]+list[y-2]; } } cout<<"the "<<num<<" fibo num is "<<list[num]<<endl; } int main() { fibonacci(); return 0; } Hope this helps.
73,175,419
73,175,559
Safety questions when increasing vector's capacity
I've stumbled accross a case where increasing the capacity of a vector hurts one of the variables related to its element, and I would like someone to help me understanding what exactly the issue is. Let's say, I have a class MyObject and a container vector<MyObject> myVector which was already populated with 4 elements. I also have a method: MyObject* GetFirstActiveElement(vector<MyObject> vec) { for (auto& val : vec) { if (val->IsActive()) return &val; } return nullptr; } I have then a piece of code that goes as follows: MyObject myObject new MyObject(); MyObject* firstActiveElement = GetFirstActiveElement(myVector); myVector.insert(myVector.begin() + 1, myObject); After the last line, if I check firstActiveElement, if it was not nullptr sometimes it is now junk. After reading some docs, I've found that since myVector had 4 elements, and its default capacity is 4, inserting one more element causes its capacity to increase in a silent manner, whereas this C++ doc says: If new_cap is greater than capacity(), all iterators, including the past-the-end iterator, and all references to the elements are invalidated. Otherwise, no iterators or references are invalidated. I actually thought that firstActiveElement is just a pointer, so it should not be invalidated in any case. But apparently, it happens to be an interator or a reference to a vector, is that true? I'm a bit lost here, but I guess the reason is my design of the method GetFirstActiveElement().
Any access to the value returned by GetFirstActiveElement is always undefined behaviour, since the vector is passed by value to the function, inside the function you're dealing with copies of the MyObjects stored in the vector inside the calling function; those copies get destroyed when returning. Even if you pass a reference resizing the vector may result in the addresses of the vector elements changing (or rather different objects being constructed in the new backing storage by moving the old objects. The following example demonstrates this: int main() { std::vector<int> v; v.push_back(1); void* p1 = &v[0]; v.reserve(1000); void* p2 = &v[0]; std::cout << "p1=" << p1 << "\np2=" << p2 << '\n'; } Possible output: p1=000001B4B85C5F70 p2=000001B4B85D29B0 If you want to keep addresses of the MyObjects stable, you could use a std::vector<std::unique_ptr<MyObject>> which however means that the vector can only be moved, not copied.
73,175,558
73,175,852
Define a type alias in C++ templates conditionally on template arguments
I would like to write a template class along the lines of: template <typename T> struct lerp1d { lerp1d(const T& abs_begin, const T& abs_end, const T& ord_begin, const T& ord_end) {} auto operator()(val_t x) const -> val_t { // ... } const std::vector<val_t> x_data_; const std::vector<val_t> y_data_; }; Such that I can ideally initialise instances like: std::vector<double> x = /*...*/; std::vector<double> y = /*...*/; double *x = get_arr_x(); double *y = get_arr_y(); auto l1 = lerp1d(x.cbegin(), x.cend(), y.cbegin(), y.cend()); /* (1) */ auto l2 = lerp1d(x, x+n, y, y+n); /* (2) */ The question is, how to alias the val_t? One option would be to simple say: using val_t = typename T::value_type; But that does not work with instance (2). Tried std::enable_if or std::conditional with std::remove_pointer<T> and std::is_pointer_v<T>, but does not seem to be applicable.
The way you've designed it, if you provide two different types of collection having the same value_t, it will produce two different classes where there is no points of them being different, except to construct them. E.g. in (1), you would build a lerp1d<std::vector<double>::iterator> and in (2) a lerp1d<double*>. But you're ontly interested in the double part, not the vector or the pointer. I would advise to template the class on the type you're actually storing and create another template for the constructors on the iterator type. #include <vector> template <typename T> struct lerp1d { template<typename U> lerp1d(const U& abs_begin, const U& abs_end, const U& ord_begin, const U& ord_end) : x_data_(abs_begin, abs_end), y_data_(ord_begin, ord_end) {} auto operator()(T x) const -> T { return x; // to be implemented } const std::vector<T> x_data_; const std::vector<T> y_data_; }; static double xs[] = {3.2, 5.1, 4.8}; static double ys[] = {7.3, 5.3, 1.0}; int main(void) { std::vector<double> vx = {3.2, 5.1, 4.8}; std::vector<double> vy = {7.3, 5.3, 1.0}; double *x = xs; double *y = ys; auto l1 = lerp1d<double>(vx.cbegin(), vx.cend(), vy.cbegin(), vy.cend()); /* (1) */ auto l2 = lerp1d<double>(x, x+3, y, y+3); /* (2) */ }
73,175,951
73,176,080
Visual Studio 2022 - Modules (Intellisense errors)
I have 3 files, namely engineering.cpp, engineering.ixx and system.ixx. Contents briefly are: system.ixx: export module sys; export import :engineering; engineering.ixx module; #include <string> #include <vector> export module sys:engineering; namespace sys::engineering { export class Psychrometry { //more code here } } engineering.cpp module; #include <sstream> module sys:engineering; namespace sys::engineering { //implementation of the class } In another cpp file I use it as: import sys; sys::engineering::Psychrometry psy; The project compiles and works well but in engineering.cpp intellisense gives 99+ errors and code-completion and other basic facilities dont work. However, if I make the following change to engineering.cpp: //instead of module sys:engineering module sys; Now intellisense works well and the project still compiles and works. However, to my understanding the first approach (module sys:engineering) is correct rather than (module sys). What am I missing? Thanks in advance. (Visual Studio Community 2022 (64-bit) - Current Version 17.2.6)
Two module units cannot use the same module partition name. As such, sys:engineering cannot be used in two module units. No diagnostic is required, which is why you don't get a compile error. Also, if engineering.cpp is going to be a module implementation partition, then it must explicitly import the module if you want to use any of the declarations exported by the module interface. Non-partition implementation units automatically import the module interface. The only reason to make a module implementation unit a partition is if you want to import that file elsewhere (perhaps to share declarations internal to the module). Otherwise, just make them non-partition implementation units.
73,176,034
73,177,566
Why doesn't the shared pointer aliasing constructor use pass-by-value semantics
The shared pointer aliasing constructor (8 on cppreference) takes r by a constant reference. Is there a reason that value semantics are avoided? The libcxx implementation of this basically copies the two pointers and increments the reference count if applicable. shared_ptr(const shared_ptr<_Yp>& __r, element_type *__p) _NOEXCEPT : __ptr_(__p), __cntrl_(__r.__cntrl_) { if (__cntrl_) __cntrl_->__add_shared(); } Is there a reason we cannot rely on the copy constructor to increment the reference count? So something like the following: template<class _Yp> shared_ptr(shared_ptr<_Yp> __r, element_type *__p) _NOEXCEPT : __ptr_(__p), __cntrl_(__r.__cntrl_) {} This was, the caller can avoid the atomic reference increment with std::move. I see c++20 adds an r-value overload that I assume is for this purpose. But why was this chosen over switching to the simpler value semantics and having only one overload.
You are missing the destructor. your suggested implementation will decrement the count upon return from constructor (the automatic shared_ptr instance will be destructed). So if the compiler is not able to optimize to noop, you just pay the cost of two extra atomic operation for no gain and an added logical error that will backlash with a UB. Regardless of the devised semantics, the constructor must increment the count. However, your proposed solution -after fixing the bug you've introduced- combines the implementation of both r-value and l-value versions of the constructor in a by-value constructor, discarding the mandatory atomic access optimization imposed by current implementation.
73,176,122
73,176,517
Why does typeid refuse to work for function types with const at the end?
So I've got this code: template <typename T, typename class_t> struct remove_ptr_to_member { using type = T; }; template <typename T, typename class_t> struct remove_ptr_to_member<T class_t::*, class_t> { using type = T; }; class container { public: void func() const; }; void print_member_type() { std::cout << typeid(typename remove_ptr_to_member<decltype(&container::func), container>::type).name() << '\n'; } I get this error message when trying to compile it: error: non-member function of type 'typename remove_ptr_to_member<decltype(&container::func), container>::type' (aka 'void () const') cannot have 'const' qualifier As I understand it, the const at the end of the function is part of it's type. Is typeid not accepting it because it's an invalid type (since non-member functions can't have const at the end)? Why is it that I can create a type that shouldn't actually exist? How would I go about removing the const, so as to make everything compile properly?
A function type with const or other cvref-qualifiers is a valid type in the language, but it has very limited uses, mainly to declare non-static member functions and to form pointers to non-static member functions. Therefore the standard has restrictions on where they may be used, listed in [dcl.fct]/6. In particular this list does not include the operand of typeid. As a consequence you are not allowed to use such a function type as operand of typeid. This was also subject of an editorial issue which resulted in a note being added to the description of typeid in the standard to make it clear that this is not permitted. So, although there is nothing wrong with how you obtain the function type, you can't use it as typeid operand. Unfortunately I don't think there is any type trait in std:: that allows you to remove the cvref qualifiers from the function type. These can be implemented by yourself, but implementing such traits on qualified function types is notoriously tedious because there are (if I didn't miscount) 24 overloads or partial specializations for all possible combinations of cvref and noexcept qualifiers required. (Actually 48 to include variadic functions.) See for example this older question about it. However note that this question is pre-C++17. Since C++17 function types with and without noexcept need to also be differentiated. Instead you might want to have a look at Boost.CallableTraits which has a list of remove_* type traits which you can use to remove the const/volatile/&/&&-qualifiers.
73,176,500
73,179,059
How to convert string from UCS2 to readable text
I need to convert the given string from UCS2 to readable text. How can I implement this in Python and C++ Arduino without using third-party modules. st ="041204410451002004210443043F04350440003A00200031003300200413041100200438043D044204350440043D043504420430002C00200031003500300020043C0438043D00200030002004410435043A0020043D04300020043C043E04310438043B044C043D044B043500200420041A00200434043E002000320037002E00300038002E00320032" I found this code, but it does not work as it should. Can you please tell me how to do the correct calculation? def con(): UCS2ToChar = '' res = "" arrUCS2 = list("0412") if (arrUCS2[1] == '4'): if (arrUCS2[2] == '0'): UCS2ToChar = 89 elif (arrUCS2[2] == '1'): UCS2ToChar = 64 elif (arrUCS2[2] == '2'): UCS2ToChar = 48 elif (arrUCS2[2] == '3'): UCS2ToChar = 32 elif (arrUCS2[2] == '4'): UCS2ToChar = 16 elif (arrUCS2[2] == '4'): UCS2ToChar = 73 if (int(arrUCS2[3]) > int('9')): UCS2ToChar -= (int(arrUCS2[3]) - 55) else: UCS2ToChar -= (int(arrUCS2[3]) - int('0')) UCS2ToChar = (int(UCS2ToChar)) res += (chr(UCS2ToChar)) print(res) con() If you do this print (ord ('B')) then the code of the letter (which, in theory, is encrypted there) will be different from that obtained using this enumeration.
Based on Python UCS2 decoding from hex string - Stack Overflow import binascii st = "041204410451002004210443043F04350440003A00200031003300200413041100200438043D044204350440043D043504420430002C00200031003500300020043C0438043D00200030002004410435043A0020043D04300020043C043E04310438043B044C043D044B043500200420041A00200434043E002000320037002E00300038002E00320032" text = binascii.unhexlify(st).decode('utf-16-be') print(text) or import codecs st = "041204410451002004210443043F04350440003A00200031003300200413041100200438043D044204350440043D043504420430002C00200031003500300020043C0438043D00200030002004410435043A0020043D04300020043C043E04310438043B044C043D044B043500200420041A00200434043E002000320037002E00300038002E00320032" text = codecs.decode(st, 'hex').decode('utf-16-be') print(text) Result: Всё Супер: 13 ГБ интернета, 150 мин 0 сек на мобильные РК до 27.08.22 binascii and codecs are standard modules preinstalled with Python.
73,177,115
73,180,796
Can asan issue trap upon violation like ubsan does?
Minimum reproducible example: https://godbolt.org/z/4hje5h1js A great feature of ubsan (undefined behavior sanitizer) is to issue a trap that breaks into gdb when an issue occurs. This is turned on with -fsanitize-undefined-trap-on-error. However asan (address sanitizer) does not seem to have such option. Is that correct or I'm missing the proper documentation? If not, is there anything intrinsic about address sanitizer that prevents it doing a trap? Compiling with clang 10.0 on Ubuntu 20.04 LTS.
For historical reasons Asan simply exits the application on error but you can ask it to abort (which will be intercepted by gdb) by setting environment variable: export ASAN_OPTIONS=abort_on_error=1 Or you could simply set a breakpoint at __asan_report_error in gdb.
73,177,342
73,177,661
c++ triangle rasterization using edge detection
I am trying to implement triangle rasterization using this article as reference https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/rasterization-stage as such I have implemented an edge function with an input of 3 points. 2 defining a line and one as the point to be tested, annotated as p bool SoftwareRendererImp::edgeFunction(float xa, float ya, float xb, float yb, float xp, float yp) { return ((xp - xa) * (yb - ya) - (yp - ya) * (xb - xa) >= 0); } in my rasterization function I am iterating over a set of integers ranging from the lowest to highest x and y values. This is to try and iterate over a box of best fit containing the triangle and test each point to see if it is contained in the triangle. void SoftwareRendererImp::rasterize_triangle(float x0, float y0, float x1, float y1, float x2, float y2, Color color) { // Task 3: // Implement triangle rasterization cout << "triangle----------------------------------------------------------------------------------------------------------------------- \n"; float minX = std::min(x0, x1); minX = std::min(minX, x2); float minY = std::min(y0, y1); minY = std::min(minY, y2); float maxX = std::max(x0, x1); maxX = std::max(maxX, x2); float maxY = std::max(y0, y1); maxY = std::max(maxY, y2); bool inside; float px, py; for (int x = minX; x < maxX; x++) { for (int y = minY; y < maxY; y++) { inside = true; px = x + 0.5f; py = y + 0.5f; inside &= SoftwareRendererImp::edgeFunction(x0, y0, x1, y1, px, py); inside &= SoftwareRendererImp::edgeFunction(x1, y1, x2, y2, px, py); inside &= SoftwareRendererImp::edgeFunction(x2, y2, x0, y0, px, py); if (inside) { SoftwareRendererImp::rasterize_point(x, y, color); cout << "inside: " << x << ", " << y << "\n"; } else { // cout << "outside: " << x << ", " << y << "\n"; } } } } From my understanding of the linked article this should work however it is not. Can anyone spot what it is that I am screwing up?
this expression was backwards (xp - xa) * (yb - ya) - (yp - ya) * (xb - xa) it should have been (yp - ya) * (xb - xa) - (xp - xa) * (yb - ya)
73,177,421
73,363,765
Makefile Errors while building megasdk python in Alpine Edge Docker
I recently am facing problems on building MegaSdkC+ python wheel on alpine edge Linux docker ...I currently tried to port it via the Ubuntu Dockerfile Error: #8 184.6 In file included from /usr/include/openssl/bio.h:20, #8 184.6 from /usr/include/openssl/ssl.h:18, #8 184.6 from ./include/mega/posix/meganet.h:28, #8 184.6 from ./include/mega.h:74, #8 184.6 from src/posix/net.cpp:22: #8 184.6 src/posix/net.cpp: In constructor 'mega::CurlHttpIO::CurlHttpIO()': #8 184.6 src/posix/net.cpp:272:10: error: converting to 'bool' from 'std::nullptr_t' requires direct-initialization [-fpermissive] #8 184.6 272 | if (!CRYPTO_get_locking_callback() #8 184.6 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~ #8 184.6 src/posix/net.cpp:274:13: error: converting to 'bool' from 'std::nullptr_t' requires direct-initialization [-fpermissive] #8 184.6 274 | && !CRYPTO_THREADID_get_callback()) #8 184.6 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ #8 185.1 make[2]: *** [Makefile:2767: src/posix/libmega_la-net.lo] Error 1 #8 185.1 make[2]: *** Waiting for unfinished jobs.... #8 187.0 mv -f src/posix/.deps/libmega_la-waiter.Tpo src/posix/.deps/libmega_la-waiter.Plo #8 187.0 make[2]: Leaving directory '/root/home/sdk' #8 187.0 make[1]: *** [Makefile:3347: all-recursive] Error 1 #8 187.0 make[1]: Leaving directory '/root/home/sdk' #8 187.0 make: *** [Makefile:1517: all] Error 2 Here is the direct logs of the errors of which is built via github actions: https://github.com/AmirulAndalib/MLTB-ALPINE-DOCKER/runs/7592589121?check_suite_focus=true#step:9:995 Tried to port from Ubuntu .. Dockerfile and Github Actions build logs are given below Logs https://github.com/AmirulAndalib/slumtoolkit0-docker/runs/7595322451?check_suite_focus=true Dockerfile https://github.com/AmirulAndalib/slumtoolkit0-docker/blob/master/Dockerfile For alpine Build Dockerfile https://github.com/AmirulAndalib/MLTB-ALPINE-DOCKER/blob/master/Dockerfile%20Base/Dockerfile Gitflow Logs https://github.com/AmirulAndalib/MLTB-ALPINE-DOCKER/runs/7592589121?check_suite_focus=true MegaSdkC Repository https://github.com/meganz/sdk
Thank you @mpb I had added the -fpermissive flag as you told and the errors were actually downgraded to warnings also my built code is working very well Fix : https://github.com/AmirulAndalib/MLTB-ALPINE-DOCKER/blob/master/Dockerfile%20Base/Dockerfile#L45 thank you very much for helping
73,177,618
73,178,073
winuser.h keyboard input char to hex convertion
I've been searching and testing this for a while now and haven't found an answer to the problem i have. What i'm trying to do is make my own kind of library for mouse and keyboard simulated keypress. I'm trying to do this for a fun little project where i can automate some tasks that are impossible to integrate with any other way. Simulating a user this way would be handy. My problem lies with keyboard key presses. to be more precise here's an example code for pressing the letter 'a' on the keyboard: INPUT inputs[2] = {}; inputs[0].type = INPUT_KEYBOARD; inputs[0].ki.wVk = 0x41; inputs[1].type = INPUT_KEYBOARD; inputs[1].ki.wVk = 0x41; inputs[1].ki.dwFlags = KEYEVENTF_KEYUP; SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT)); This works fine. So i tried to make it into a variable: void keyboardKeyPress(char key) { INPUT inputs[2] = {}; inputs[0].type = INPUT_KEYBOARD; inputs[0].ki.wVk = key; inputs[1].type = INPUT_KEYBOARD; inputs[1].ki.wVk = key; inputs[1].ki.dwFlags = KEYEVENTF_KEYUP; SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT)); } This also works fine. BUT as soon as i iterate through a string using this function, it outputs something weird. i tested this with the string "hello" and it outputs "85/". Here's the code i'm using: #include <iostream> #include <cmath> #include <windows.h> #include <winuser.h> using namespace std; void keyboardKeyPress(char key) { INPUT inputs[2] = {}; inputs[0].type = INPUT_KEYBOARD; inputs[0].ki.wVk = key; inputs[1].type = INPUT_KEYBOARD; inputs[1].ki.wVk = key; inputs[1].ki.dwFlags = KEYEVENTF_KEYUP; SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT)); } void keyboardType(const string str) { for(int i = 0; i < str.length(); i++) { keyboardKeyPress(str[i]); } } int main() { keyboardKeyPress(65); keyboardKeyPress(66); keyboardKeyPress(' '); keyboardType("hello"); return 0; } It outputs "ab 85/". I tried to do many things. i realised you can use hex codes instead of chars because the .ki.wVk actually wants unsigned short's. it works when you plug the values in statically but as soon as you try to get the hex values from an eg unsigned short array, it goes back to displaying "85/". The array: WORD ascii[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F }; The array index is basically the ascii integer number and the value stored is the unsigned short (or WORD from winuser). And here's the changed function: void keyboardKeyPress(char key) { INPUT inputs[2] = {}; inputs[0].type = INPUT_KEYBOARD; inputs[0].ki.wVk = ascii[int(key)]; inputs[1].type = INPUT_KEYBOARD; inputs[1].ki.wVk = ascii[int(key)]; inputs[1].ki.dwFlags = KEYEVENTF_KEYUP; SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT)); }
Your functions don't work as expected because ASCII codes are not Virtual Key codes, though there is some overlap but not the way you think. The A and B keys on the keyboard are represented by virtual key codes VK_A (65/0x41) and VK_B (66/0x42), respectively. They also happen to be the same values as the ASCII codes for the 'A' and 'B' characters, not the 'a' (97/0x61) and 'b' (98/0x62) characters. When typing on a keyboard, uppercase and lowercase letters are differentiated by whether the Shift key (virtual key code VK_SHIFT, 16/0x10) is held down or not. Since you are not simulating the Shift key being held down, that is why keyboardKeyPress(65) and keyboardKeyPress(66) are outputting a and b. However, the ASCII code for the 'h' character (104/0x68) is the same value as the virtual key code VK_NUMPAD8. The H key on the keyboard is represented by virtual key code VK_H (72/0x48) instead. The 'e' character is ASCII code 101/0x65, aka virtual key code VK_NUMPAD5, not VK_E (69/0x45). The 'l' character is ASCII code 108/0x6C, aka virtual key code VK_SEPARATOR (which does not represent any ASCII character) , not VK_L (76/0x4C). The 'o' character is ASCII code 111/0x6F, aka virtual key code VK_DIVIDE, not VK_O (79/0x4F). That is why keyboardType("hello") is outputting 85/. Also, your ascii[] array is useless, because it is simply mapping the character codes back to their original values as-is, not to the proper virtual key codes. So, to fix your code, you would have to get rid of the ascii[] array, and instead add additional logic to "hold down" the VK_SHIFT virtual key for an uppercase letter if it is not currently down, and "release" it for a lowercase letter if it is currently down. And then things get more complex if you need to deal with languages that have non-ASCII characters, etc. That said, simulating textual characters is much easier if you use the KEYEVENTF_UNICODE flag. Use virtual key codes only for non-textual keys. And you should send the entire string as one atomic unit instead of sending each character individually (injecting multiple events atomically into the event queue is one of the key features of SendInput() over keybd_event()). See my previous answer for an example of using SendInput() with strings.
73,177,689
73,178,090
this c++ code of file handling runs in dev c++ but not in vs code
newbie here my code doesn't seem to compile in vscode. It give me the desired output while using dev c++. It gives me error while reading from file, writing to a file no problem. I have posted error message below the code. #include <iostream> #include <fstream> #include <string.h> using namespace std; class student{ private: char name[25]; int id; int age; public: void get(){ cin>>name>>id>>age; } void show(){ cout<<name<<id<<age; } void write2file(){ ofstream outfile("student.dat",ios::binary|ios::app); get(); outfile.write(reinterpret_cast<char*>(this),sizeof(*this)); } void readfromfile(){ ifstream infile("student.dat",ios::binary|ios::in); while(!infile.eof()){ if(infile.read(reinterpret_cast<char*>(this),sizeof(*this))>0){ show(); } } } }; int main(){ student s; s.write2file(); s.readfromfile(); return 0; } Here is the error I got when I run the program in VS code, but same program run perfectly in dev c++. awd.cpp: In member function 'void student::readfromfile()': awd.cpp:26:76: error: no match for 'operator>' (operand types are 'std::basic_istream<char>::__istream_type' {aka 'std::basic_istream<char>'} and 'int') 26 | if(infile.read(reinterpret_cast<char*>(this),sizeof(*this))>0){ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~ | | | | | int | std::basic_istream<char>::__istream_type {aka std::basic_istream<char>} awd.cpp:26:76: note: candidate: 'operator>(int, int)' (built-in) 26 | if(infile.read(reinterpret_cast<char*>(this),sizeof(*this))>0){ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~ awd.cpp:26:76: note: no known conversion for argument 1 from 'std::basic_istream<char>::__istream_type' {aka 'std::basic_istream<char>'} to 'int' In file included from C:/msys64/mingw64/include/c++/12.1.0/string:47, from C:/msys64/mingw64/include/c++/12.1.0/bits/locale_classes.h:40, from C:/msys64/mingw64/include/c++/12.1.0/bits/ios_base.h:41, from C:/msys64/mingw64/include/c++/12.1.0/ios:42, from C:/msys64/mingw64/include/c++/12.1.0/ostream:38, from C:/msys64/mingw64/include/c++/12.1.0/iostream:39, from awd.cpp:1:
Better code would be this void readfromfile(){ ifstream infile("student.dat",ios::binary|ios::in); while (infile.read(reinterpret_cast<char*>(this),sizeof(*this)) { show(); } } As already pointed out istream::read does not return an integer, which is what the original code seems to be assuming. Instead, like most I/O functions, the stream itself is returned. In a boolean context this can be used to see if the stream is in a good state. If it is not then the previous I/O operation failed.
73,177,944
73,178,262
Is std::views::keys guaranteed to work correctly with any pair/tuple type?
Code is pasted here & https://www.godbolt.org/z/qszqYsT4o I am attempting to provide boost::adaptors::indexed functionality that is compatible with c++20 views. My primary use case is for std::vector, but I would definitely prefer a generic solution. I was shocked to discover that std::views::keys did not work as expected to extract the first element correctly. For GCC 10.3, the output of rng1 is garbage and rng2 is as expected. GCC 10.4+ works fine. The latest version of clang fails to compile the code. Questions: Is std::views::keys guaranteed to support any pair/tuple type, or is my code UB? Given clang 14.0.0 fails to compile, is my code legal C++? Is there a better way to achieve this functionality in c++20? I was looking at std::span for a bit, but couldn't seem to make it work naturally. Note: I would have gladly used std::views::zip with std::views::iota if it were available. #include <vector> #include <ranges> #include <iostream> template <typename T> using IndexValuePair = std::pair<std::size_t, std::reference_wrapper<T>>; template <typename T, typename Allocator> auto make_indexed_view(std::vector<T, Allocator>& vec) { auto fn = [&vec](T& val) { return IndexValuePair<T>{static_cast<std::size_t>(&val - vec.data()), val}; }; return std::views::all(vec) | std::views::transform(fn); } template <typename T, typename Allocator> auto make_indexed_view(const std::vector<T, Allocator>& vec) { auto fn = [&vec](const T& val) { return IndexValuePair<const T>{static_cast<std::size_t>(&val - vec.data()), val}; }; return std::views::all(vec) | std::views::transform(fn); } struct GetFirstSafely { template <typename T1, typename T2> const T1& operator()(const std::pair<T1, T2>& p) const { return std::get<0>(p); } template <typename T1, typename T2> T1 operator()(std::pair<T1, T2>&& p) const { return std::get<0>(std::move(p)); } }; auto get_first = [](auto&& p) -> decltype(auto) { return GetFirstSafely{}(std::forward<decltype(p)>(p)); }; int main() { const std::vector<int> v{10, 20, 30}; auto fn = [](const auto& val) { return val.second >= 20; }; auto rng1 = make_indexed_view(v) | std::views::filter(fn) | std::views::keys; auto rng2 = make_indexed_view(v) | std::views::filter(fn) | std::views::transform(get_first); for (auto&& elem : rng1) std::cout << elem << '\n'; for (auto&& elem : rng2) std::cout << elem << '\n'; return 0; }
This was LWG 3502. Your code fails on gcc 10.3 because of that particular issue, but it has been resolved and your code works fine on gcc 10.4 (or 11.1, etc.). The example in the issue there should look familiar: std::vector<int> vec = {42}; auto r = vec | std::views::transform([](auto c) { return std::make_tuple(c, c); }) | std::views::keys; It failed because operator* for elements_view was specified as: constexpr decltype(auto) operator*() const { return get<N>(*current_); } And when the Nth element is a prvalue (as it is in that example and your example), this is an immediately-dangling rvalue reference. The resolution in the issue ensures that operator* in these cases returns a prvalue, so everything works fine. Note that there's no reason to write: return std::views::all(vec) | std::views::transform(fn); The range adaptors already do that for you. You can just write: return vec | std::views::transform(fn);
73,178,514
73,178,543
A question about dynamic memory allocation 2
After a few years, I discovered a memory leak bug in my code. Unfortunately the bug was not causing any issues to be noticed until I found out about it indirectly. Below is a function addElement() from class c_string which adds a new element to a chain. My old way of doing it is like this: class c_string { private: char *chain; size_t chain_total; public: void addElement(char ch); }; void c_string::addElement(char ch) { char *tmpChain = new char[chain_total+1]; for(size_t i=0;i<chain_total;i++) tmpChain[i] = chain[i]; tmpChain[chain_total++] = ch; delete chain; chain = new char[chain_total]; chain = tmpChain; } I found out that by doing chain = tmpChain; I am causing a memory leak. My question is, what is the best way to handle it? Please note, in this class I am not using any STL function, because I am simply writing my own string.
The best way to do it is simply drop the second allocation, it serves no purpose. void c_string::addElement(char ch) { char *tmpChain = new char[chain_total+1]; for(size_t i=0;i<chain_total;i++) tmpChain[i] = chain[i]; tmpChain[chain_total++] = ch; delete[] chain; chain = tmpChain; } The above is correct and even has the strong exception guarantee. Of course even if you do not want to use std::string, std::unique_ptr would is still safer than raw new+delete and you would get the rule of five for free instead of having to implement it on your own. From performance standpoint, you might be interested in Why is it common practice to double array capacity when full? and of course std::memcpy or std::copy instead of the manual loop.
73,178,604
73,178,894
Possible way to get rid of abominable function types in C++?
So I was recently exposed to the grotesqueness that is the so-called "abominable function type" in C++ (originates from this paper as far as I know: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0172r0.html). I thought about it for a while and it does seem to make some amount of sense, but everything would be much cleaner and more satisfying if one were to somehow remove them from the language completely. Maybe there are other points of origin, but (for me at least) most issues with abominable function types come from handling member functions. If I want to get the type of a member function, I do something like this: template <typename T> struct remove_ptr_to_member { using type = T; }; template <typename T, typename class_t> struct remove_ptr_to_member<T class_t::*> { using type = T; }; struct container { void func() const; }; using member_function_type = typename remove_ptr_to_member<decltype(container::func)>::type; Since there exists a const in the declaration of func(), removing the pointer-to-member part leaves us with an abominable function. This could be avoided if one were to put the invisible this argument into the type of member functions. Then, the things that would normally cause an abominable function would all be applied to the this argument (const would mean a const this pointer, && would mean an rvalue reference to an instance of this, etc...). Now, even if you remove the pointer-to-member part of the type, all that you're left with is a totally normal function type. The great thing about this would be that it would cut down on the amount of boiler-plate you have to write when implementing things like is_function. Classic method: // primary template template<class> struct is_function : std::false_type { }; // specialization for regular functions template<class Ret, class... Args> struct is_function<Ret(Args...)> : std::true_type {}; // specialization for variadic functions such as std::printf template<class Ret, class... Args> struct is_function<Ret(Args......)> : std::true_type {}; // specialization for function types that have cv-qualifiers template<class Ret, class... Args> struct is_function<Ret(Args...) const> : std::true_type {}; template<class Ret, class... Args> struct is_function<Ret(Args...) volatile> : std::true_type {}; template<class Ret, class... Args> struct is_function<Ret(Args...) const volatile> : std::true_type {}; // etc... (goes on for a while) New method: // primary template template <typename> struct is_function : std::false_type { }; // specialization for regular functions template<typename Ret, typname... Args> struct is_function<Ret(Args...)> : std::true_type { }; // specialization for variadic functions such as std::printf template<typename Ret, typname... Args> struct is_function<Ret(Args......)> : std::true_type { }; // same thing but with noexcept template<typename Ret, typname... Args> struct is_function<Ret(Args...) noexcept> : std::true_type { }; template<typename Ret, typname... Args> struct is_function<Ret(Args......) noexcept> : std::true_type { }; And that would be it. No long boiler-plate required, since all the intricasies (const, volatile, etc...) are hidden within the first argument. I'm sorry for waiting so long before asking the actual question, but the time has come: Does anyone have a counter-argument to this fix? Is it even a fix, maybe it doesn't deal with everything there is to deal with? I guess what I'm wondering is, why this isn't in the standard? If it's such a great idea, someone must have thought of it right? There has got to be some extra information that I haven't considered, because this seems too simple.
Pretty much exactly what you are suggesting has already been accepted for C++23 as member functions with explicit object parameters like this: struct container { void func(this container const&); }; The type of this function is then void(container const&) instead of void() const or equivalently the type of &container::func will be void(*)(container const&) instead of void (container::*)() const. See P0847 which introduced this new feature. But that is not going to change that the old-style non-static member functions with implicit instead of explicit object parameter need to have the cvref-qualified function types. Changing the type of these functions would break a lot of code, so it is too late for that.
73,178,843
73,178,891
c++ portable address encoding
I'm writing a software that, at some point must write internal addresses into a buffer. I wrote the following code which works. But produce warnings when cross-compiling to a target device with an address size smaller than 64 bits. How can I make this portable without generating errors? I would have expected gcc to ignore the warning due to the condition-always-false around the problematic statement. I get the same behaviour when doing this with a template (where i feed sizeof(void*()) as address_size). uint8_t decode_address_big_endian(uint8_t* buf, uintptr_t* addr) { constexpr unsigned int addr_size = sizeof(void*); static_assert(addr_size == 1 || addr_size == 2 || addr_size == 4 || addr_size == 8, "Unsupported address size"); uintptr_t computed_addr = 0; unsigned int i = 0; if (addr_size >= 8) { computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 56)); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 48)); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 40)); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 32)); } if (addr_size >= 4) { computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 24)); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 16)); } if (addr_size >= 2) { computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 8)); } if (addr_size >= 1) { computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 0)); } *addr = computed_addr; return static_cast<uint8_t>(addr_size); } The code works. MSVC is able to optimize that to a single x86_64 instruction. It also works on a AtMega328p, but avr-gcc do throw these warnings. /home/py/scrutiny-embedded/lib/src/protocol/scrutiny_protocol_tools.cpp:32:72: warning: left shift count >= width of type [-Wshift-count-overflow] computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 56)); ^ /home/py/scrutiny-embedded/lib/src/protocol/scrutiny_protocol_tools.cpp:33:72: warning: left shift count >= width of type [-Wshift-count-overflow] computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 48)); ^ /home/py/scrutiny-embedded/lib/src/protocol/scrutiny_protocol_tools.cpp:34:72: warning: left shift count >= width of type [-Wshift-count-overflow] computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 40)); ^ /home/py/scrutiny-embedded/lib/src/protocol/scrutiny_protocol_tools.cpp:35:72: warning: left shift count >= width of type [-Wshift-count-overflow] computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 32)); ^ /home/py/scrutiny-embedded/lib/src/protocol/scrutiny_protocol_tools.cpp:40:72: warning: left shift count >= width of type [-Wshift-count-overflow] computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 24)); ^ /home/py/scrutiny-embedded/lib/src/protocol/scrutiny_protocol_tools.cpp:41:72: warning: left shift count >= width of type [-Wshift-count-overflow] computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << 16)); ^ In this case, I can make a static_assert on address_size to prove that it is indeed equal to 2. But still get the warnings.
Try if constexpr (addr_size >= 8) If C++17 is not available to you, you can suppress the warning if (addr_size >= 8) { computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << ((addr_size >= 8) * 56))); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << ((addr_size >= 8) * 48))); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << ((addr_size >= 8) * 40))); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << ((addr_size >= 8) * 32))); } If addr_size >= 8 is true, it evaluates to 1 in the multiplication arguments. Otherwise, it would evaluate to 0, but the branch is not executed. Shorter with @RaymondChen's hint. if (addr_size >= 8) { computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << (56 % (addr_size * 8)); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << (48 % (addr_size * 8)); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << (40 % (addr_size * 8)); computed_addr |= ((static_cast<uintptr_t>(buf[i++]) << (32 % (addr_size * 8)); } // Will be shorter with constexpr unsigned int addr_size = sizeof(void*) * 8; Alternative code if (addr_size >= 8) { uint64_t tmp; tmp = static_cast<uintptr_t>(buf[i++]) << 28; computed_addr |= tmp << 28; tmp = static_cast<uintptr_t>(buf[i++]) << 24; computed_addr |= tmp << 24; tmp = static_cast<uintptr_t>(buf[i++]) << 20; computed_addr |= tmp << 20; tmp = static_cast<uintptr_t>(buf[i++]) << 16; computed_addr |= tmp << 16; }
73,179,104
73,179,148
How to resolve Exception Error in C++ Builder
I am in the process of converting an older DOS based 16-bit application into a current Windows console app. Each time I run the application in debug mode I receive the following error: Project xxxx.exe raised exception class $C0000005 with message 'access violation at 0x004151f9: read of address 0x00000000'. The following is the code line that blows up: if ((argc < 1) || (strcmp(argv[1],"/?")) == 0) prg_syntax(); The code evaluates and should run the function to display the programs syntax but doesn't and instead throws the error. I am using C++ Builder version (11.1.5). Any help of where or how to overcome I would greatly appreciate. Thanks, Kent
By the convention argc cannot be lower than 1, because it will have at least the name / symbolic link to the execution (binary) file. In the case of no arguments passed to your program it will try to deference NULL pointer (the last element of argv[]). if ((1 < 1) || (strcmp(NULL,"/?")) == 0) prg_syntax(); I believe you've wanted to do something like this: if ((argc < 2) || (strcmp(argv[1],"/?")) == 0) prg_syntax();
73,179,805
73,179,941
Control dimension of vector at run time
I am working on a program that needs to be able to create vectors with different dimensions at runtime. I know that C++ templates are a compile time feature, and I am not sure how to work around this currently. I have seen some examples that use if statements to control the allocation of memory like so: if (some_condition == 1) { std::vector<int> x; } else if (some_condition == 2) { std::vector<std::vector<int>> x; } // repeat for how ever many times This works fine as a temporary solution, but I would really like there to be a way to control the dimension of a created vector without brute forcing if else statements up to some arbitrary number. If it is not possible would it be possible to make my own vector class, but with fixed types? I have tried making a 1 dimensional vector and using math to index it like a multi dimensional vector, but this seems to get complicated fast. template<typename class_name> class rvector { std::vector<class_name> items; int depth; // Some collection type that lays out the format of all the items }
This is a way to implement the recursive template application: #include <iostream> #include <vector> #include <type_traits> template<typename T> struct ID {}; template<size_t i, typename U> auto n_dim_vec_gen(U u) { if constexpr (i) { return n_dim_vec_gen<i - 1>(std::vector<U>()); } else { return u; } } template<typename T, size_t i> using n_dim_vec = decltype(n_dim_vec_gen<i>(std::declval<T>())); static_assert(std::is_same<n_dim_vec<int, 1>, std::vector<int>>::value); static_assert(std::is_same<n_dim_vec<int, 2>, std::vector<std::vector<int>>>::value); If you'd also like to standardize the some_condition processing, then you need to make a runtime - to - compile-time bridge (a simple switch statement works) and then apply the lambda. You might generate the branches of the switch using e.g. BOOST_PP_FOREACH, but that might be a little overkill. Then apply the pre-defined lambda. auto whatToDo = [&](auto x, auto depth) { // note that depth's type is compile-time // integral_constant, so you can use it in e.g. // if constexpr and template arguments n_dim_vec<int, depth> x; // ... }; // this is the runtime - to - compile-time bridge switch (some_condition) { #define CASE(I) case I: whatToDo(std::integral_constant<int, I>()); break; CASE(1) CASE(2) CASE(3) // ... #undef CASE };
73,179,808
73,200,480
How to transfer elements of 1 vector into another vector?
I am learning C++ and decided to make a card deck system using vectors. I have been able to randomly shuffle it, make 1 singular deck, and now I want to make a function that deals a hand from that deck. Say I wanted a hand of 10 cards from a deck of 52 cards, therefore 42 cards would be left and the first 10 cards of the Deck vector will be taken and placed into the newHand vector but after looking for solutions on how to approach this using erase() and pop_back(), I cant seem to find an efficient or proper solution. However since I am new to C++ my code might not be the best thing to look at so I am open for suggestions on how to make this better, maybe with pointers? (Pointers are confusing to me and I am not sure when to use them). Here are the main functions: void Deck::deleteElement(std::vector<std::string> Deck, int index) { while (index--) { Deck.erase(Deck.begin(), Deck.begin() + index); } } void Deck::dealHand(int numOfCards, std::vector<std::string>& currentDeck, int numOfDecks) { std::vector<std::string> newHand; static int remaining = deckSize(numOfDecks); while (numOfCards-- && remaining != 0) { newHand.push_back(currentDeck[numOfCards]); --remaining; } deleteElement(currentDeck, numOfCards); for (auto & i : newHand) { std::cout << i << " "; } std::cout << ",there are now " << remaining << " cards remaining" << std::endl; } I want to mention that deleteElement when using erase gives me this error malloc: *** error for object 0x16f9ddf40: pointer being freed was not allocated malloc: *** set a breakpoint in malloc_error_break to debug I also could not find much on explaining what this means, if anyone can that would be a great help.
I would probably not bother with actually erasing elements from the deck's internal vector. That's because you might want to reshuffle and deal cards multiple times over the course of a game, which is easier if you just keep them all in the deck and track which ones have been dealt. And since almost everything container-related uses iterators, you can keep it short and simple like this: #include <iterator> #include <vector> class Card {}; class Deck { public: using Cards = std::vector<Card>; // Just an example constructor explicit Deck(std::size_t size = 52) : m_cards(size), m_current{m_cards.begin()} {} Cards dealHand(std::size_t count) { auto begin = m_current; std::ranges::advance(m_current, count, m_cards.end()); return Cards(begin, m_current); } std::size_t size() const { return std::ranges::distance(m_current, m_cards.end()); } private: Cards m_cards; Cards::iterator m_current; }; int main() { Deck deck {}; auto hand = deck.dealHand(10); return deck.size(); } While it's not strictly necessary to use std::ranges functions (they have equivalents in the std namespace), this part of C++20 is now widely supported. One advantage is that range algorithms accept entire ranges (such as containers) instead of only pairs of iterators, for example std::ranges::shuffle.
73,179,838
73,180,520
How to prove c++11 make_shared() can keep shared_ptr's control block alive even after its dtor?
My question is: is there a case that share_ptr ref count is 0, while weak_ptr ref count is not 0? Difference in make_shared and normal shared_ptr in C++ Referr this thread, showing that if a shared_ptr is created by make_shared and there's weak_ptr, its control block will be alive until both shared_ptr and weak_ptr's ref count gets 0. It says: There must be a way for weak_ptrs to determine if the managed object is still valid (eg. for lock). They do this by checking the number of shared_ptrs that own the managed object, which is stored in the control block. The result is that the control blocks are alive until the shared_ptr count and the weak_ptr count both hit 0. I had a quick test. I hope the shared_ptr created by make_shared, if there's weak_ptr pointing to it, its control block will still hold sth after shared_ptr is destructed. #include<memory> #include<iostream> using namespace std; struct My { int m_i; My(int i) : m_i(i) { cout << "My ctor:" << m_i << '\n';} ~My() { cout << "My ctor:" << m_i << '\n';} }; weak_ptr<My> wp1, wp2; int main() { { auto sp1 = shared_ptr<My>(new My(30)); wp1 = weak_ptr<My>(sp1); } cout<< wp1.use_count() << endl; { auto sp2 = make_shared<My>(40); wp2 = weak_ptr<My>(sp2); } cout<< wp2.use_count() << endl; return 0; } Both use_count will print 0, my program didn't seems to show whether the control blocks is alive or not. So, how can we prove that The result is that the control blocks are alive until both shared_ptr and weak_ptr's ref count gets 0? Any sample code that could test/prove this theory?
Your code couldn't prove, because sp1,sp2 are local variables, they will be released when they out of range. And you could use hook or froce jump to show the result you want to see, but it's not easy. We could read the source code of weak_ptr, so we can know about what really does, the souce code of weak_ptr is too much, we just view the key segment: // The actual weak_ptr, with forwarding constructors and // assignment operators. template<typename _Tp> class weak_ptr : public __weak_ptr<_Tp> { }; From the code, we could see that most work are done by the father class __weak_ptr, that's view the code of __weak_ptr: template<typename _Tp, _Lock_policy _Lp> class __weak_ptr { public: template<typename _Tp1> __weak_ptr(const __shared_ptr<_Tp1, _Lp>& __r) : _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) // never throws { __glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>) } long use_count() const // never throws { return _M_refcount._M_get_use_count(); } _Tp* _M_ptr; // Contained pointer. __weak_count<_Lp> _M_refcount; // Reference counter. }; When we call the use_count() of weak_ptr, we call _M_refcount._M_get_use_count(), _M_refcount was assigned in the constructor of class __weak_ptr , in the assign list we could see _M_refcount(__r._M_refcount), so we should know what really does in the constructor of __weak_count: template<_Lock_policy _Lp> class __weak_count { public: __weak_count(const __shared_count<_Lp>& __r) : _M_pi(__r._M_pi) // nothrow { if (_M_pi != 0) _M_pi->_M_weak_add_ref(); } long _M_get_use_count() const // nothrow { return _M_pi != 0 ? _M_pi->_M_get_use_count() : 0; } private: friend class __shared_count<_Lp>; _Sp_counted_base<_Lp>* _M_pi; }; In the constructor of class __weak_count the member _M_pi is assigned by the member _M_pi of shared_ptr, and we view the function _M_get_use_count(), when we call use_count() of weak_ptr, in fact we call the use_count() of shared_ptr, weak_ptr don't have the _Sp_counted_base itself, it`s the _Sp_counted_base of shared_ptr, so the weak_ptr must rely on the shared_ptr. Let's get back to your question: "Is there a case that share_ptr ref count is 0, while weak_ptr ref count is not 0?" I think using the normal way to write the code, the answer is NO !
73,181,160
73,184,875
C++ stack overflow error, even though i use a pointer array
Hello im trying to test a algorithm(Quicksort) by sorting an array with 1 000 000 numbers but i get a stack overflow error. I found out earlier that i should save the array on the heap instead of the stack. So i did it like this. int *enMiljon = new int[1000000]; Instead of this: int enMiljon[1000000] = {}; This is how i call the function and how it looks like: quicksortPivotLast(enMiljon, 999999); template <typename T> int partitionPivotLast(T arr[], int startIndex, int endIndex) { int pivot = arr[endIndex]; // Constant time= C1 int count = 0; // Constant time= C2 for (int i = startIndex; i < endIndex; i++) { // Linear time= n if (arr[i] <= pivot) // Constant time= C3 { count++; // Constant time= C4 } } int indexP = startIndex + count; // Constant time= C5 swap(arr[indexP], arr[endIndex]); // Constant time= C6 int i = startIndex; // Constant time= C7 int j = endIndex; // Constant time= C8 while (i < indexP && j > indexP) { // linear time=n while (arr[i] <= pivot) { // Linear time = n/2 or n i++; } while (arr[j] > pivot) { // Linear time = n/2 or n j--; } if (i < indexP && j > indexP) { // Constant time= C9 swap(arr[i++], arr[j--]); // Constant time= C10 } } return indexP; //T(n)=O(4c+2c+2c*n+2c*3n+logn) } template<typename T> void quicksortPivotLastTwo(T arr[], int startIndex, int endIndex) { if (startIndex >= endIndex) // Constant time= C1 { return; } // partitioning the array int p = partitionPivotLast(arr, startIndex, endIndex); // Constant time= C2 // Sorting the left part quicksortPivotLastTwo(arr, startIndex, p - 1); // Constant time= C3 // Sorting the right part quicksortPivotLastTwo(arr, p + 1, endIndex); // Constant time= C4 } template<typename T> void quicksortPivotLast(T arr[], int n) { quicksortPivotLastTwo(arr, 0, n); } But i still get stack overflow error. Does anyone know how i should do?
Recurse on smaller partition, loop on larger partition. This will limit stack space complexity to O(log2(n)), but worst case time complexity remains at O(n^2). template<typename T> void quicksortPivotLastTwo(T arr[], int startIndex, int endIndex) { while(startIndex < endIndex) { int p = partitionPivotLast(arr, startIndex, endIndex); if((p - startIndex) <= (endIndex - p)){ quicksortPivotLastTwo(arr, startIndex, p - 1); startIndex = p+1; } else { quicksortPivotLastTwo(arr, p + 1, endIndex); endIndex = p-1; } }
73,181,173
73,181,240
Any creative ways to detect deleted data allocated in heap?
I am designing a game engine and a lot of subsystems would interface with each other better if deleted pointers could be detected. I decided to take a look at what the actual memory address points to. It appears to point to 0000000000008123 in my PC. I wonder, does it points to the same memory address to anyone else. If it does, would it point to the same memory address in other operating systems? It most likely varies from PC to PC, but maybe storing what that actual value is at the beginning of the program could be helpful to detect deleted memory. Could this be a trustworthy method to detect deleted memory in C++? Here is the test case I used: #include <iostream> using namespace std; int main() { cout << "Program operating..." << endl; for (unsigned int i = 0; i < 5; i++) { int* integer1 = nullptr; int* integer2 = nullptr; int* integer3 = nullptr; int* integer4 = nullptr; int* integer5 = nullptr; integer1 = new int(1); integer2 = new int(2); integer3 = new int(3); integer4 = new int(4); integer5 = new int(5); cout << integer1 << endl; cout << integer2 << endl; cout << integer3 << endl; cout << integer4 << endl; cout << integer5 << endl; cout << endl; delete integer1; delete integer2; delete integer3; delete integer4; delete integer5; cout << integer1 << endl; cout << integer2 << endl; cout << integer3 << endl; cout << integer4 << endl; cout << integer5 << endl; cout << endl; } cout << "Program terminated..." << endl; } Output 0000000000008123 0000000000008123 0000000000008123 0000000000008123 0000000000008123
Smart pointers do exactly what you are looking for with the advantage that they will reclaim memory as objects go out of scope. You can query them to check if they are empty or not. Example: https://godbolt.org/z/6s5vxrjsa #include <iostream> #include <memory> int main() { std::cout << "Program operating..." << std::endl; for (unsigned int i = 0; i < 5; i++) { std::unique_ptr<int> integer1( new int(1)); std::cout << integer1.get() << " empty:" << (integer1?"No":"Yes") << std::endl; integer1.reset(); std::cout << integer1.get() << " empty:" << (integer1?"No":"Yes") << std::endl; } std::cout << "Program terminated..." << std::endl; } Program operating... 0x602000000010 empty:No 0 empty:Yes 0x602000000030 empty:No 0 empty:Yes 0x602000000050 empty:No 0 empty:Yes 0x602000000070 empty:No 0 empty:Yes 0x602000000090 empty:No 0 empty:Yes Program terminated... Note that you do not need to delete the object. They will be deleted automatically. This example shows this: #include <iostream> #include <memory> struct Printer { Printer( int value ) : _value(value) { std::cout << "Creating printer with value " << value << std::endl; } ~Printer() { std::cout << "Deleting printer with value " << _value << std::endl; } int _value; }; int main() { std::cout << "Program operating..." << std::endl; for (unsigned int i = 0; i < 5; i++) { std::unique_ptr<Printer> printer( new Printer(2*i)); std::cout << printer.get() << " empty:" << (printer?"No":"Yes") << std::endl; printer.reset(); std::cout << printer.get() << " empty:" << (printer?"No":"Yes") << std::endl; printer.reset( new Printer(2*i+1) ); std::cout << printer.get() << " empty:" << (printer?"No":"Yes") << std::endl; } std::cout << "Program terminated..." << std::endl; } Program operating... Creating printer with value 0 0x602000000010 empty:No Deleting printer with value 0 0 empty:Yes Creating printer with value 1 0x602000000030 empty:No Deleting printer with value 1 Creating printer with value 2 0x602000000050 empty:No Deleting printer with value 2 0 empty:Yes Creating printer with value 3 0x602000000070 empty:No Deleting printer with value 3 ...
73,181,225
73,181,392
Print neat progress bar from macOS terminal command prompt
macOS terminal is of type xterm-256color. I'd like to print colored progress bar with special characters. for example, I uses printf with the symbol \xb0 to present the progress bar : printf("%s", msg.c_str()); in debugger : (lldb) p msg (const std::string) $0 = "[\xb0\xb0\xb0\xb0]" But apparently, it prints invisible symbols. Any idea how to print \xb0 in terminal ? Furthermore, is there any way print messages that overrun the current line? I wish to show the progress bar advancing, and not printing it in multiple lines that each represent different percentage state. Thanks !
Well doing it from scratch is pretty cumbersome. Why don't you use an existing library like this, the code seems pretty straightforward. You get all fancy progress bars, with color, and it seems pretty intuitive, and its very customizable. (From the Github Repo, here) #include <indicators/progress_bar.hpp> #include <thread> #include <chrono> int main() { using namespace indicators; ProgressBar bar{ option::BarWidth{50}, option::Start{"["}, option::Fill{"="}, option::Lead{">"}, option::Remainder{" "}, option::End{"]"}, option::PostfixText{"Extracting Archive"}, option::ForegroundColor{Color::green}, option::FontStyles{std::vector<FontStyle>{FontStyle::bold}} }; // Update bar state while (true) { bar.tick(); if (bar.is_completed()) break; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return 0; } I can change the total length of the bar by changing the value of option::BarWidth, or make the fill to 0 by changing option::Fill{"="} to option::Fill{"0"}
73,181,233
73,181,338
C++ Is there any difference in performance by calling a func with code instead of calling the code directly? (From python)
I am from Python and still new at c++. Now I wonder if calling a function is slower in performance then calling the code of the func itself? Some example. struct mynum { public: int m_value = 0; constexpr int value() { return m_value; } // Say we would create a func here. // That wants to use the value of "m_value" // Is it slower to use "value()" instead of "m_value"? // Even if the difference is very small. // Or is there indeed no difference because everything gets compiled. void somefunc() { if(value() == 0) {} } }
If the function body is available at the time it is called, there is a good chance the compiler will try to either automatically inline it (the "inline" keyword is just a hint) or leave it as a function body. In both cases you are probably in the best path as compilers are pretty good at this kind of decisions - or better than us. If only the function prototype (the declaration) is known by the compiler and the body is defined in another compilation unit (*.cpp file) then there are a couple of hits you might take: The processor pipeline (and speculative execution) might stall which may call you a few cycles although processors have become extremely efficient at these things in the past 10 years or so. Even dynamic branch optimization has become so good that there is no point rearranging the order or if/else like we used to do 20 years ago (still necessary for microprocessors though). The register optimization will display a clean cut, which will affect some intensive calculations primarily. Basically the processor runs an optimization to decide in which registers the variables being used will reside on. When you make a call, only a couple of them will be guaranteed to be preserved, all the others will need to be reloaded when the function returns. If the number of variables active is large, that load/unload can affect performance but that is really rare. If the function is a virtual method, the indirect lookup on the virtual table might add up to ten cycles. Compilers might de-virtualize a call if it knows exactly which class will be called however so this cost might be actually the same of a normal function. In more complex cases, with several layers of polymorphism then virtual calls might take up to 20 cycles. On my tests with 2 layers the cost is in average 5-7 cycles on an AMD Zen3 (Threadripper). But overall if the function call is not virtual, the cost will be really negligible. There are programmers that swear by inlining everything but if my experience is worth note, I have programatically generated code 100% inlined and the same code compiled in separate and the performance was largely the same.
73,181,336
73,181,351
Are iterators still valid when the underlying elements have been moved?
If I have an iterator pointing to an element in an STL container, and I moved the element with the iterator, does the standard guarantee that the iterator is still valid? Can I use it with container's method, e.g. container::erase? Also does it matter, if the container is a continuous one, e.g. vector, or non-continuous one, e.g. list? std::list<std::string> l{"a", "b", "c"}; auto iter = l.begin(); auto s = std::move(*iter); l.erase(iter); // <----- is it valid to erase it, whose underlying element has been removed?
Yes, you've modified the object in the container. You've not modified the container itself so the iterator is still valid
73,182,098
73,182,177
Question of removing numbers from a loop in c++
so I have a question, so I have these codes here in c++ #include <bits/stdc++.h> using namespace std; int main() { for(int i = 1; i <= 100; i += 2) { cout<<i<<"\t"; } return 0; } so the result of this is all odd numbers from 1 to 100, but I want it to remove the number 5 7 93 from the result, so how do I do that?
inside the loop you can do a check condition of the current loop index value and skip by using continue; for(int i = 1; i <= 100; i += 2) { if (i == 5 || i == 7 || i == 93) { continue; } cout<<i<<"\t"; }
73,182,141
73,183,627
Undefined reference when creating entry point in shared library clang
I have an issue I don't understand. My project is quite simple for now. I have a shared library Engine which is called by my executable. I'm trying to move the entry point inside my shared library, so the executable part only has functions and some class to create. ---EDIT: I edit to post the project as it is reproductible easily. To do so, I have these files in my shared library: entry.h BaseGame.h Application.cpp Here is entry.h #include "BaseGame.h" extern game* create_game(); int main(int argc, char *argv[]) { auto testgame = create_game(); delete testgame; return 0; } BaseGame.h class __declspec(dllexport) game { public: game() = default; virtual ~game(); virtual bool initialize() =0; virtual bool update(float deltaTime) =0; virtual bool render(float deltaTime) =0; virtual void on_resize() =0; }; Application.cpp #include "BaseGame.h" class __declspec(dllexport) Application { public: Application()=default; ~Application()=default; }; And in my executable, I have two files entry.cpp which defines create_game and my_game.h which inherited from game. entry.cpp #include <entry.h> #include "my_game.h" game* create_game() { return new myGame; } and my_game.h: class myGame : public game { public: myGame(){}; ~myGame() override = default; bool initialize() override; bool update(float deltaTime) override; bool render(float deltaTime) override; void on_resize() override; }; my_game.cpp: #include "my_game.h" bool myGame::initialize() { return true; } bool myGame::update(float deltaTime) { return true; } bool myGame::render(float deltaTime) { return true; } void myGame::on_resize() { } What I don't understand is that I always get an linker error when building my exe: Création de la bibliothèque ..\bin\testbed.lib et de l'objet ..\bin\testbed.exp entry-3b33f2.o : error LNK2019: symbole externe non résolu "public: virtual __cdecl game::~game(void)" (??1game@@UEAA@XZ) référencé dans la fonction "public: virtual __cdecl myGame::~myGame(void)" (??1myGame@@UEAA@XZ) ..\bin\testbed.exe : fatal error LNK1120: 1 externes non résolus Also here is how i build my shared library: SET assembly=Engine SET compilerFlags=-g -shared -Wvarargs -Wall -Werror SET includeFlags=-Isrc SET linkerFlags=-luser32 SET defines=-D_DEBUG_EG -DGEXPORT -D_CRT_SECURE_NO_WARNINGS ECHO "Building %assembly%%..." clang++ %cFilenames% %compilerFlags% -o ../bin/%assembly%.dll %defines% %includeFlags% %linkerFlags% And here is my executable: SET assembly=testbed SET compilerFlags=-g REM -Wall -Werror SET includeFlags=-Isrc -I../Engine/src/ SET linkerFlags=-L../bin/ -lEngine.lib SET defines=-D_DEBUG_EG -DGIMPORT clang++ %cFilenames% %compilerFlags% -o ../bin/%assembly%.exe %defines% %includeFlags% %linkerFlags% Even if game is exported. Does anyone see something wrong? PS: I'm using Clang as the compiler.
The game class lacks a destructor definition. I suggest making it default: class myGame : public game { public: myGame(){}; ~myGame() override = default; // here bool initialize() override; bool update(float deltaTime) override; bool render(float deltaTime) override; void on_resize() override; }; You may also remove the default constructor and destructor from myGame. It'll be default constructible and have a virtual destructor by default. class myGame : public game { public: // myGame(){}; // remove // ~myGame() override = default; // remove // ... Other notes: All your header files should have header guards to prevent including the same file twice in one translation unit. my_game.h should #include "BaseGame.h" to get the definition of game.
73,182,242
73,182,272
Cout trigger breakpoint when i try to print something which is not a string
I trying to build fft function in c++. I realized there are errors in the process so I wanted to print each step on it's own. When I try to do cout to everything that is not a string it trigger a breakpoint and error: "A heap has been corrupted " In the main it sometimes and sometimes not Any help, or suggestions would be much appreciated. Edit : Code after fix complex<double>* fft(complex<double>* signal, int len) { if (len == 1) return signal; else { const complex<double> J(0, 1); const double PI = 3.14159265358979323846; const double THRESHOLD = 1e-10; complex<double> w(1, 0); complex<double>* x_d1 = new complex<double>[len / 2]; complex<double>* x_d2 = new complex<double>[len / 2]; for (int i = 0; i < len/2; i++) { x_d1[i] = signal[2*i]; x_d2[i] = signal[2*i + 1]; } complex<double>* y_1 = fft(x_d1, len / 2); complex<double>* y_2 = fft(x_d2, len / 2); complex<double>* dft = mergePointers(y_1, y_2, len / 2); delete[] x_d1, x_d2, y_1, y_2; for (int k = 0; k < len/2; k++) { complex<double> p = dft[k]; complex<double> w_k = exp(J * ((-2*PI*k) / len)); complex<double> q = w_k * dft[k + (len / 2)]; dft[k] = p + q; dft[k + len / 2] = p - q; if (abs(dft[k].real()) < THRESHOLD) dft[k] = complex<double>(0, dft[k].imag()); if (abs(dft[k].imag()) < THRESHOLD) dft[k] = complex<double>(dft[k].real(), 0); if (abs(dft[k + (len / 2)].real()) < THRESHOLD) dft[k + (len / 2)] = complex<double>(0, dft[k + (len / 2)].imag()); if (abs(dft[k + (len / 2)].imag()) < THRESHOLD) dft[k + (len / 2)] = complex<double>(dft[k + (len / 2)].real(), 0); } return dft; } }
You allocated dynamically arrays with len / 2 elements. But in for loops like this for ( int i = 0; i <= len/2; i++ ) you are trying to access len / 2 + 1 elements that results in undefined behavior. The valid range of indices is [0, len / 2 ). You have to write for ( int i = 0; i < len/2; i++ )
73,182,373
73,184,227
std::invoke with ref qualifiers
I'm running into the following issue when using ref qualifiers with operator() below. What is the correct syntax to enable the l-value ref overload in this instance? #include <functional> struct F { void operator()() & {} void operator()() && {} // Commenting this overload enables code to compile }; int main() { F f; std::invoke(&F::operator(), f); } Error <source>: In function 'int main()': <source>:10:15: error: no matching function for call to 'invoke(<unresolved overloaded function type>, F&)' 10 | std::invoke(&F::operator(), f); | ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~ In file included from <source>:1: /opt/compiler-explorer/gcc-trunk-20220731/include/c++/13.0.0/functional:107:5: note: candidate: 'template<class _Callable, class ... _Args> constexpr std::invoke_result_t<_Fn, _Args ...> std::invoke(_Callable&&, _Args&& ...)' 107 | invoke(_Callable&& __fn, _Args&&... __args) | ^~~~~~ /opt/compiler-explorer/gcc-trunk-20220731/include/c++/13.0.0/functional:107:5: note: template argument deduction/substitution failed: <source>:10:15: note: couldn't deduce template parameter '_Callable' 10 | std::invoke(&F::operator(), f); | ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~ ASM generation compiler returned: 1 <source>: In function 'int main()': <source>:10:15: error: no matching function for call to 'invoke(<unresolved overloaded function type>, F&)' 10 | std::invoke(&F::operator(), f); | ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~ In file included from <source>:1: /opt/compiler-explorer/gcc-trunk-20220731/include/c++/13.0.0/functional:107:5: note: candidate: 'template<class _Callable, class ... _Args> constexpr std::invoke_result_t<_Fn, _Args ...> std::invoke(_Callable&&, _Args&& ...)' 107 | invoke(_Callable&& __fn, _Args&&... __args) | ^~~~~~ /opt/compiler-explorer/gcc-trunk-20220731/include/c++/13.0.0/functional:107:5: note: template argument deduction/substitution failed: <source>:10:15: note: couldn't deduce template parameter '_Callable' 10 | std::invoke(&F::operator(), f); | ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~ Execution build compiler returned: 1
For the first argument of std::invoke, which is expected to be a pointer to a member function. As per cppref: A pointer to function may be initialized from an overload set which may include functions, function template specializations, and function templates, if only one overload matches the type of the pointer cppref: The parameter types and the return type of the function must match the target exactly, no implicit conversions are considered In your case, &F::operator() can't be deduced, you need to provide the type explicitly. std::invoke<void(F::*)()&>(&F::operator(), f); std::invoke<void(F::*)()&&>(&F::operator(), std::move(f)); Demo
73,182,555
73,183,255
How to read "std::greater<>{}" in "std::make_heap"
// min heap solution // extract k smallest data from a min-heap of all n data points class K_Smallest_MinHeap { public: K_Smallest_MinHeap(std::size_t n, std::size_t k): N(n), K(k), count(0) { } void add(int value){ values.push_back(value); } std::vector<int> get(){ std::make_heap(values.begin(), values.end(), std::greater<>{}); std::vector<int> result; for (std::size_t i = 0; i < K; ++i){ std::pop_heap(values.begin(), values.end(), std::greater<>{}); result.push_back(values.back()); values.pop_back(); } return result; } private: std::size_t N; std::size_t K; std::size_t count; std::vector<int> values; }; Hi everyone I do not understand the "std::greater<>{}" in std::make_heap() I thought the takes only two iterators begin&end? "void make_heap( RandomIt first, RandomIt last );" Thank you for helping!
According to the cppreference: template< class RandomIt > void make_heap( RandomIt first, RandomIt last ); template< class RandomIt > constexpr void make_heap( RandomIt first, RandomIt last ); template< class RandomIt, class Compare > void make_heap( RandomIt first, RandomIt last, Compare comp ); template< class RandomIt, class Compare > constexpr void make_heap( RandomIt first, RandomIt last, Compare comp ); Constructs a max heap in the range [first, last). The first version of the function uses operator< to compare the elements, the second uses the given comparison function comp. I do not understand the "std::greater<>{}" in std::make_heap() I thought the takes only two iterators begin&end? If your make_heap function only take two iterators, it will create a max_heap. If you want to create a min_heap, you should use operator> to compare the elements, this is exactly what std::greater<>{} does.
73,182,592
73,182,859
Character counter returning incorrect value for char[n] array
I am writing a C++ program for homework, and it needs to count the characters in a char arr[n] string. However, my counter keeps returning the wrong values. I have looked through other answers to similar questions, however, they are not specific to C++ and none of the answers explain the value I am getting. #include<iostream> using namespace std; #include<string.h> #include <stdlib.h> class Counter { public: char word[20]; int totChar{ 0 }; void setWord(char word) { this->word[20] = word; } void setCount(int totChar) { this->totChar = totChar; } int getLength() { return totChar; } void charCount() { int n = 0; for (int i = 0; word[i] != '\0'; i++) { if (word[i] != '\0') { n++; } } setCount(n); } }; int main() { char text[20]; cout << "Enter the string:" << endl; cin >> text; Logic input; input.setWord(text[20]); input.charCount(); // input.resetWord(); cout << input.getLength(); }
So it seems you haven't figured out how arrays and C strings work in C++ yet. void setWord(const char* word) { strcpy(this->word, word); } and Logic input; input.setWord(text); Your code is a bit weird, I guess you are just experimenting, but I think those two changes should make it work.
73,182,925
73,182,979
How to create a function inside a structure in a header file and implement this function in another c source file?
Here I created a main.c #include <iostream> #include "Header.h" struct person_t a; int main() { a.func(1,2); } And I have a header called "Header.h", I define a structure in this file struct person_t { char name; unsigned age; int(*func)(int, int); }; Then I implement int(*func)(int, int); in another c file called "Source.c" #include "Header1.h" struct person_t a; int add2(int x, int y) { return x + y; }; a.func = &add2; But it seems not work, does anyone who has any idea of this question?
You may not use statements outside a function like this a.func = &add2; Remove this statement and this declaration struct person_t a; from Source.c. In the header place the function declaration int add2(int x, int y); And in the file with main write int main() { struct person_t a; a.func = add2; a.func(1,2); }
73,183,032
73,184,141
bytearray to numpy array in Python for displaying in pyqt5 GUI
I'm new to Python and have sorta c++ style coding background. In short: tring to display 16 bit grayscale images in my GUI(pyqt6) have the stored the image data in bytearray, that is, 1024 by 768 (the total size of the byte array would be 1024 x 768 x 2 since it's 16 bit). having difficulties with using this data = bytearray(1572864) for displaying. The following code is what I have used for displaying the same image (but downscaled to 8-bit). What I'm now trying to do is use the 16-bit data and have it converted to QPixmap in order to display. The code for displaying 8-bit raw image is ( I have used rawpy for this, please feel free to get rid of the rawpy section if you could come up with a better way to do this) raw = np.array( binary data read from file) src = raw.postprocess() buf = src.data.tobytes() h, w, ch = src.shape bytesperline = ch * w image = QImage(buf, 1024, 768, bytesperline, QImage.Format_RGB888) self.DisplayRect.setPixmap(QPixmap.fromImage(image)) self.DisplayRect.show() Hope I explained my question without causing any confusion. In summary: trying to use data in bytearray(1572864) to display in my GUI in need of help with manipulating the binary data from/to different data structures What I would have done if it were c++: //declare a Mat with 16UC1 format //easily memcpy(mat.data, source, size); //stretchDiBits(dc, where_to_draw_imgs, mat.data); Thank you very much in advance.
Versions of Qt >= 5.13 include QImage.Format_Grayscale16: # load 8-bit image with size w x h raw8 = Path('image8.raw').read_bytes() image8 = QImage(raw8, w, h, w, QImage.Format_Grayscale8) # load 16-bit image, note 2 * w bytes per line! raw16 = Path('image16.raw').read_bytes() image16 = QImage(raw16, w, h, 2 * w, QImage.Format_Grayscale16) For conversion and scaling between formats, you can use: scale = lambda b, r1, r2: int((2 ** r2 - 1) * b / (2 ** r1 - 1)) data8 = bytes([0, 64, 128, 255]) data16 = b''.join(scale(b, 8, 16).to_bytes(2, 'little') for b in data8) data8_restored = bytes(scale(int.from_bytes(data16[i:i + 2], 'little'), 16, 8) for i in range(0, len(data16), 2)) # change 'little' to 'big' if needed
73,183,668
73,183,797
How to encode a string in C++ so as to not collide with seperator?
I am currently developing an open-source Text-based storage utility called WaterBase. The aim is to facilitate easy saving and access of persistent key-value data, like we have in Android SharedPreferences. The data storage scheme is like this: type:key:value The problem I am facing is that if someone uses : as a character in their key or value, the code breaks as it counts : as separator. How do I overcome this behavior? I don't want to restrict the use of separators in user data. I looked about encoding but couldn't find any working code without external libraries. You can have a look in the .h file here. A mechanism that can be easily implemented in all languages instead of just C++ would be better so as to diversify the use case.
If you indeed want no special characters in the output string, you need to store the information about the string length beforehand. You could use an approach similar to name mangling: store the length of the next entry as integer followed by a seperator followed by the actual content: Example A string is stored as <string length(decimal)> '_' <string content> struct Entry { std::string type; std::string key; std::string value; }; void WriteMangled(std::ostream& s, std::string const& str) { s << str.length() << '_' << str; } void ParseMangled(std::istream& s, std::string& str) { size_t size; char c; if ((s >> size) && (s >> c)) { assert(c == '_'); str.resize(size, '\0'); s.read(str.data(), size); } } std::ostream& operator<<(std::ostream& s, Entry const& entry) { WriteMangled(s, entry.type); WriteMangled(s, entry.key); WriteMangled(s, entry.value); return s; } std::istream& operator>>(std::istream& s, Entry& entry) { ParseMangled(s, entry.type); ParseMangled(s, entry.key); ParseMangled(s, entry.value); return s; } int main() { std::ostringstream oss; oss << Entry{ "_Td$a", "8X0_8", "foo bar baz"}; std::string str = std::move(oss).str(); std::cout << str << '\n'; std::istringstream iss(std::move(str)); Entry e; iss >> e; std::cout << e.type << '\n' << e.key << '\n' << e.value << '\n'; } Adding an escape char could be simpler though, e.g. using the backslash char as character simply marking the next char as a char that is not a special character, like a seperator. The drawback is that you have to replace backslashes in the original strings with double backslashes when writing the output. constexpr char EscapeChar = '\\'; constexpr char SeparatorChar = ':'; bool ReadEscapedString(std::istream& s, std::string& str) { bool escaped = false; char c; while (s >> c) { switch (c) { case EscapeChar: if (!(s >> c)) { return false; // could not read escaped char } break; case SeparatorChar: return true; default: break; } str.push_back(c); } return true; } std::istream& operator>>(std::istream& s, Entry& entry) { ReadEscapedString(s, entry.type) && ReadEscapedString(s, entry.key) && ReadEscapedString(s, entry.value); return s; } int main() { std::istringstream iss(R"(foo\:bar:\:baz\:\:a:x)"); // Note: Raw string literal for easier readability, see https://en.cppreference.com/w/cpp/language/string_literal Entry e; iss >> e; std::cout << e.type << '\n' << e.key << '\n' << e.value << '\n'; }
73,183,982
73,184,008
how to return a reference of an object from std::vector<std::vector<>>
like in the title, here is a pice of code: class matrix{ std::vector<std::vector<bool>> base; std::pair<int, int> size; public: matrix(int x, int y){ size.first = x; size.second = y; std::vector<std::vector<bool>> b(x, std::vector<bool>(y)); base = b; } bool& operator ()(int x, int y) const { if(x < 0 || y < 0 || x >= size.first || y >= size.second){outOfBounds ex; throw ex;} return base[x][y]; } /*and more that is unrelated to the question*/ }; the error is in bool& operator(...) and it is as follows: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type‘std::vector<bool>::const_reference’ {aka ‘bool’} 30 | return base[x][y]; in the code, the size of the vector (matrix) dose not change I also replaced bool with int and its the same problem, can't convert from int to int& The function can't be const, so that the value of the reference can be changed
bool& operator ()(int x, int y) const { The const at the end means that this is a constant class method, and this is constant. return base[x][y]; Everything in this is constant. Including this. The return value from this operator overload should, therefore, be const bool & instead of bool &. If after understanding this you go back and reread your compiler's error message it should now make perfect sense to you, because that's exactly what your compiler was telling you. Alternatively you can drop the const from the overloaded operator declaration, and return a bool &, that's up to you. But then, you're going to wind up with another, special problem: a std::vector<bool> is not really a vector of bools, but something very weird. So, the final solution may be to simply declare the return value as an auto &, and let the compiler figure it out for you. ...You don't really want to know what it really is.
73,184,082
73,184,112
How are templates work so that the classes are properly generated by the compiler to work with both pointer types and non pointer types?
Given int i = 42; int* p = &i; we cannot do const int * & d = p; In my current understanding, this is because const int * & d can be read as "d is a reference of a pointer to an int that is a const" and p is "a pointer to an int", which means the RHS needs to be turned into a temporary being "a pointer to an int that is a const" and that cannot be binded directly with a reference (as on the LHS). We would need to have, say, const int* const& d = p;. Possible references: 1, 2. That said, consider the following toy code: template<typename T> class X { public: void fun(const T& d) { } }; At first, I thought if I do X<int*> x; x.fun(p); The method generated by the compiler would be void fun(const int*& d), and I would get an error due to the above reason. However, there is no error and it works "as expected" (by that I mean, we always have d itself as the const no matter T is replaced by pointer types or by non-pointer types). My current guess is that, for the above scenario, the method generated by the compiler is something like void fun(int* const& d). May I ask if my guess is correct? How are templates work so that the classes generated by the compiler work with pointers "as expected"?
Your guess is correct. For const T, const is qualified on type T directly. Given T is int* (non-const pointer to non-const int), const T results in const pointer, i.e. int* const (const pointer to non-const int) but not const int* (non-const pointer to const int).
73,184,335
73,184,506
c++ design with unique_ptr with custom deleter
I am writing a tree data structure. Each node has a fixed size so I use a fixed size allocator for allocating/deallocating Node. This gives me a headache: struct Node { // other attributes ... std::array<std::unique_ptr<Node, CustomDeleter>, num_children> children_; }; Since all allocations/deallocations of Node are managed by my custom Alloc, I can't use std::unique_ptr<Node> for child nodes, I have to ship custom deleter (associated with that allocator) to children. But Alloc must know the type of Node, because Alloc is a fixed-size allocator for Node, it should be aware of sizeof(Node) and alignof(Node). But Node must know the type of Alloc, because CustomDeleter cannot be instantiated without Alloc! This is a circular depedency! Have the C++ committee never considered about implementing a tree structure when they designed std::unique_ptr<Node, Deleter>? How can I resolve this problem? ps. I can't use std::allocator<Node> because I should be able to use memory resource other than the default memory resource
You can use Template template arguments: #include <memory> template <template <class T> class AllocTemplate> struct Tree { struct Node; using Alloc = AllocTemplate<Node>; [[no_unique_address]] Alloc alloc_; struct Deleter { [[no_unique_address]] Alloc alloc_; Deleter(const Alloc &alloc) : alloc_{alloc} {} template <typename T> void operator()(T* ptr) noexcept { alloc_.deallocate(ptr, sizeof(T)); } }; struct Node { int val_ = 0; std::unique_ptr<Node, Deleter> next_; Node(Deleter deleter) : next_{nullptr, std::move(deleter)} {} }; using nodeptr = std::unique_ptr<Node, Deleter>; nodeptr make_node() { auto buf = alloc_.allocate(1); auto deleter = Deleter{alloc_}; Node* node = new(buf) Node(deleter); return nodeptr(node, deleter); } }; int main() { Tree<std::allocator> tree; [[maybe_unused]] auto node = tree.make_node(); }
73,184,447
73,188,480
Why does my compiler complain about a missing template argument for a concept?
Initially I had following concept which worked just fine: template<typename T, typename...KEYS> concept js_concept = requires(T t, int index, std::string& json_body, KEYS... keys, std::string key) { { t.template get_value<T>(keys) } -> std::same_as<T>; { t.template get_value<T>(key) } -> std::same_as<T>; }; The two above is just to have a distinction between 1/several args. Now I would simply implement this by: class JsoncppImpl { template<typename T, typename... KEYS> T get_value(KEYS&& ... keys) { /// impl } template<typename T> T get_value(std::string key) { /// impl } } And the use case: class JsonUtil { public: template<js_concept JSON_OPERATOR> JsonUtil(std::string body, JSON_OPERATOR&& json_impl){ m_st = json_impl.get_value<std::string>(body); } std::string m_st; }; int main( ){ std::string body = "c++"; JsonUtil<JsoncppImpl::value> jsoncpp(body, JsoncppImpl{}); return 0; } That works just fine. If I do the following addition by adding another function to the concept returning a template argument: template<typename T , typename VALUE, typename...KEYS> concept js_concept = requires(T t, int index, std::string& json_body, KEYS... keys, std::string key) { // // setting consts here is pointless (these are treated as pr values) { t.template get_value<T>(keys) } -> std::same_as<T>; { t.template get_value<T>(key) } -> std::same_as<T>; { t.template release() } -> std::same_as<VALUE>; }; and adding the additional function to the implemention: JsoncppImpl::release(){ return std::move(m_some_internal_value);} The variable ´m_some_internal_value´ is just some type well defined within JsoncppImpl. It can even be defined as a primitive type. Now using the release function: template<js_concept JSON_OPERATOR> JsonUtil::JsonUtil(std::string body, JSON_OPERATOR&& json_impl){ m_st = json_impl.get_value<std::string>(body); auto val = json_impl.release(); } Gives following compiler error: js_concept' requires more than 1 template argument; provide the remaining arguments explicitly to use it here template<js_concept JSON_OPERATOR>
template<js_concept JSON_OPERATOR> JsonUtil(std::string body, JSON_OPERATOR&& json_impl) {} Is equivalent to template<typename JSON_OPERATOR> JsonUtil(std::string body, JSON_OPERATOR&& json_impl) requires js_concept<JSON_OPERATOR> {} KEYS... empty, so it works fine. (But I really doubt if it behaves as you expect... When you add another template parameter, you have to explicitly provide it since the compiler has no idea where it comes from. You could do like this, template<typename VALUE, js_concept<VALUE> JSON_OPERATOR> JsonUtil::JsonUtil(std::string body, JSON_OPERATOR&& json_impl){
73,184,451
73,185,793
how to split a sentence into strings using recursion in c++
string strings[10]; void split(string s){ int curr=0,start=0,end=0,i=0; while(i<=len(s)){ if(s[i]==' ' or i == len(s)){ end = i; string sub; sub.append(s,start,end-start); strings[curr] = sub; start = end + 1; curr += 1 ; } i++; } } for example if the input is " computer laptop screen desktop mouse " then the output string should be: computer laptop screen desktop mouse I have successfully tried using loops but failed using recursion, can anyone help me solve split() using recursion. Thank you
This solution assumes you want only words from the string to enter your array and that you want to split on some predetermined string delimiter like <space>" " or <double-dash>"--". If you need to keep the void function signature, here is one: void split_rec(string str_array[], size_t arr_index, string s, string delimiter) { if (s == "") { return; } size_t str_index = s.find(delimiter); string word = s.substr(0, str_index); if (word != "") { str_array[arr_index++] = word; } // find type functions return string::npos if they don't find. str_index = s.find_first_not_of(delimiter, str_index); if (str_index == string::npos) { return; } return split_rec(str_array, arr_index, s.substr(str_index), delimiter); } But I would recommend returning the size of the array so you communicate what the function is doing more accurately. Like this: size_t split_rec(string str_array[], size_t arr_index, string s, string delimiter) { if (s == "") { return arr_index; } size_t str_index = s.find(delimiter); string word = s.substr(0, str_index); if (word != "") { str_array[arr_index++] = word; } str_index = s.find_first_not_of(delimiter, str_index); if (str_index == string::npos) { return arr_index; } return split_rec(str_array, arr_index, s.substr(str_index), delimiter); } Then the call is like this: string strings[10]; // I left some extra spaces in this string. string str = " computer laptop screen desktop mouse "; size_t strings_len = split_rec(strings, 0, str, " "); cout << "Array is length " << strings_len << endl; for (size_t i = 0; i < strings_len; i++) { cout << strings[i] << endl; } Array is length 5 computer laptop screen desktop mouse
73,184,464
73,184,540
How to direct initialize a C++ variant with one of its non-default option?
Consider the following: class Foo { [...] public: Foo(int); } class Bar { [...] public: Bar(int); } using MyVariant = std::variant<Foo,Bar>; How can one direct initialize (i.e no copy and no Foo building involved) an instance of MyVariant as a Bar ?
Pass the a tag of type std::in_place_type_t<Bar> as first constructor parameter: struct Foo { Foo(int value) { std::cout << "Foo(" << value << ")\n"; } }; struct Bar { Bar(int value) { std::cout << "Bar(" << value << ")\n"; } Bar(Bar const&) { std::cout << "Bar(Bar const&)\n"; } Bar& operator=(Bar const&) { std::cout << "Bar& operator=(Bar const&)\n"; } }; int main() { std::variant<Foo, Bar> var(std::in_place_type_t<Bar>{}, 1); } std::in_place_index_t would be an alternative first parameter, if you prefer passing the position of the type in the template parameter list of std::variant.
73,184,493
73,184,813
How can I efficiently search for multiple adjacent elements in a std::set?
I have a set containing a sortable data type. I need to be able to search to find all elements that lie between two unknown points within this set. For the sake of simplicity I'll use some pseudocode to describe this. set = { (a, 0), (a, 3), (a, 8), (b, 2), (b, 5), (c, 0) } In reality, my code is implemented as follows // This is highly simplified template<typename A, typename B> class overall_type { public: auto find(A min_a, A max_a) { // Find all elements between (min_a, -oo) and (max_a, oo) // How can I do this? } // A large number of other implementation details private: struct contained_type { A data_a; B data_b; auto operator<(contained_type const& other) -> bool { if (data_a < other.data_a) { return true; } if (data_a > other.data_a) { return false; } return data_b < other.data_b; } } std::set<contained_type> internal_data; } I want to find all elements within the range (for example) (b, -oo) <= e <= (b, oo). As I have implemented comparators for my data type, the data will be placed in-order within the set, meaning that I just need to find a starting point and an ending point. The problem I have is that I cannot be sure what the precise starting point is. In the example above, the lowest element is (b, 1), and therefore a simple find() operation won't suffice. Another constraint is that I don't know the minimum values for any of the types of elements that are contained within my data, because all the types are templates. I instead need to be able to search using incomplete data. I have also considered implementing my own binary search, but as sets don't seem to be random accessible, I cannot easily do so whilst using one. The only alternative I have considered is using a std::vector and implementing my own binary search over it, and adding code to insert to the correct position to keep it sorted, however the under-the-hood implmenetation of vectors means that I wouldn't meet the worst-case time complexity requirements of my project. Apologies if I have overlooked a clear solution here - my university has taught the STL exceptionally poorly, so there may be a data structure designed for this that I simply haven't heard of and which my numerous searches didn't uncover. How can I create a solution that matches the above criteria?
Something along these lines, perhaps. This relies on the capability, added in C++14, of std::set::equal_range et al to perform heterogeneous searches, given a comparator that has overloads for combinations of different types. template<typename A, typename B> class overall_type { public: auto find(A min_a, A max_a) { return internal_data.equal_range(RangeCover{min_a, max_a}); } private: using contained_type = std::pair<A, B>; struct RangeCover { A& min_a; A& max_a; }; struct Compare { using is_transparent = int; bool operator()(contained_type const& l, contained_type const& r) const { return l < r; } bool operator()(contained_type const& l, RangeCover const& r) const { return l.first < r.min_a; } bool operator()(RangeCover const& l, contained_type const& r) const { return l.max_a < r.first; } }; std::set<contained_type, Compare> internal_data; }; Demo Compare makes an instance of RangeCover compare equivalent to all instances of contained_type that have the first component in the range, ignoring the second one.
73,184,496
73,184,515
c++ is there a way of use properties allready declared in the header file inside implementation
I know it's a basic question, but I didn't find the answer anywhere. Supose we have this header: #pragma once; #include "user.h" class Teacher { public: float teachSkill = 0.01; void teach(User &user); }; And a implementation like this: #include "teacher.h" class Teacher { public: float teachSkill; void teach(User &user) { user.knowledge += (*this).teachSkill; } }; if we already declared that teachSkill property in the header, is there a way c++ compiler can understand that this property is in the header on an implementation like this: #include "teacher.h" class Teacher { public: void teach(User &user) { user.knowledge += (*this).teachSkill; } };
You can simply write, in the implementation: void Teacher::teach(User &user) { user.knowledge += (*this).teachSkill; } No need to re-declare the class there. Furthermore, you don't need (*this), so it's simply: void Teacher::teach(User &user) { user.knowledge += teachSkill; }
73,184,670
73,188,731
Visual Studio cmd doesn't display Unicode characters
I am trying to make an ASCII converter in C++ that outputs an image using ▀ ▄ ░ █ Unicode characters. It works, except for the output part. Instead of the actual characters, it just displays ?. When I add system("chcp 65001"); or system("chcp 65001"); (to use UTF-8/UTF-16) at the beginning of the file, it doesn't do anything, and still displays ? When I try add /source-charset:utf-8 /execution-charset:utf-8 to the debug properties, it writes some weird LoLs: Here is the whole code: #include <iostream> #define STBI_ONLY_BMP #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" int main(int argc, char* argv[]) { system("chcp 65001"); int width, height, channels; unsigned char* img = stbi_load("C:/Users/user/source/repos/OCBitmapConvert/grayscale.bmp", &width, &height, &channels, 1); if (img == NULL) { printf("Error in loading the image\n"); exit(1); } char imgarray[80][50]; printf("Loaded image with a width of %dpx, a height of %dpx and %d channels\n", width, height, channels); //Convert the image from 1 dimensional array to 2 dimensional array for(int y = 0; y < 50; y++){ for (int x = 0; x < 79; x++){ int pixell = (y*80)+x; if(img[pixell] == 0){ imgarray[x][y] = 0; } else imgarray[x][y] = 1; }; }; //Print the 2dim array (just for debugging that the 2d array conversion works correctly) for(int y = 0; y < 50; y++){ for(int x = 0; x < 79; x++){ printf("%d",imgarray[x][y]); } printf("\n"); } //Convert the image to ascii characters (using ▀ ▄ ░ █). 2 pixels above each other is 1 unicode character printf("\n\n\n"); for(int y = 0; y < 48; y= y+2){ for(int x = 0; x < 79; x++){ if(imgarray[x][y] == 0){ if(imgarray[x][y + 1] == 0){ printf("░"); } else printf("▄"); } else{ if(imgarray[x][y + 1] == 0){ printf("▀"); } else printf("█"); } } printf("\n"); } }
After testing, the following code can output ▀ ▄ ░ █ , you could refer to my code to modify your code. #include <stdio.h> #include <io.h> #include <fcntl.h> int main() { _setmode(_fileno(stdout), _O_U16TEXT); wprintf(L"░▒▓▄▀█▀ ▄ ░ █\n"); return 0; // CYRILLIC CAPITAL LETTER YAE U+0518 } Result: Update: I modified the code with reference to your sample, the code can still run, I suggest you refer to this code and modify it. #include <stdio.h> #include <io.h> #include <fcntl.h> #include <iostream> #define STBI_ONLY_BMP #define STB_IMAGE_IMPLEMENTATION int main() { _setmode(_fileno(stdout), _O_U16TEXT); char imgarray[80][50]; for (int y = 0; y < 50; y++) { for (int x = 0; x < 79; x++) { imgarray[x][y] = 1; } } for (int y = 0; y < 48; y = y + 2) { for (int x = 0; x < 79; x++) { if (imgarray[x][y] == 1) wprintf(L"░▒▓▄▀█▀ ▄ ░ █\n"); } } return 0; } Result: In this case you need to find the place that caused the exception. The debugger cannot predict the future, but you can tell it to break on all exceptions, (ctrl+atl+e and tick all the boxes under "Thrown"). When the assert happens walk down the call stack to your code it will tell you which line is causing the problem.
73,185,045
73,200,688
Compiler error with 'static const std::wstring DELETE;'
I started a new VCL application under C++Builder, and I observe something bizarre. When I declare a const member named DELETE as std::string, I get an error. Here is the .h file: #pragma once #ifndef Communication_ButtonTagH #define Communication_ButtonTagH #include <string> namespace OverB::Communication { class ButtonTag { public: static const std::wstring DELETE; }; } #endif And here is the .cpp file: #include "Communication_ButtonTag.h" namespace OverB::Communication { const std::wstring ButtonTag::DELETE = L"DELETE"; } Changing only the name of the const, the application builds correctly. I am using C++Builder 11.1 Alexandria, and Windows 11. Here is the list of errors: [C++ Error] Communication_ButtonTag.h(13, 32): expected member name or ';' after declaration specifiers [C++ Error] Communication_ButtonTag.h(13, 32): expected ')' [C++ Error] Communication_ButtonTag.h(13, 32): to match this '(' [C++ Error] Communication_ButtonTag.cpp(5, 35): expected unqualified-id Can anyone explain what is happening exactly?
The VCL is built on top of the Win32 API, which has a DELETE preprocessor macro defined in winnt.h: #define DELETE (0x00010000L) The preprocessor is run first, and it performs text replacements of defined macros before the compiler is run. Thus, after the preprocessor has processed your code and made its replacements, the compiler will see the following invalid code, which is why it errors: #pragma once #ifndef Communication_ButtonTagH #define Communication_ButtonTagH #include <string> namespace OverB::Communication { class ButtonTag { public: static const std::wstring (0x00010000L); }; } #endif #include "Communication_ButtonTag.h" namespace OverB::Communication { const std::wstring ButtonTag::(0x00010000L) = L"DELETE"; } In short, don't declare your own variables and identifiers that happen to match the names of Win32 API macros. The Win32 API is primarily a C library, not a C++ library. It doesn't use properly typed constants, or respect namespaces, etc. Common C++ best practices go out the window when dealing with the Win32 SDK.
73,185,229
73,185,230
'clang -ftime-trace' does not produce a JSON file
Clang supports the -ftime-trace flag since version 9 which allows to analyze compilation times by producing a JSON file that can be read by Google Chrome. Unfortunately, Clang fails to output a JSON file for me, even for the simplest program. Minimal example: I have a main.cpp file #include <iostream> int main(){ std::cout << "test" << std::endl; } Using Clang 13 (on WSL with Ubuntu 20.04) and compiling it with clang++ -ftime-trace main.cpp produces the executable a.out, but no JSON file. What am I doing wrong?
The -ftime-trace flag produces JSON files for each object file and places them next to each object file. It does not profile the linking stage. Running clang++ -ftime-trace main.cpp produces a temporary object file in the /tmp/ directory and then runs the linker to form the complete executable a.out in your working directory. Thus, if you look into the /tmp/ directory, you can actually find your JSON file there. Simply specify the -c flag, i.e., clang++ -ftime-trace -c main.cpp, to skip the linker and produce an object file main.o along the JSON file main.json in your working directory. You can also provide a different name for these files using the -o flag.
73,185,261
73,198,514
Unhandled exception: An invalid parameter was passed to a function that considers invalid parameters fatal in UWP application
So I was making a polynomial simplifier for my school project. I decided to make the application using C++ UWP in Visual Studio. As one of the extra features of the application I implemented a system to store and retrieve polynomials from a file so that you can access your previously entered polynomials. I am using boost::filesystem for this. The code compiles fine. But while debugging, this function: fs::exists(basePath) // namespace fs = boost::filesystem ...is somehow causing the following exception: Unhandled exception at 0x00007FFBB71AAFEC (ucrtbased.dll) in ExpressionSimplifierV4 UWP.exe: An invalid parameter was passed to a function that considers invalid parameters fatal. ..thrown from this line: rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments); // App.xaml.cpp My question: What is the cause of this exception and how do I resolve it? If any extra information is needed, do tell me... Thanks!
When writing UWP applications, be aware that they by design run in a 'locked-down' environment. One aspect of this is that they have very limited access to the file system. A UWP application by default has: read-only access to its own installed directory (which is typically the 'current working directory' at start-up). This is pointed to by Windows.ApplicationModel.Package.Current.InstalledLocation. read/write access to its own per user application data directory. The non-roaming version is ApplicationData.Current.LocalFolder. The roaming version is ApplicationData.Current.RoamingFolder. read/write access to a per user application temporary directory that may or may not be there on future invocations of the application. This is ApplicationData.Current.TemporaryFolder. Any attempt to access a file folder other than those above by default will fail. See Microsoft Docs.
73,185,798
73,186,302
Best practices for large array of integers in C++
I am loading a 123 MB file of unsigned integers that needs to be in memory (for fast look ups for a monte carlo simulation) in C++. Right now I have a global array but i've heard global arrays are frowned upon. What are the best practices for this? For context, I'm doing Monte Carlo simulations on a poker game and need an array of about 30 million integers to quickly compute the winner of a poker hand. To determine the winner, you first compute the 'handranks' by doing 7 queries of the array. Then to determine the winner, you compare the 'handranks'. int HR[32487834]; int get_handrank(const std::array<int,7> cards) { int p = 53; for (const auto& c: cards) p = HR[p + c]; return p; } int main() { // load the data memset(HR, 0, sizeof(HR)); FILE * fin = fopen("handranks.dat", "rb"); if (!fin) std::cout << "error when loading handranks.dat" << std::endl; size_t bytesread = fread(HR, sizeof(HR), 1, fin); fclose(fin); std::cout << "complete.\n\n"; // monte carlo simulations using get_handrank() function . . . }
Use local variables, and pass them to functions as appropriate. This makes the program easier to reason about. Use vector instead of an array for this large amount of data, otherwise you might cause stack overflow. Modify your functions to work with std::span instead of a particular container, as this creates more decoupling. Create a symbolic constant with a meaningful name for 32487834 instead of using it as a magic constant.
73,186,143
73,197,935
Error: the preLaunchTask build terminated with exit code -1, launch program does not exist
Recently I've been trying to move from CodeBlocks to Visual Studio Code, but the latter has been giving me problems especially when making projects with classes, in this case when trying to run it I get this window: the preLaunchTask C/C++:g++.exe build active file terminated with exit code -1 If I click show errors it tells me no problems have been detected in the workspace Then after clicking debug anyway this appears: launch program does not exist It's been a while since I've used VScode but I'm pretty sure that the launch program gets created when running the code of the program for the first time right? Here are my launch.json and task.json: launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "(Windows) Launch", "type": "cppvsdbg", "request": "launch", "program": "${workspaceFolder}/myfile.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": true }, { "name": "(Windows) Attach", "type": "cppvsdbg", "request": "attach", "processId": "${command:pickProcess}" } ] } tasks.json: { "version": "2.0.0", "tasks": [ { "label": "build myfile", "type": "shell", "command": "g++", "args": [ "-std=c++14", "-g", "-o", "myfile.exe", "myfile.cpp" ], "group": "build" }, { "type": "cppbuild", "label": "C/C++: g++.exe build active file", "command": "C:\\msys64\\mingw64\\bin\\g++.exe", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ] } I got all the .json from this answer to a similar question: https://stackoverflow.com/a/50658089/19009898 I used to have different.json which I guess were the default ones but this change doesn't seem to make any trouble for other previous code without classes that I've made so I'm guessing it's ok. Would appreciate the help.
Found a way in the spanish stack overflow. In tasks.json I added this: "label": "g++.exe build active file", "args": [ "-g", "${fileDirname}\\**.cpp", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe", ], Then run by either debuging or running the C/C++ file NOT just clicking run code and then it works perfectly.
73,186,343
73,186,392
Why c++ don't infer template argument T for simple nested types variables?
In this piece of code: #include <iostream> #include <vector> #include <utility> template <typename T> using Separation = std::pair<std::vector<T>, std::vector<T>>; int main() { std::vector<int> vector1 = {1}; Separation s1(vector1, vector1); std::cout << s1.first[0]; return 0; } The g++ compiler says: error: missing template arguments before ‘(’ token That can be fixed just by adding the template parameter to Separation. But, if v1 is a vector of integer, shouldn't the compiler be able to understand that T should be generic that comes from the vector??
If you can make it a subtype, you may add a deduction guide: #include <iostream> #include <vector> #include <utility> template <typename T> struct Separation : std::pair<std::vector<T>, std::vector<T>> { using std::pair<std::vector<T>, std::vector<T>>::pair; }; template <class T> Separation(std::vector<T>, std::vector<T>) -> Separation<T>; int main() { std::vector<int> vector1 = {1}; Separation s1(vector1, vector1); // works fine std::cout << s1.first[0]; return 0; }
73,186,387
73,186,708
std::uniform_real_distribution cannot be const anymore in MSVS2022?
In MSVS 2019 I used to declare my distribution const. Yet in the latest MSVS2022 preview, I get an error: error C3848: expression having type 'const std::uniform_real_distribution<double>' would lose some const-volatile qualifiers in order to call 'double std::uniform_real<_Ty>::operator ()<std::mt19937>(_Engine &)' 1> with 1> [ 1> _Ty=double, 1> _Engine=std::mt19937 1> ] If I strip the const all is fine again. Is this a MSVS2022 quirk? Or was 2019 wrong all that time? (example from https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution) #include <random> #include <iostream> int main() { std::random_device rd; // Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd() const std::uniform_real_distribution<> dis(1.0, 2.0); // this const will break in MSVS2022 for (int n = 0; n < 10; ++n) { // Use dis to transform the random unsigned int generated by gen into a // double in [1, 2). Each call to dis(gen) generates a new random double std::cout << dis(gen) << ' '; } std::cout << '\n'; }
const std::uniform_real_distribution<> was never guaranteed to be usable. The standard did not specify that operator() of std::uniform_real_distribution is const. In particular <random>'s distributions are allowed to have internal state, e.g. to remember unused bits returned from the generator or to store state if the transformation algorithm requires it. However, standard library implementations are allowed to add const on a non-virtual member function if that wouldn't affect any call to the function that would be well-formed without it according to the standard's specification. Therefore Microsoft's implementation was not non-conforming in allowing you to use the const version, even if that is not guaranteed to work according to the standard. Nonetheless Microsoft's standard library developers decided to remove the const by-default anyway, to encourage portability with other standard library implementations. They left the option to define _ALLOW_RANDOM_DISTRIBUTION_CONST_OPERATOR (e.g. on the command line /D_ALLOW_RANDOM_DISTRIBUTION_CONST_OPERATOR) to get back the old non-portable behavior if someone really needs it. All of this is explained and discussed in the corresponding issue https://github.com/microsoft/STL/issues/1912 and the pull request https://github.com/microsoft/STL/pull/2732.
73,186,510
73,193,383
Is checking the location of the sign bit enough to determine endianness of IEEE-754 float with respect to integer endianness?
I recently wrote some code that uses memcpy to unpack float/double to unsigned integers of the appropriate width, and then uses some bit-shifting to separate the sign bit from the combined significand/exponent. Note: For my use case, I don't need to separate the latter two parts from eachother, but I do need them in the correct order i.e: {sign, (exponent, significand)}, with the latter tuple packed as an unsigned int of sufficient width. My code is working fine, thoroughly tested and no trouble; however I was a bit alarmed to discover that IEEE-754 doesn't specify the endianness of its binary interchange formats —which to my understanding, means there is a rare possibility that my bit-shifting may be incorrect in the rare occasions where float endianness ≠ integer endianness. Based on the answered question here, my assumption is that given that bit-shifting is independent of actual endianness in storage, I only need to worry about whether the endianness of my floats matches that of my ints. I devised the following code loosely following that in the linked answer, but avoiding the use of type-punning through pointer casts, which seems like unspecified/undefined behaviour territory to me: #include <cstdint> #include <cstring> // SAME means "same as integer endianness" enum class FloatEndian { UNKNOWN, SAME, OPPOSITE, }; FloatEndian endianness() { float check = -0.0f; // in IEEE-754, this should be all-zero significand and exponent with sign=1 std::uint32_t view; std::memcpy(&view, &check, sizeof(check)); switch (view) { case 0x80000000: // sign bit is in most significant byte return FloatEndian::SAME; case 0x00000080: // sign bit is in least significant byte return FloatEndian::OPPOSITE; default: // can't detect endianness of float return FloatEndian::UNKNOWN; } } If I ensure that my floats are indeed IEEE-754 with std::numeric_limits<T>::is_iec559, is my approach a robust and portable way of making sure I get the floats "the right way round" when I chop them up?
Is checking the location of the sign bit enough to determine endianness of IEEE-754 float with respect to integer endianness? As I read it, given the C++ spec and the C spec that it tends to also rely on, checking the sign bit is technically insufficient to determine endian relationship between float/uint32_t. It is likely practically sufficient as endians other than big/little are rare as well as differences between float/uint32_t endian. I would suggest a different constant than -0.0f, maybe -0x1.ca8642p-113f which has the pattern 0x87654321 and would be a more thorough endian test. Quite unclear why OP wants to use a one's-bit-sparse -0.0f to discern 3 possible results. As mentioned by others, in C++, the test should be a compile time one, so thoroughness is not a run-time cost over the simplicity of only testing a sign bit. Relying on is_iec559 is true may unnecessarily limits portability as for that to be true, many non-finite compliance rules are needed. ref. Does your code really need quiet and signaling NANs? See also If is_iec559 is true, does that mean that I can extract exponent and mantissa in a well defined way?. I hope OP also tests that the sizeof(float) == sizeof(uint32_t) else memcpy(&view, &check, sizeof(check)) is bad code. is my approach a robust and portable way of making sure I get the floats "the right way round" when I chop them up? Code is not as robust and portable as it could be. "when I chop them up" --> that code is not shown, so unanswerable. I am suspect of the endianness() goal that is used to support "uses memcpy to unpack float/double to unsigned integers of the appropriate width, and then uses some bit-shifting to separate the sign bit from the combined significand/exponent." It is that code that deserves review.
73,187,171
73,187,205
How does the argument list for std::function work
I'm sorry if this is a very noobish question, but I'm confused on how you can specify std::function argument lists like this: std::function<void(double)> func; But in an actual function, this doesn't work: void passFunc(void(double) func) {} For the method above you have to specify a function pointer. So how is void(double) allowed to be passed into std::function? Is void(double) even a type? If not, how can it be in the argument list for std::function? If it is a type, why is it not valid to have void(double) be the type of a function parameter?
You can declare a type like that: using Func = void(double); But in the definition, you still need the name of the argument; otherwise, you could not use it in the function: void passFunc(void func(double)) {} Note that func is inbetween the return type and the arguments. If you don't like that, you can use the above-defined type: void passFunc(Func func) {}
73,187,217
73,187,415
Problem with CreateProcessA() windows 10 c++ code::blocks
I have a problem with CreateProcessA, I looked at all the questions about it on stackoverflow and other sites, I rewrote a program following the advice of others but it still does not execute any commands and return error 998. I'm sure the string is correct because it works both with system and written directly on cmd. I really don't know what to do anymore. I've also read how it works but doesn't want to work. Sorry if my english is bad, thanks to those who answer me. #include <iostream> #include <windows.h> using namespace std; int main() { STARTUPINFOA si; si.cb = sizeof(si); PROCESS_INFORMATION pi; string com="\"C:\\Program Files\\MKVToolNix\\mkvextract.exe\" \"D:\\Anime recuperati\\BKT\\Caricati\\[BKT] Jormungand 01-12 END BDRip\\Jormungand - Ep01.mkv\" attachments -f 1:\"C:\\Users\\Utente\\Desktop\\Subs\\n\\Jormungand - Ep01\\Justus-Bold.ttf\""; CreateProcessA(NULL,const_cast<char *>(com.c_str()),NULL,NULL,FALSE,0,NULL,NULL,&si,&pi); cout<<GetLastError(); return 0; }
You pass uninitialized STARTUPINFOA si;. It must be initialized. See the example. #include <iostream> #include <string> #include <windows.h> using std::cout; using std::string; int main() { STARTUPINFOA si{sizeof(si)}; PROCESS_INFORMATION pi{}; string com = R"("C:\Program Files\MKVToolNix\mkvextract.exe" "D:\Anime recuperati\BKT\Caricati\[BKT] Jormungand 01-12 END BDRip\Jormungand - Ep01.mkv" attachments -f 1:"C:\Users\Utente\Desktop\Subs\n\Jormungand - Ep01\Justus-Bold.ttf)"; CreateProcessA(nullptr, const_cast<char *>(com.c_str()), nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi); cout<<GetLastError(); return 0; } #include <string> if you use std::string. Use R"(...)" to avoid using escape sequences. Use nullptr in C++. Use false in C++. Why is using namespace std; considered bad practice?
73,187,451
73,187,472
Is assignment operator a sequence point under C++17? and what would be the result of this expression?
It is recommended not to modify an object more than once in a single expression nor using it after modifying it in the same expression. int i = 0; ++++i; // UB ++i = i++; // OK? I think that the last expression was UB before C++17 standard but now I guess it is OK because the assignment operator has become a sequence point. So what do you think? and can you explain to me what value should i in the last expression be ++i = i++;? I know it is of bad design to do so but it is just for education purpose. Thank you. When I compile against C++17 or C++20: g++ main.cpp -std=c++17 -o prog -Wall -pedantic I still get the same warning: ++i = i++; This is the output from GCC: main.cpp: In function ‘int main()’: main.cpp:12:12: warning: operation on ‘i’ may be undefined [-Wsequence-point] 12 | ++i = i++; | ~^~.
There's no sequence points now: we have sequenced-before and sequenced-after. When you have an operator= call (or any other operator@= call - built-in operator= or user-defined call), right-hand side is sequenced-before left-hand side. So ++i = i++ is valid in C++17, with i++ sequenced-before ++i. Before C++17, as you wrote, it was UB.
73,187,895
73,188,317
Getting full path in C++ adjacency list Dijkstra
I want to get full path in adjacency list Dijkstra algorithm using C++ queue. Graph edges are oriented. Dijkstra algorithm works fine and I understand why. However getting full path is a bit more complicated to me, this usually described much less than Dijkstra algorithm itself. I tried to reused a few solutions (this, for example) I've found for square matrix, but it didn't worked for my adjacency list implementation. Part I'm stucked with: int dijkstra(int start, int finish) { //some code parent.resize(vertex_count(), -1); while (!q.empty()) { //some code for (auto edge : link[current]) { if (dist[current] + edge.weight < dist[edge.to]) { dist[edge.to] = dist[current] + edge.weight; parent[edge.to] = start; q.push(QueueVertex(edge.to,dist[edge.to])); } } } path(parent); return dist[finish]; } void path(vector<int> parent) { for (auto i = 0; i < parent.size(); i++) { if (parent[i] != -1) cout << i << ' '; } cout << endl; } Full code: #include <iostream> #include <queue> #include <algorithm> #include <vector> #include <climits> #define INF INT_MAX using namespace std; struct Edge { int to; int weight; Edge() {} Edge(int to, int weight) : to(to), weight(weight) {} void read() { cin >> to >> weight; } }; struct QueueVertex { int number; int dist; QueueVertex(int number, int dist) : number(number), dist(dist) {} }; bool operator<(const QueueVertex& v1, const QueueVertex& v2) { return v1.dist > v2.dist; } class Graph { vector<vector<Edge>> link; vector <int> dist; vector<int> parent = {}; public: Graph(int vertex_count) : link(vertex_count) {} void add_edge_u(int from, int to, int weight) { //unoriented link[from].push_back(Edge(to, weight)); link[to].push_back(Edge(from, weight)); } void add_edge_o(int from, int to, int weight) { //oriented link[from].push_back(Edge(to, weight)); } int vertex_count() const { return link.size(); } int dijkstra(int start, int finish) { dist.resize(vertex_count(), INF); dist[start] = 0; parent.resize(vertex_count(), -1); priority_queue <QueueVertex> q; q.push(QueueVertex(start, 0)); while (!q.empty()) { int current = q.top().number; int current_dist = q.top().dist; q.pop(); if (current_dist > dist[current]) { continue; } for (auto edge : link[current]) { if (dist[current] + edge.weight < dist[edge.to]) { dist[edge.to] = dist[current] + edge.weight; parent[edge.to] = start; q.push(QueueVertex(edge.to,dist[edge.to])); } } } path(parent); return dist[finish]; } void path(vector<int> parent) { for (auto i = 0; i < parent.size(); i++) { if (parent[i] != -1) cout << i << ' '; } cout << endl; } }; int main() { { int n = 3, m = 3, start = 1, finish = 0; Graph gr(n); gr.add_edge_o(0, 1, 1); gr.add_edge_o(1, 2, 2); gr.add_edge_o(2, 3, 5); gr.add_edge_o(3, 0, 4); int dist = gr.dijkstra(start, finish); cout << dist << endl; return 0; } Desirable output (program getting 11 just fine, but not 1 2 3 0 part): 1 2 3 0 11 Thank you.
Your path function makes no sense. You should be using the parent array to walk backwards from the goal state to the start. As written, this function simply outputs all the parents. Consider something like this: deque<int> path; while(finish != -1) { path.push_front(finish); finish = (finish == start) ? -1 : parent[finish]; } for (int node : path) cout << (node + 1) << ' '; cout << endl; Note that the above uses a std::deque for convenience, since the path is built in reverse. But you can use a std::vector if you wish, and either reverse it or walk over it with a reverse_iterator. Now that the path is being built correctly, you'll quickly see another problem, which is that your parent table is not being built correctly. You're doing this: parent[edge.to] = start; //<-- incorrect That looks like a copy/paste error, because you don't want every node's parent to point back at the start. The parent of the edge being examined is stored in current: parent[edge.to] = current; //<-- correct
73,188,576
73,188,847
How to alloc largest available memory on different computer?
If I need a program to r/w data larger then 1T randomly, a simplest way is putting all data into memory. For the PC with 2G memory, we can nevertheless work by doing a lot of i/o. Different computers have different size memory, so how to alloc suitable memory on computers from 2G to 2T memory in one program? I thought of popen /proc/meminfo and alloc MemFree but I think it maybe have a better way. note: use Linux, but other OS is welcome avoid being OOM killed as well as possible (without root) disk i/o as less as possible use multiprocessing c or c++ answer is fine
You can use the GNU extension get_avphys_pages() from glibc The get_phys_pages function returns the number of available pages of physical the system has. To get the amount of memory this number has to be multiplied by the page size. Sample code: #include <unistd.h> #include <sys/sysinfo.h> #include <stdio.h> int main() { long int pagesize = getpagesize(); long int avail_pages = get_avphys_pages(); long int avail_bytes = avail_pages * pagesize; printf( "Page size:%ld Pages:%ld Bytes:%ld\n", pagesize, avail_pages, avail_bytes ); return 0; } Result Godbolt Program returned: 0 Page size:4096 Pages:39321 Bytes:161058816 This is the amount of PHYSICAL memory in your box so: The true available memory can be much higher if the process pages in/out The physical memory is a maximum as there would be other processes using memory too. So treat that result as an estimate upper bound for available DDR. If you plan to allocate large chunks of memory use mmap() directly as malloc() would be too high level for this usage.
73,189,041
73,189,451
Why I did not get the right result in this c++ code ( see the f3.show_fraction() in main )?
I did not get right result for object f3 when I see the f3 using show_fraction() function in the below code: I am confused. I want to access the sum of f1 and f2 fraction that is stored in f3.But when i see the result in f3 it shows 0/0 in result using fraction_show() function #include <iostream> using namespace std; class fraction { private: float numerator; float denominator; char ch; public: void get_fraction() { cout << "\nEnter the fraction ( in format n/d ): "; cin >> numerator >> ch >> denominator; } void show_fraction() { cout << " Fraction is: " << numerator << "/" << denominator; } fraction sum(fraction &f, fraction &d) // returns sum of two fractions { fraction ff; // to hold the result // denominator of result ff.numerator = (f.numerator * d.denominator + f.denominator * d.numerator); ff.denominator = f.denominator * d.denominator; // numerator of result return ff; } }; int main() // program to test the class { fraction f1, f2, f3; // three objects of type fraction created char ch1; do { f1.get_fraction(); f2.get_fraction(); f3.sum(f1, f2); cout << "\nSum of "; f3.show_fraction(); // shows the result ( wrong result) cout << "\nDo you want to continue ( y/n ): "; // If the user want to continue cin >> ch1; } while (ch1 != 'n'); cout << endl; return 0; } // end of main
I don't like this style of coding, but at least this works void sum(fraction &f, fraction &d) // calculates sum of two fractions { numerator = (f.numerator * d.denominator + f.denominator * d.numerator); denominator = f.denominator * d.denominator; } then f3.sum(f1, f2); I would prefer something like this friend fraction sum(fraction &f, fraction &d) // returns sum of two fractions { fraction ff; // to hold the result // denominator of result ff.numerator = (f.numerator * d.denominator + f.denominator * d.numerator); ff.denominator = f.denominator * d.denominator; // numerator of result return ff; } with this version you need to change the way you call the function f3 = sum(f1, f2); I'm not sure which you were intending but you wrote something that was half way between the two versions.
73,189,351
73,204,858
"Name: value" widget via GTK
How to make a widget via GTK that looks like the following? ------------------ | Text1: | 1 | |-----------+----| | Text2: | 10 | |-----------+----| | | | | | | | | | ------------------ 'Text1', 'Text2' - constant strings; '1', '10' - dynamically changed values. What Gtk::Widget's should I use for that?
Make Gtk::Grid with labels, align them, set column spacing and column homogeneous. #include <gtkmm.h> class window : public Gtk::Window { protected: Gtk::Box box; Gtk::Grid grid; Gtk::Button button; Gtk::Label name1, name2, value1, value2; int n_click = 0; public: window(); ~window() = default; void on_click() { value1.set_label("1"); value2.set_label(n_click % 2 ? "1" : "10"); n_click++; queue_draw(); } }; window::window() : button("Update"), name1("Text:"), name2("Text2:") { add(box); box.pack_start(button); button.signal_clicked().connect(sigc::mem_fun(*this, &window::on_click)); box.pack_end(grid, Gtk::PACK_SHRINK); grid.attach(name1, 0, 0, 2, 1); grid.attach(value1, 2, 0, 1, 1); grid.attach(name2, 0, 1, 2, 1); grid.attach(value2, 2, 1, 1, 1); name1.set_halign(Gtk::ALIGN_START); name2.set_halign(Gtk::ALIGN_START); value1.set_halign(Gtk::ALIGN_START); value2.set_halign(Gtk::ALIGN_START); grid.set_column_spacing(10); grid.set_column_homogeneous(true); show_all(); } int main(int argc, char *argv[]) { auto app = Gtk::Application::create(argc, argv, ""); window win; return app->run(win); }
73,189,691
73,190,169
Storing a std::function as a private member results in it being null when used
I am at a loss for why this isn't working. I've tried passing a function by value, by reference, and still when I go to call the function from within SetFromState, it is null. My class: StateIndicator::StateIndicator(QWidget *parent) { StateIndicator(parent, StateIndicator::DefaultSelectionStrategy); } StateIndicator::StateIndicator(QWidget *parent, const std::function<std::string (State)>& selectionStrategy) :QWidget(parent), selection_strategy_(selectionStrategy) { wrapped = new QLabel(this); } void StateIndicator::SetFromState(State state) { std::string resourcePath = selection_strategy_(state); wrapped->setTextFormat(Qt::TextFormat::RichText); char* buffer = new char[StateIndicator::label_format.length() + resourcePath .length()]; sprintf(buffer, label_format.c_str(), resourcePath .c_str()); wrapped->setText(buffer); } std::string TruckStateIndicator::DefaultSelectionStrategy(State state){ return ":img/Disconnected"; } call: StateIndicator* state = new StateIndicator(this); ui->leftPaneLayout->insertWidget(1,state); state->SetFromState(State::Connected); When I use the debugger, in my constructor it shows that my selection strategy is set. But when I get to the call to SetFromState the private member selection_strategy_ is null. However, my code works if within the SetFromState function I instead change it to: std::function<std::string(TruckState)> strategy = &DefaultSelectionStrategy; std::string path = strategy(state); and assign the variable right there. It feels like something is going out of scope and causing my function pointer to become null, but I'm pretty much stuck. Edited: Here is the header file. I will also try to make the example minimal by removing the inheritance and trying to reproduce #ifndef STATEINDICATOR_H #define STATEINDICATOR_H #include <QLabel> #include "src/models/state.h" class StateIndicator : public QWidget { public: explicit StateIndicator(QWidget* parent); explicit StateIndicator(QWidget* parent, const std::function<std::string (State)>& selectionStrategy); void SetFromState(State state); private: static std::string DefaultSelectionStrategy(State state); QLabel* wrapped; const std::function<std::string(State)> image_selection_strategy_; inline const static std::string label_format = "&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;" "img src=&quot;%s&quot;/&gt;" "&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; }; #endif // TRUCKSTATEINDICATOR_H
The problem was with how I was calling the overloaded constructor it seems: StateIndicator::StateIndicator(QWidget *parent) { StateIndicator(parent, StateIndicator::DefaultSelectionStrategy); } should be StateIndicator::StateIndicator(QWidget *parent) : StateIndicator(parent, StateIndicator::DefaultSelectionStrategy) { }
73,189,899
73,189,975
Why 0xFEFF appear in recv data
i try to create a client written in c++ and a server using python flask. The task is simple, client connect and get data from server, then display it on console. I have two piece of code: Server: from flask import Flask app = Flask(__name__) @app.route('/hello') def hello(): return "hello".encode("utf-16") if __name__ == "__main__": app.run(debug=True,host="127.0.0.1") Client: BOOL bResults = FALSE; bool ret = false; DWORD dwDownloaded = 0; WCHAR wDataRecv[1024] = {0}; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; DWORD dwSize = 0; HINTERNET hSession = WinHttpOpen(L"WinHTTP Example/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); # open session to connect hConnect = WinHttpConnect(hSession, L"localhost", (port == 0) ? INTERNET_DEFAULT_HTTP_PORT : port, 0); # connect to localhost with port 80 or custom port (this time i use port 5000) if (!hConnect) goto Free_And_Exit; hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/hello", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (hRequest) { bResults = WinHttpSendRequest(hRequest, NULL, 0,WINHTTP_NO_REQUEST_DATA, 0,0, 0);# send GET request } if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); if (bResults) { dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) { std::cout << "WinHttpQueryDataAvailable failed with code: " << GetLastError(); } if (!WinHttpReadData(hRequest, wDataRecv, dwSize, &dwDownloaded)) { std::cout << "WinHttpReadData failed with code: " << GetLastError(); } std::wcout << wDataRecv; # wcout wont print anything to console } Free_And_Exit: #clean up if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); return ret; I noticed that the data return from server like: b'\xfe\xff\hello' Why 0xFEFF is there ?
Its is BOM (byte order mark). I just need to decode from the client or use: return "hello".encode('UTF-16LE') # not UTF-16
73,189,988
73,190,207
Is there a better way to overload operators on objects without making tons of copies?
So I wrote a very simplified example of what I'm trying to accomplish which in this case is a simple "matrix" struct. As expected this program will compile and run (gcc 9.4 on ubuntu 20.04) and provide a valid result for the matrix D, however the problem is that I can't use references as arguments for the functions and overloaded operators (I've tried and it just spits out undefined references) and which will result in a ton of copies of the object "matrix" to evaluate matrix<int> D = C^(ExpFunc(A + B)). So the question is: What would be the "correct" or better way to accomplish this? Thank you!! (before you go all out recommending all those great libs that will handle this way way better and will be more reliable and etc.. I want to do this from scratch to learn and improve my skills and knowledge) //f.h file #include <iostream> #include <vector> #include <math.h> template <typename T> struct matrix { std::vector<T> data; size_t lines, columns; matrix() = default; matrix(const size_t L, const size_t C); void print(); }; //operation A + B = result template <typename T> matrix<T> operator+(matrix<T> A, matrix<T> B); //Hadamard product of A # B template <typename T> matrix<T> operator^(matrix<T> A, matrix<T> B); //element-wise e^x function template <typename T> matrix<T> ExpFunc(matrix<T> A); //f.cpp file #include "f.h" template <typename T> matrix<T>::matrix(const size_t L, const size_t C){ matrix<T>::data.resize(L * C); matrix<T>::lines = L; matrix<T>::columns = C; } template matrix<int>::matrix(const size_t L, const size_t C); template <typename T> void matrix<T>::print(){ for (size_t i = 1; i < matrix<T>::lines + 1; i++) { std::cout << "| "; for (size_t j = 1; j < matrix<T>::columns + 1; j++) { std::cout << matrix<T>::data[(i - 1) * matrix<T>::columns + (j - 1)] << " "; } std::cout << "|" << std::endl; } std::cout << "--------------" << std::endl; } template void matrix<int>::print(); template <typename T> matrix<T> ExpFunc(matrix<T> A){ for (auto& ie : A.data) ie = exp(ie); return A; } template matrix<int> ExpFunc(matrix<int> A); //operation A + B = result template <typename T> matrix<T> operator+(matrix<T> A, matrix<T> B){ for (size_t i = 0; i < A.data.size(); i++){ A.data[i] += B.data[i]; } return A; } template matrix<int> operator+( matrix<int> A, matrix<int> B); template <typename T> matrix<T> operator^( matrix<T> A, matrix<T> B){ for (size_t i = 0; i < A.data.size(); i++){ A.data[i] *= B.data[i]; } return A; } template matrix<int> operator^( matrix<int> A, matrix<int> B); And the main.cpp file #include "f.h" int main(){ matrix<int> A(3,3), B(3,3), C(3,3); A.data = std::vector<int>{0,0,0,1,1,1,2,2,2}; B.data = std::vector<int>{9,1,8,2,7,3,6,5,4}; C.data = std::vector<int>{1,2,3,4,5,6,7,8,9}; matrix<int> D = C^(ExpFunc(A + B)); D.print(); return 0; }
This compiles and should work fine: #include <vector> template <typename T> struct matrix { std::vector<T> data; std::size_t lines, columns; matrix() = default; matrix(const std::size_t L, const std::size_t C); void print(); }; template <typename T> matrix<T> operator+(const matrix<T>& A, const matrix<T>& B); template <typename T> matrix<T> operator+(const matrix<T>& A, const matrix<T>& B) { matrix<T> rtrn(A.lines, A.columns); for (std::size_t i = 0; i < A.data.size(); i++) rtrn.data[i] = A.data[i] + B.data[i]; return rtrn; } You could also keep the current pattern of using the left input as a copy for the output. It is reasonably efficient but may increase code size. template <typename T> matrix<T> operator+(matrix<T> A, const matrix<T>& B); template <typename T> matrix<T> operator+(matrix<T> A, const matrix<T>& B) { for (std::size_t i = 0; i < A.data.size(); i++) A.data[i] += B.data[i]; return A; } Normally, I would advise against this pattern because it invokes a copy that could instead be folded into the computation (reducing the total number of memory operations). However, you use std::vector internally and that always zero-initializes its elements. Therefore compared to the version above, the copy only replaces one memset with a memcpy. Not much worse. Further reduction in allocations If you want to reduce the number of temporary vectors further in chained operations such as C^(ExpFunc(A + B)) you can change the operations to work on expression objects, similar to what Eigen does.
73,190,294
73,190,344
Is there any tools for detecting files and lines that is using c++17 features?
Question Is there any tools for detecting files and lines that is using c++17 features? Background I'm developing some software with c++17. Recentlty a customer requested us to list files and lines that is using c++17 features. The reason is that they have to applicate deviation permits for using c++17 feature because their internal coding conventions is standarized by c++14. It may be possible to detect them using a compiler, but the compiler stops every time it detects an error, making it time-consuming to detect all errors. For ease to list up, I asked above question! What we tried I tried to use cpplint/clang-format. But these tools didn't detect c++17 feature despite c++14 option. The code I tested is below. #include <iostream> // C++17 feature namespace aaa::bbb::ccc { void f() { std::cout << "a new nested namespace definition is worked!\n"; } } namespace aaa { namespace bbb { namespace ccc { void g() { std::cout << "a legacy nested namespace definition is workded.\n"; } } } } int main() { aaa::bbb::ccc::f(); aaa::bbb::ccc::g(); }   Thank you!
If you compile with Clang, the -Wpre-c++17-compat diagnostic flag warns about the case from your example: <source>:4:14: warning: nested namespace definition is incompatible with C++ standards before C++17 [-Wpre-c++17-compat] namespace aaa::bbb::ccc ^ 1 warning generated. It will also warn on if/switch initialization statements, pack fold expressions, decomposition declarations and a bunch of other common C++17 features that aren't in earlier versions. The full list of cases is included in the reference of all diagnostic flags, here: https://clang.llvm.org/docs/DiagnosticsReference.html#wpre-c-17-compat By default, Clang will warn, then carry on compiling. If your build uses -Werror, you may want to disable that for this warning with -Wno-error=pre-c++17-compat.
73,190,422
73,192,691
Is there a flood fill outlining algorithm for constructing a polygon?
Is there a flood fill like method of generating an outline around the object? I'm trying to detect an object in an image and outline it. I'm currently successful with highlighting it but don't know how to outline. I'm using QT C++ and would like to construct a QPolygon of the points at the edges. My code so far: while(!stack.empty()) { auto curr = stack.pop(); const auto x = curr.first.x(), y= curr.first.y(); if(x>=maxX || y>=maxY || x<minX || y<minY || memo[x+y*img.width()]) { continue; } auto currColor = orig[x+y*img.width()]; auto diff = colorDifference(currColor, curr.second); if(diff < 40) { memo[x+y*img.width()] = true; stack.push(make_pair(QPoint(x-1,y),currColor)); stack.push(make_pair(QPoint(x+1,y),currColor)); stack.push(make_pair(QPoint(x,y-1),currColor)); stack.push(make_pair(QPoint(x,y+1),currColor)); changed[x+y*img.width()] = filler; //highlight pixel, need to be replaced with outlining } }
You can use OpenCV API, cv::findContours().(It's based on Satoshi et al., 1985) Call cv::findContours() on the image you labeled. It returns points of all contours(outlines).(Be careful to filter out trivial contours in the tree of contours such as a root node.) See the official tutorial, Contours Hierarchy.
73,191,905
73,204,134
Cannot run more than 1 thread in parallel using OpenMP in Windows 11, VIsual Studio 2019
I created an empty C++ project using Visual Studio 2019 in Windows 11. Then I ran this minimal piece of code to test multi-threading, using OpenMP: #include <iostream> #include <omp.h> int main() { omp_set_dynamic(0); // ensure that the number of threads doesn't change due to system demands omp_set_num_threads(16); std::cout << "Max threads: " << omp_get_max_threads() << "\n"; int id; #pragma omp parallel private(id) { std::cout << "Number of threads running in parallel: " << omp_get_num_threads() << "\n"; std::cout << "Thread ID in parallel region: " << omp_get_thread_num() << "\n"; } return 0; } This is the output I am getting: Max threads: 16 Number of threads running in parallel: 1 Thread ID in parallel region: 0 I first tried multithreading in a CMake project (used CMake 3.22 and the modern way of including OpenMP in a CMake project) and attempted using both the Visual Studio 2019 and 2022 compilers. The result was the same, I couldn't get more than 1 thread to run in parallel. So, then I tried this simple example in Visual Studio 2019 and ran into the same issue. I'm wondering if there is some Windows rule/setting that restricts the number of threads I can use. Btw, using Matlab 2021b and the Parallel Computing toolbox, I was able to use multithreading successfully (8/16 threads). If you need any other information about the issue/my system, don't hesitate to ask it from me. Thank you. Edit: I get the following output from CMake "C:\Program Files\JetBrains\CLion 2022.1.1\bin\cmake\win\bin\cmake.exe" -DCMAKE_BUILD_TYPE=Debug "-DCMAKE_MAKE_PROGRAM=C:/Program Files/JetBrains/CLion 2022.1.1/bin/ninja/win/ninja.exe" -G Ninja -S C:\Users\parvanitis\Documents\MBI_code\cpp\ImagingFocus -B C:\Users\parvanitis\Documents\MBI_code\cpp\ImagingFocus\cmake-build-debug The CXX compiler identification is MSVC 19.32.31332.0 The CUDA compiler identification is NVIDIA 11.6.124 Detecting CXX compiler ABI info Detecting CXX compiler ABI info - done Check for working CXX compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.32.31326/bin/Hostx64/x64/cl.exe skipped Detecting CXX compile features Detecting CXX compile features - done Detecting CUDA compiler ABI info Detecting CUDA compiler ABI info - done Check for working CUDA compiler: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.6/bin/nvcc.exe - skipped Detecting CUDA compile features Detecting CUDA compile features - done Found Matlab: C:/Program Files/MATLAB/R2022a/extern/include (found version "9.12") found components: MAT_LIBRARY Found Git: C:/Program Files/Git/cmd/git.exe (found version "2.36.1.windows.1") Found OpenMP_CXX: -openmp (found version "2.0") Found OpenMP: TRUE (found version "2.0") Configuring done Generating done Build files have been written to: C:/Users/parvanitis/Documents/MBI_code/cpp/ImagingFocus/cmake-build-debug [Finished]
OK, real rookie mistake(s) here. First of all, I didn't add the /openmp flag to the CMAKE_CXX_FLAGS which is necessary in Windows (I thought find_package(OpenMP) was enough, while adding -fopenmp, as in Linux, was not recognized, so I skipped it). Even after I did, it didn't work. The reason was that the project I was building was also using CUDA and I was calling the OpenMP-multithreaded code from a .cu file, which is of course compiled using NVCC, which is ignorant of the CXX flags, and most likely does not have any reason to support them awyway. So, I needed to move the OpenMP-multithreaded code to a .cpp file in order for it to work. I didn't mention my project was also using CUDA in the first place because I didn't think that would cause a problem (silly me). Thanks for your help anyway Jérôme.
73,192,837
73,193,909
Set Extended Styles on Win32 Edit Control
Is it possible to set extended styles on Edit control (simple Edit, not Rich Edit)? For example, I want to set the extended style to WS_EX_ZOOMABLE | WS_EX_ALLOWEOL_ALL. The creation of the control is as follows: HWND hEdit = CreateWindowExW( ES_EX_ZOOMABLE | ES_EX_ALLOWEOL_ALL, L"EDIT", L"", WS_BORDER | WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL, 0, 0, 100, 100, hWndMain, (HMENU)ID_EDIT, hInstance, NULL ); The problem is that none of the extended styles work. The EOL is still CR LF and the control isn't zoomable.
As noted in comments, edit control extended styles are set by sending the control an EM_SETEXTENDEDSTYLE message: HWND hEdit = ::CreateWindow( L"EDIT", L"", WS_BORDER | WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL, 0, 0, 100, 100, hWndMain, (HMENU)ID_EDIT, hInstance, NULL ); DWORD exStyles = ES_EX_ZOOMABLE | ES_EX_ALLOWEOL_ALL; ::SendMessage( hEdit, EM_SETEXTENDEDSTYLE, exStyles, exStyles ); You pass the style bits you want to modify as the wParam argument (the mask) and you pass the new values of these bits as the lParam argument. This allows you to both set and clear styles using a single call, without having to query for the previous values of these styles. This is a very common pattern used by many APIs. If you only want to enable these styles, set wParam and lParam to the same values, as I did in the code sample above. If you want to clear style bits, leave out the ones you want to clear from the lParam argument. E. g. to set ES_EX_ZOOMABLE but clear ES_EX_ALLOWEOL_ALL: ::SendMessage( hEdit, EM_SETEXTENDEDSTYLE, ES_EX_ZOOMABLE | ES_EX_ALLOWEOL_ALL, ES_EX_ZOOMABLE ); To clear both bits: ::SendMessage( hEdit, EM_SETEXTENDEDSTYLE, ES_EX_ZOOMABLE | ES_EX_ALLOWEOL_ALL, 0 ); Manifest requirements For the extended styles to actually work, you need to specify version 6.0 of the common controls in the application manifest. One of the easiest ways to do this is to insert the following compiler directive in your code, typically in the precompiled header file: #pragma comment(linker,"\"/manifestdependency:type='win32' \ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") Background information This is likely how the control handles EM_SETEXTENDEDSTYLE in terms of bit-wise operations: auto newExStyle = currentExStyle & ~wParam | lParam; Invert all bits of wParam, using bit-wise NOT (~). Apply the result as a mask to currentExStyle, using bitwise AND (&). This clears all these bits from currentExStyle that were initially set for wParam. Using bit-wise OR (|), set the bits that were passed for lParam.
73,193,356
73,193,408
Thread safety for deterministic one-time write to static location?
I'm checking CPUID flags on x86-64 for instruction set extensions, and caching the results in a static array. The function doing this may be called from any of several different threads, so race conditions are possible - but does this matter? Any thread will produce the same results, so I don't care about conflicting writes, and checking the same flags more than once is a non-issue. My conclusion is that this is safe, but am I missing something? Here's a stripped-down version of what I'm doing: enum class Arch : int { SSE2, AVX, MAX }; static bool CheckCPUID(Arch arch) { // Check CPU features } static bool IsSupportedArch(Arch arch) { enum class TriVal : int { Unknown, True, False }; constexpr int arch_max = static_cast<int>(Arch::MAX); const int i_arch = static_cast<int>(arch); // Cache results in-memory: static TriVal cached_results[arch_max - 1] = { TriVal::Unknown, TriVal::Unknown }; if (cached_results[i_arch] == TriVal::Unknown) { cached_results[i_arch] = CheckCPUID(arch) ? TriVal::True : TriVal::False; } return cached_results[i_arch] == TriVal::True; }
so I don't care about conflicting writes Conflicting writes to non-atomic objects are a data race and a data race always causes undefined behavior. The compiler may optimize based on that. Therefore you must care about this. You can use a std::array<TriVal, arch_max - 1> for the static local variable cached_results and have it be set in its initializer. The initialization of static local variables is guaranteed to be thread-safe and executed exactly once (assuming C++11 or later). static bool IsSupportedArch(Arch arch) { enum class TriVal : int { Unknown, True, False }; constexpr int arch_max = static_cast<int>(Arch::MAX); const int i_arch = static_cast<int>(arch); // Cache results in-memory: static const auto cached_results = []{ std::array<TriVal, arch_max-1> cached_results; // loop here to set the whole array return cached_results; }(); return cached_results[i_arch] == TriVal::True; } Alternatively you can mark the variable thread_local, but in that case every thread will call CPUID once. If you really care that CPUID is called only as few number of times as required, you can make the array elements std::atomics: static std::atomic<TriVal> cached_results[arch_max - 1]{}; In that case it is ok to have concurrent writes and as you say you don't care about which one ends up being the value. You probably want to replace the loads and stores with relaxed memory order operations though, since you don't need the default seq_cst guarantees: static bool IsSupportedArch(Arch arch) { enum class TriVal : int { Unknown, True, False }; constexpr int arch_max = static_cast<int>(Arch::MAX); const int i_arch = static_cast<int>(arch); // Cache results in-memory: static std::atomic<TriVal> cached_results[arch_max - 1]{}; auto value = cached_results[i_arch].load(std::memory_order_relaxed); if (value == TriVal::Unknown) { // OK only if CheckCPUID is guaranteed to always // return the same value value = CheckCPUID(arch) ? TriVal::True : TriVal::False; cached_results[i_arch].store(value, std::memory_order_relaxed); } return value == TriVal::True; }
73,193,691
73,199,757
Understanding calling inherited methods from abstract class in C++
I was doing an experiment on inheritance and abstract classes without using pointers (avoiding the use of new when possible), and I came across a behavior that makes sense but I havent found documentation on it on the internet (neither a name for it or example). I create a class, Abstract that has two methods, one is defined and the other is not. Then, a class Inherited inherits from Abstract and implements this second method. Heres the classes: Abstract.hpp: #ifndef ABSTRACT_HPP # define ABSTRACT_HPP #include <iostream> class Abstract { public: Abstract() {}; ~Abstract() {}; virtual void DoSomethingAbstract() = 0; void DoSomethingNormal() { std::cout << "Inside Abstract::DoSomethingNormal" << std::endl; DoSomethingAbstract(); } }; #endif /* ABSTRACT_HPP */ Inherited.hpp : #ifndef Inherited_HPP # define Inherited_HPP #include "Abstract.hpp" class Inherited : public Abstract { public: Inherited() {}; ~Inherited() {}; virtual void DoSomethingAbstract() { std::cout << "Inside Inherited::DoSomethingAbstract" << std::endl; } }; #endif /* Inherited_HPP */ The following main works as expected (the only implementation of each function is the one that is called): #include "Abstract.hpp" #include "Inherited.hpp" int main() { Inherited a; a.DoSomethingNormal(); return 0; } output: Inside Abstract::DoSomethingNormal Inside Inherited::DoSomethingAbstract Mostly I'd like to know if this is a UB and I'm just getting lucky, an unfrequent way of checking runtime polymorphism (which should not since there are no pointers to abstract classes here), or a perfectly defined behaviour somewhere in the standard. PS: I am compiling with g++ 9.4.0, with flags `-std=c++98 -Wno-c++0x-compat.
Your example seems simple -- and for the most part, it is. But it leads to some important concepts. First, what you can do is a google on c++ polymorphism. There are a lot of hits, and the first several didn't seem to be wrong. Let's look at some of your code: virtual void DoSomethingAbstract() = 0; This is referred to as a pure virtual function. It means you won't actually make this method, but you're going to reserve a slot for it (and can call it). It means you can not make instances of this class -- it's abstract. If you try to make one, the compiler will complain. Your subclasses MUST provide implementations or they are also abstract and can't be instantiated. void DoSomethingNormal() { std::cout << "Inside Abstract::DoSomethingNormal" << std::endl; DoSomethingAbstract(); } This method is NOT virtual. Your subclass can make its own copy of this method, but then you can get weird results. Let's say you do this: class Inherited: public Abstract { public: void DoSomethingNormal() {...} }; void blah(Abstract &obj) { obj.DoSomethingNormal(); } It won't matter whether you pass in an Abstract or an Inherited -- because you didn't declare the method virtual, and because blah() doesn't know what you're passing in but thinks it's an Abstract, you'll get Abstract's version of DoSomethingNormal(). But if you declare the method virtual, you're saying, "Use whichever version corresponds to the class that actually was instantiated." This is polymorphism at it's most useful, important role.
73,194,326
73,208,035
What wrong with OMP APIs?
Sorry again for my ignorance, I want to run #include <omp.h> for the #pragma omp parallel for command. As it didn't work for me I checked my gcc version and it is 5.1.0, I added the libgomp.a and libgomp.spec files to the mingw lib folder. From codeblocks-> settings-> compiler I added -fopenmp on other compiler options and -lgomp -pthread on other linker options as suggested by any online guide. Result: "undefined reference to GOMP_parallel", "undefined reference to omp_get_num_threads" and "undefined reference to omp_get_thread_num". I'm on windows 10 and running codeblocks for c ++.
GCC 5.1.0 is extremely old! Use a newer GCC (current is 12.1.0) with MinGW-w64 (instead of MinGW, which is also very old). There is a standalone package available for both 32-bit and 64-bit Windows at https://winlibs.com/ and the site also explains how to configure Code::Blocks to use it.
73,194,469
73,194,618
c++20 template parameter of random_access_iterator concept, cannot accept iterator type?
For c++ 20 concept, I had a quick test: #include<iostream> #include<vector> using namespace std; template <random_access_iterator I> void advance(I &iter, int n) { cout << "random_access_iterator" << '\n'; } int main() { vector vec{1, 2, 3}; { vector<int>::iterator itRa = vec.begin(); advance(itRa, 2); } advance(vec.begin(), 3); // compilation error! return 0; } I run clang++ 14 on windows10 and it prints: clang++ .\MyAdvance.cpp -std=c++20 candidate function [with _InIt = std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>, _Diff = int] not viable: expects an lvalue for 1st argument _CONSTEXPR17 void advance(_InIt& _Where, _Diff _Off) { // increment iterat... ^ .\MyAdvance.cpp:6:6: note: candidate function [with I = std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>] not viable: expects an lvalue for 1st argument void advance(I &iter, int n) { ^ 1 error generated. Very strange, what's the difference between: vector<int>::iterator itRa = vec.begin(); advance(itRa, 2); and advance(vec.begin(), 3); // compilation error! Why the 1st version gets compiled and 2nd version doesn't?
begin() returns an iterator by-value, meaning the call expression is a prvalue. You can't pass a prvalue as an argument to a non-const lvalue reference parameter. That is not specific to iterators. It applies to any type, e.g. void f(int&); //... f(1234); // fails because 1234 is a prvalue To allow for prvalues as argument as well you would need to add another overload with I&& instead of I& argument type: template <random_access_iterator I> void advance(I &&iter, int n) { cout << "random_access_iterator" << '\n'; } But that doesn't really make sense. Why should it be allowed to advance an iterator which is then immediately destroyed? If someone writes advance(vec.begin(), 3) then that must be a mistake and it is good that it produces an error since that expression has no effect at all.
73,194,620
73,260,140
How do I get the size of a c-string input in cin?
So, basically I want to write a program in c++ that encrypts text by moving the chars by a random number in the ascii table. But first I need to get a string by the user. When I want to store the c-string in a char array my problem is that I first need to know the size of the string to have the right size in the array. How can I get it without needing to know the future? Thanks in advance!
Below are two simple approaches to solving this problem you have. You can choose one of them based on the needs of your program. Here: #include <iostream> #include <string> #define METHOD_NUM 1 // set this to 1 for the 1st approach // or 2 for the 2nd approach int main( ) { // an arbitrary size, I chose 20 for demo constexpr std::size_t requiredCharsCount { 20 }; #if METHOD_NUM == 1 std::string user_input { }; std::size_t buffSize { }; do { std::getline( std::cin, user_input ); // number of chars in the user input buffSize = user_input.size( ); } while ( buffSize > requiredCharsCount ); #else // + 1 is for the '\0' aka the null terminator constexpr std::size_t buffSize { requiredCharsCount + 1 }; std::string user_input( buffSize, '\0' ); std::cin.getline( user_input.data( ), static_cast<std::streamsize>( user_input.size( ) ) ); #endif std::cout << "The user entered: " << user_input << '\n'; // manipulate the string however you want // just make sure that the indices you're using are // less than buffSize to avoid buffer overrun user_input[0] = '1'; user_input[5] = 'g'; user_input[2] = '@'; } To begin with, I recommend you use the std::string class because it handles all the necessary allocations/deallocations for you and automatically keeps track of that stuff. A C-style array or even a std::array won't have this kind of luxury out of the box. Now, the 1st approach lets the user enter as many characters as they want, and then the program checks the number of characters entered to make sure it's not greater than a predefined number (i.e. requiredCharsCount and I have set it to 20). If it is, then the program will ask for new input. In case you don't want to set a limit for the user you can remove that variable and the do-while loop. Speaking of the 2nd approach, as you can see, it lets the user enter a limited number of characters (again, 20) and won't read more than the limit even if the user's string contains more than that. This approach is more efficient but obviously has the limitation that I just mentioned.
73,194,762
73,195,339
C++ file doesn't recognize function defined in assembly file
I'm trying to learn some assembly code and I'm following a tutorial proposed by a book, I've got a C++ code defined as follows (Ch02_01.cpp) : #include <iostream> using namespace std; extern "C" int IntegerAddSub_(int a, int b, int c, int d); int main() { int a, b, c, d, result; a = 101; b = 34; c = -190; d = 25; result = IntegerAddSub_(a, b, c, d); cout << "result = " << result << n1; return 0; } Knowing that The function IntegerAddSub_ is defined in an assembly file (asm extension) in the folder as follows (Ch02_01.asm) : ; extern "C" int IntegerAddSub_(int a, int b, int c, int d); .code IntegerAddSub_ proc ; Calculate a + b + c -d mov eax, ecx ;eax = a add eax, edx ;eax = a + b add eax, r8d ;eax = a + b + c sub eax, r9d ;eax = a + b + c - d ret ; return result to caller IntegerAddSub_ endp end Error message : Error message : /home/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/222.3345.126/bin/cmake/linux/bin/cmake --build /home/Assembly/cmake-build-debug --target Assembly -j 16 [1/1] Linking CXX executable Assembly FAILED: Assembly : && /usr/bin/c++ -g CMakeFiles/Assembly.dir/Ch02_01.cpp.o -o Assembly && : /usr/bin/ld: CMakeFiles/Assembly.dir/Ch02_01.cpp.o: in function `main': /home/Assembly/Ch02_01.cpp:25: undefined reference to `IntegerAddSub_' collect2: error: ld returned 1 exit status ninja: build stopped: subcommand failed. I think the semantics of the error is simply that the C++ file did not recognize the function defined in the assembler file. According to the exchanges in the comments, i'll add the following informations: I'am using CLION (From Jetbrains) and here is my CMakeLists.txt cmake_minimum_required(VERSION 3.23) project(Assembly) set(CMAKE_CXX_STANDARD 14) set ( SOURCES Ch02_01.asm ) add_executable(Assembly Ch02_01.cpp) And I don't know how to compile that using g++, it never recognizes the function from the ASM file, how can I successfully compile that, please? I am in Ubuntu. Thanks
You need to tell CMake that the project includes nasm code too - or masm if that's what it actually is. Example: cmake_minimum_required(VERSION 3.22) project(Assembly CXX ASM_NASM) # or perhaps it should be ASM_MASM set(CMAKE_CXX_STANDARD 14) add_executable(Assembly Ch02_01.asm Ch02_01.cpp) This makes it at least try to compile the asm file, but for me it fails: [ 33%] Building ASM_NASM object CMakeFiles/Assembly.dir/Ch02_01.asm.o /home/ted/proj/stackoverflow/assembly/Ch02_01.asm:3: warning: label alone on a line without a colon might be in error [-w+label-orphan] /home/ted/proj/stackoverflow/assembly/Ch02_01.asm:4: error: parser: instruction expected /home/ted/proj/stackoverflow/assembly/Ch02_01.asm:12: error: label `IntegerAddSub_' inconsistently redefined /home/ted/proj/stackoverflow/assembly/Ch02_01.asm:4: info: label `IntegerAddSub_' originally defined here /home/ted/proj/stackoverflow/assembly/Ch02_01.asm:12: error: parser: instruction expected /home/ted/proj/stackoverflow/assembly/Ch02_01.asm:13: warning: label alone on a line without a colon might be in error [-w+label-orphan] make[2]: *** [CMakeFiles/Assembly.dir/build.make:76: CMakeFiles/Assembly.dir/Ch02_01.asm.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/Assembly.dir/all] Error 2 make: *** [Makefile:91: all] Error 2
73,195,147
73,196,580
Converting shift-jis encoded file to to utf-8 in c++
I am trying with below code to convert from shift-jis file to utf-8, but when we open the output file it has corrupted characters, looks like something is missed out here, any thoughts? // From file FILE* shiftJisFile = _tfopen(lpszShiftJs, _T("rb")); int nLen = _filelength(fileno(shiftJisFile)); LPSTR lpszBuf = new char[nLen]; fread(lpszBuf, 1, nLen, shiftJisFile); // convert multibyte to wide char int utf16size = ::MultiByteToWideChar(CP_ACP, 0, lpszBuf, -1, 0, 0); LPWSTR pUTF16 = new WCHAR[utf16size]; ::MultiByteToWideChar(CP_ACP, 0, lpszBuf, -1, pUTF16, utf16size); wstring str(pUTF16); // convert wide char to multi byte utf-8 before writing to a file fstream File("filepath", std::ios::out); string result = string(); result.resize(WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, 0, 0)); char* ptr = &result[0]; WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, ptr, result.size(), 0, 0); File << result; File.close();
There are multiple problems. The first problem is that when you are writing the output file, you need to set it to binary for the same reason you need to do so when reading the input. fstream File("filepath", std::ios::out | std::ios::binary); The second problem is that when you are reading the input file, you are only reading the bytes of the input stream and treat them like a string. However, those bytes do not have a terminating null character. If you call MultiByteToWideChar with a -1 length, it infers the input string length from the terminating null character, which is missing in your case. That means both utf16size and the contents of pUTF16 are already wrong. Add it manually after reading the file: int nLen = _filelength(fileno(shiftJisFile)); LPSTR lpszBuf = new char[nLen+1]; fread(lpszBuf, 1, nLen, shiftJisFile); lpszBuf[nLen] = 0; The last problem is that you are using CP_ACP. That means "the current code page". In your question, you were specifically asking how to convert Shift-JIS. The code page Windows uses for its closes equivalent to what is commonly called "Shift-JIS" is 932 (you can look that up on wikipedia for example). So use 932 instead of CP_ACP: int utf16size = ::MultiByteToWideChar(932, 0, lpszBuf, -1, 0, 0); LPWSTR pUTF16 = new WCHAR[utf16size]; ::MultiByteToWideChar(932, 0, lpszBuf, -1, pUTF16, utf16size); Additionally, there is no reason to create wstring str(pUTF16). Just use pUTF16 directly in the WideCharToMultiByte calls. Also, I'm not sure how kosher char *ptr = &result[0] is. I personally would not create a string specifically as a buffer for this. Here is the corrected code. I would personally not write it this way, but I don't want to impose my coding ideology on you, so I made only the changes necessary to fix it: // From file FILE* shiftJisFile = _tfopen(lpszShiftJs, _T("rb")); int nLen = _filelength(fileno(shiftJisFile)); LPSTR lpszBuf = new char[nLen+1]; fread(lpszBuf, 1, nLen, shiftJisFile); lpszBuf[nLen] = 0; // convert multibyte to wide char int utf16size = ::MultiByteToWideChar(932, 0, lpszBuf, -1, 0, 0); LPWSTR pUTF16 = new WCHAR[utf16size]; ::MultiByteToWideChar(932, 0, lpszBuf, -1, pUTF16, utf16size); // convert wide char to multi byte utf-8 before writing to a file fstream File("filepath", std::ios::out | std::ios::binary); string result; result.resize(WideCharToMultiByte(CP_UTF8, 0, pUTF16, -1, NULL, 0, 0, 0)); char *ptr = &result[0]; WideCharToMultiByte(CP_UTF8, 0, pUTF16, -1, ptr, result.size(), 0, 0); File << ptr; File.close(); Also, you have a memory leak -- lpszBuf and pUTF16 are not cleaned up.
73,196,578
73,906,542
Why do some classes of a library need to be included and not others?
Starting Point I have a C++ application (working with VS2019, Window 10 64bit), which heavily relies on the Open3D library. Everything was working perfectly fine, I was using the previous version (0.14.x), which I built from source using CMAKE and Visual Studio 2019. There are some features in the new version (0.15.1) I would like to use. Furthermore, new releases come with a binary packages, so no more building from source. So I backup my current version and download the new binaries and try to link them to my project. Issue To start from a clean slate I remove all the old entries for Open3D and manually insert the new ones. Here are the entries: Project Properties --> C/C++ --> General --> Additional Include Directories: C:\Open3D\include C:\Open3D\include\open3d\3rdparty other stuff Project Properties --> Linker --> Input --> Additional Dependencies: C:\Open3D\lib\Open3D.lib other stuff Building now leads to a whole lot of linker errors all connected to fmt, a 3rd party library used by Open3D it seems. However, these seem to be caused only because, I have two additional includes with respect to Open3D in my precompiled header: // open3d #include "open3d/Open3D.h" #include "open3d/core/Indexer.h" #include "open3d/t/geometry/RaycastingScene.h" If I remove them, all linking errors disappear, but I'm facing yet another issue: Indexer.h is needed for the TensorIterator class, RaycastingScene.h for the RaycastingScene class, both of which I'm using a lot in my project. Question(s) Why do I need an extra import for RaycastingScene but not for example VoxelblockGrid, which is in the same namespace? I have already tried to clone, build and link fmt manually. It looks like I can access the library from my own code successfully, but using Open3D I still get the same linker errors. How am I supposed to use these two classes?
A namespace has nothing to do with including files. It's just a way of grouping and organizing classes, functions, etc. For instance, vector and cout are both in the std namespace. But #include does not give you access to the vector class. Why would it? Vectors have nothing to do with I/O; it would be upsetting if the entire standard namespace had to be imported just so that I could write to standard out. But the files that you include might also include other files in turn. So maybe you've accidentally included VoxelblockGrid transitively, and that's why it works fine. You should assume that it's not imported transitively. The standard practice is to make imports idempotent, which is to say that if you #include the same file twice, the second action is a no-op. So there's no harm in importing the file twice. Even if it has been transitively imported (which you might determine by testing, as you suggest), a future update to the package might no longer need that transitive import due to changes in implementation details, so it might remove it. If you're not also importing it manually in your own code, then your code will break.
73,196,817
73,196,965
Why do lambda functions need to capture [this] pointer explicitly in c++20?
Pre-c++20, the this pointer is captured in [=] implicity. So what's the reason that c++20 decided that user should write [=, this] to capture this pointer explicitly, I mean, without this change, the pre-c++20 code could have any code-smell or potential bug? Any good sample or reason for this language change?
This is explain in P0806, which as the title says, "Deprecate[d] implicit capture of this via [=]" The argument in the paper is that at this point we had [this] (captures the this pointer) and [*this] (captures the object itself), and [&] (captures the object by reference, which is basically capturing the this pointer by value). So it could be ambiguous whether [=] should mean [this] or [*this] and potentially surprising that it means the former (since [=] functions as a reference capture in this context). Thus, you have to write [=, this] or [=, *this], depending on which one of the two you actually intended. As an aside, it's worth nothing that the paper claims: The change does not break otherwise valid C++20 code Yet if you compile with warnings enabled and -Werror, as many people do (and should unless you have a compelling reason not to - which there are), this change of course broke lots of otherwise valid C++20 code.
73,197,114
73,197,864
Entering a folder with a template path - C++ MFC
I am using Visual Studio C++ 2017 Professional and MFC I am working on a project which has a function that collects file paths (like C:/foo1/foo2/foo3.txt) as strings, if a file with that path exists (found using the filesystem library). At first this looks straightforward until I see that the file paths often are simply (for lack of a better word) templates. My program is given a template file path such as this: C:/User/Documents/%A/%B.txt, where %A represents a year (which my program has a range for and iterates through each year, comparing to the template folder) and %B is the month, again iterating. It only gets more complicated, because we now add two more template symbols: * and ?. For example: C:/User/Documents/*_%A_??_*/%B_*.txt. Here, * represents 0 or more characters and ? represents one character. So in the example, a filepath like: C:/User/Documents/smile_2022_A1_/07_ABCDEFGHIJKLMNOP.txt should be found and saved as a string. I am able to separate the file path via tokenization, meaning I already have a function that collects a vector filled with, say, C:, foo1, foo2, foo3.txt. With this I can iterate through the vector either with a loop or recursively enter a folder until I either: reach a deadend (aka the folder or file does not exist) reach the file I want and save its entire path as a string One thought I have come up with is look for _ symbols and separate the folder or file name with those but this gets countered by: if the * or ? contain a _ if the folder or file name simply do not contain _ The solution I am looking for ideally does not utilize regex. However, if that is the only solution (obviously I do not want to recreate regex), please advise me on how I can use it on varying path complexities, as my function should allow for both regular folder paths without template symbols and those with them. The reason I say no regex is because from my understanding, it is a little more strict when it comes to comparing a file. It expects the string to be written in a certain generic but consistent way. However, in my case I cannot expect a user to name their folders in a consistent manner...
Once you replace YOUR env variables (%A, %B, etc.), then FindFirstFile, FindNextFile API calls support wild cards.
73,197,738
73,197,871
C++11 lambda: when do we need to capture [*this] instead of [this]?
For a quick sample we could see: class Foo { std::string s_; int i_; public: Foo(const std::string& s, int i) : s_(s), i_(i) {} void Print() { auto do_print = [this](){ std::cout << s_ << std::endl; std::cout << i_ << std::endl; }; do_print(); } }; Ok, capture [this], so the lambda do_print could use s_ and i_ member of Foo. Capture [this] is enough. But when do we have to capture [*this] instand of [this]? What could be a typical use-case / scenario, any quick samples? Thanks!
You capture *this if you want a copy of the element to be captured. This can be useful if the element may change or go out of scope after the lambda is created, but you want an element that is as it was at the time of creating the lambda. #include <iostream> class Foo { std::string s_; int i_; public: Foo(const std::string& s, int i) : s_(s), i_(i) {} auto get_print() { return [*this] { // copy std::cout << s_ << std::endl; std::cout << i_ << std::endl; }; } }; auto func() { Foo foo("foo", 123); return foo.get_print(); } // foo goes out of scope int main() { func()(); // but the lambda holds a copy, so this is ok, otherwise, UB } Also note that capturing *this requires C++17. A similar program in C++11 could look like this: #include <functional> #include <iostream> class Foo { std::string s_; int i_; public: Foo(const std::string& s, int i) : s_(s), i_(i) {} std::function<void()> get_print() { auto Self = *this; return [Self] { std::cout << Self.s_ << std::endl; std::cout << Self.i_ << std::endl; }; } }; std::function<void()> func() { Foo foo("foo", 123); return foo.get_print(); } int main() { func()(); }
73,198,042
73,198,060
What is the >> operator really doing in this C++ code?
I am following along with Programming: Principles and Practice Using C++, and I am messing with the "get from" (>>) operator from some code in the third chapter. Here is a minimal reproducible version. #include<iostream> using namespace std; int main() { int first_num; int second_num; cout << "Enter a number: "; cin >> first_num; first_num >> second_num; cout << "second_num is now: " << second_num; } The output that I got was the following: Enter a number: 12 second_num is now: 4201200 I had thought that second_num would just get the value of first_num, but clearly not. What has happened here? I am assuming this is defaulting to a bitshift rather than the "get from" operator, but if second_num is not defined, how does the computer know how far to bit shift first_num?
The program has undefined behavior because you bitshift using second_num which is not initialized. first_num >> second_num // right shift `second_num` bits Note that the operator >> you use above is not the same as the overload used to extract a value from std::cin.
73,198,292
73,198,739
Cannot convert argument 1 from 'const char[13] to 'char*'
I am attempting to implement some TWAIN functionality into a QT project. I have opened this code from the provider and compiled it. However when I past the code into my project it wont compile. Basically I have 3 files CommonTWAIN.h, TwainAPP.cpp, and DSMInterface.cpp. In CommonTwain.h I define a constant I believe, called. kTWAIN_DSM_DLL_NAME /* CommonTWAIN.h */ #ifdef TWH_CMP_MSC #ifdef TWH_64BIT #define kTWAIN_DSM_DLL_NAME "TWAINDSM.dll" #else #define kTWAIN_DSM_DLL_NAME "TWAINDSM.dll" #endif // #ifdef TWH_64BIT #elif defined(TWH_CMP_GNU) #define kTWAIN_DSM_DLL_NAME "libtwaindsm.so" #else #error Sorry, we don't recognize this system... #endif In TwainApp.cpp I use that constant in a function call. /* TwainApp.cpp */ LoadDSMLib(kTWAIN_DSM_DIR kTWAIN_DSM_DLL_NAME) That function calls code that is in DSMInterface.cpp defined by /* DSMInterface.h */ bool LoadDSMLib(char* _pszLibName); I get stuck with this error However The code also provides a visual studio solution that I can open and compile. This works as expected with the same code. So I am assuming I just have something configured wrong. This is fairly out of what I am comfortable with but I do think I am missing something simple. So far I have tried adding QMAKE_CXXFLAGS += -permissive to the project file. no luck.
you should be able to cast it away: LoadDSMLib((char*)(kTWAIN_DSM_DIR kTWAIN_DSM_DLL_NAME)) as long as the function isn't trying to modify the string it should be fine.
73,198,350
73,198,640
C++11/14/17 Lambda reference capture [&] doesn't copy [*this]
Refer to this thread: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0806r2.html It says: In other words, one default capture ([&]) captures *this in the way that would be redundant when spelled out, but the other capture ([=]) captures it in the non-redundant way. Which says that pre c++17, the [=] captures this as value, and [&] will capture [*this], which is ambiguous. So I had a quick test, to see if [&] captures [*this] by default. My test code trys to see if [&] defaultly captures *this, then copy ctor should be called, and any change to its value won't affect original object, as it is a copy. #include<iostream> using namespace std; class M{ int mI; public: M() : mI(3) { cout << "ctor\n"; } ~M() { cout << "dtor\n"; } M(const M& m) { if (this != &m) { cout << "copy ctor\n"; mI = m.mI; } } M& operator=(const M& m) { if (this != &m) { cout << "operator =\n"; mI = m.mI; } return *this; } void CaptureByValue() { auto f1 = [=] () { // capture this cout << mI << '\n'; ++(this->mI); }; f1(); cout << mI << '\n'; } void CaptureByReference() { auto f1 = [&] () { // capture *this cout << mI << '\n'; ++(this->mI); }; f1(); cout << mI << '\n'; } }; int main() { { M obj1; obj1.CaptureByValue(); } cout << "------------\n"; { M obj2; obj2.CaptureByReference(); } return 0; } Compile and run it with: clang++ LambdaCapture.cpp -std=c++11 && ./a.out clang++ LambdaCapture.cpp -std=c++14 && ./a.out clang++ LambdaCapture.cpp -std=c++17 && ./a.out All cases print: ctor 3 4 dtor ------------ ctor 3 4 dtor My questions: (1) The result is out of my expectation: no copy ctor is called by CaptureByReference and the value being changed affected original this object. The test code didn't promoted the lambda syntax change in cpp17. (2) I can't even change my capture into [=, *this] or [&, *this] as compiler will say: LambdaCapture.cpp:25:13: error: read-only variable is not assignable ++(this->mI); ^ ~~~~~~~~~~ Very strange, how came out a read-only variable here, as to this pointer. Appreciate your explanations.
[=], [this], [=, this] and [&, this] all captures this by value. That is, it copies the value of the pointer that is this. [&] captures *this by reference. That is, this in the lambda is a pointer to *this outside the lambda. The effect of the above versions with regards to this in the lambda will therefore be the same. [=, *this] copies all elements captured and also makes a copy of *this - not the this pointer. [&, *this] makes a reference to all elements captured but makes a copy of *this. LambdaCapture.cpp:25:13: error: read-only variable is not assignable ++(this->mI); ^ ~~~~~~~~~~ That's because lambdas are const by default. You need to make them mutable in order to be able to change them. auto f1 = [&, *this]() mutable { // made mutable cout << mI << '\n'; ++(this->mI); // now ok };
73,198,589
73,212,112
Concept requires parameter list with template parameters
What I'm trying to do is find a clean way to implement a concept for a callable object that takes in a single parameter of type either int or long. My first attempt was to create a single concept with a secondary template parameter to ensure the parameter type is either int or long. The problem with this approach, as seen in the example below, is that applications of this concept can't infer template parameters. For example, the usages of call() below require that template parameters be explicitly listed out. // https://godbolt.org/z/E519s8Pso // #include <concepts> #include <iostream> // Concept for a callable that can take a single parameter or either int or long. template<typename T, typename P> concept MySpecialFunction = (std::same_as<P, int> || std::same_as<P, long>) && requires(T t, P l) { { t(l) } -> std::same_as<decltype(l)>; }; // T must be callable with 1 parameter that is either int or long! template<typename T, typename P> requires MySpecialFunction<T, P> decltype(auto) call(T t) { return t(2); } // Test int square_int(int num) { return num * num; } long square_long(long num) { return num * num; } int main() { std::cout << call<decltype(square_int), int>(square_int) << std::endl; std::cout << call<decltype(square_long), long>(square_long) << std::endl; return 0; } My second attempt was to explode out the concept to one for int and one for long, then combine them together in a third concept. In this version, the usages of call() below don't require that template parameters be explicitly listed out, but the concept is more verbose. Imagine how something like this would look if there were more than 20 types instead of just 2. // https://godbolt.org/z/hchT11rMx // #include <concepts> #include <iostream> // Concept for a callable that can take a single parameter or either int or long. template<typename T> concept MySpecialFunction1 = requires(T t, int i) { { t(i) } -> std::same_as<decltype(i)>; }; template<typename T> concept MySpecialFunction2 = requires(T t, long l) { { t(l) } -> std::same_as<decltype(l)>; }; template<typename T> concept MySpecialFunction = MySpecialFunction1<T> || MySpecialFunction2<T>; // T must be callable with 1 parameter that is either int or long! template<MySpecialFunction T> decltype(auto) call(T t) { return t(2); } // Test int square_int(int num) { return num * num; } long square_long(long num) { return num * num; } int main() { std::cout << call(square_int) << std::endl; std::cout << call(square_long) << std::endl; return 0; } Is there anyway to have the conciseness / easy of understanding that the first example gives without the compiler losing the ability to infer template parameters as happens in the second example?
After some browsing around, I came across https://stackoverflow.com/a/43526780/1196226 and https://stackoverflow.com/a/22632571/1196226. I was able to utilize these answers to build out a solution that can apply concepts to parameters concisely and without the compiler losing the ability to infer template parameters. // https://godbolt.org/z/nh8nWxhzK // #include <concepts> #include <iostream> template <std::size_t N, typename T0, typename ... Ts> struct typeN { using type = typename typeN<N-1U, Ts...>::type; }; template <typename T0, typename ... Ts> struct typeN<0U, T0, Ts...> { using type = T0; }; template <std::size_t, typename F> struct argN; template <std::size_t N, typename R, typename ... As> struct argN<N, R(*)(As...)> { using type = typename typeN<N, As...>::type; }; // needed for std::integral<> template <std::size_t N, typename R, typename ... As> struct argN<N, R(As...)> { using type = typename typeN<N, As...>::type; }; // needed for std::is_integeral_v<> template <typename F> struct returnType; template <typename R, typename ... As> struct returnType<R(*)(As...)> { using type = R; }; // works for std::integral<> / std::same_as<> template <typename R, typename ... As> struct returnType<R(As...)> { using type = R; }; // needed for std::is_integeral_v<> template<typename Fn> concept MySpecialFunction = (std::same_as<typename argN<0U, Fn>::type, int> || std::same_as<typename argN<0U, Fn>::type, long>) && std::same_as<typename returnType<Fn>::type, typename argN<0U, Fn>::type>; template<MySpecialFunction Fn> decltype(auto) call(Fn fn) { return fn(2); } // Test int square_int(int num) { return num * num; } long square_long(long num) { return num * num; } static_assert( std::is_integral_v<typename argN<0U, decltype(square_int)>::type> ); static_assert( std::is_integral_v<typename returnType<decltype(square_int)>::type> ); static_assert( std::is_integral_v<typename argN<0U, decltype(square_long)>::type> ); static_assert( std::is_integral_v<typename returnType<decltype(square_long)>::type> ); int main() { std::cout << call(square_int) << std::endl; std::cout << call(square_long) << std::endl; return 0; }
73,198,594
73,198,718
How does std::conditional_t<std::is_enum_v<T>, TypeWhenTrue, TypeWhenFalse> determine how to evaluate?
It seems that std::conditional_t<B,T,F> doesn't always return the second value, even when B is false. Here's an example: #include <type_traits> template<class T> using UnderlyingType = std::conditional_t< std::is_enum_v<T>, std::underlying_type_t<T>, T >; template< typename T > constexpr UnderlyingType<T> toUnderlying( T val ) { static_assert( std::is_integral_v<T> || std::is_enum_v<T>, "T must be an enum, or an integral type" ); return val; } enum ExampleEnum { ZERO = 0, ONE, TWO, THREE }; int main() { UnderlyingType<ExampleEnum> underlying = toUnderlying( ZERO ); // compiles and works fine UnderlyingType<ExampleEnum> actual = toUnderlying( 0 ); // error: no matching function for call to 'toUnderlying(int)' } Then later on in the error message I get: <source>:4:7: error: no type named 'type' in 'struct std::underlying_type<int>' 4 | using UnderlyingType = std::conditional_t< std::is_enum_v<T>, std::underlying_type_t<T>, T >; | ^~~~~~~~~~~~~~ Here's the code in godbolt: https://godbolt.org/z/zd5qT94qY Can anyone explain how it is possible that UnderlyingType is evaluating to the first type, even when the template should be taking an int? And possibly a solution? I also tried replacing std::conditional_t with the implementation on https://en.cppreference.com/w/cpp/types/conditional thinking maybe it was some implementation quirk, but it seems to fail as well. UPDATE: Thanks to everyone that answered. I was able to tweak the given answer a bit to allow only specified types. Here's the full code for that for future googlers: #include <type_traits> #include <iostream> #include <iomanip> template <typename T> struct UnderlyingTypeStruct { using type = T; }; template <typename T> requires (!std::is_integral_v<T> && !std::is_enum_v<T>) struct UnderlyingTypeStruct<T> { static_assert( std::is_integral_v<T> || std::is_enum_v<T>, "T must be an enum, or an integral type" ); using type = std::underlying_type_t<T>; }; template <typename T> requires std::is_integral_v<T> struct UnderlyingTypeStruct<T> { using type = T; }; template <typename T> requires std::is_enum_v<T> struct UnderlyingTypeStruct<T> { using type = std::underlying_type_t<T>; }; template<class T> using UnderlyingType = typename UnderlyingTypeStruct<T>::type; template< typename T > constexpr UnderlyingType<T> toUnderlying( T val ) { static_assert( std::is_integral_v<T> || std::is_enum_v<T>, "T must be an enum, or an integral type" ); return val; } enum ExampleEnum { ZERO = 0, ONE, TWO, THREE }; int main() { UnderlyingType<ExampleEnum> underlying = toUnderlying( ZERO ); // ok std::cout << underlying << std::endl; UnderlyingType<ExampleEnum> actual = toUnderlying( 0 ); // okstd::cout << actual << std::endl; UnderlyingType<const char *> myInvalidString = toUnderlying( "hello world" ); // error std::cout << myInvalidString << std::endl; return 0; } And the link to an updated godbolt: https://godbolt.org/z/KbbM3bdMj
std::conditional doesnt even get to choose one of the types, because the first argument isnt a type. std::underlying_type_t<int> just doesnt exist. From cppreference: If T is a complete enumeration (enum) type, provides a member typedef type that names the underlying type of T. Otherwise, the behavior is undefined. (until C++20) Otherwise, if T is not an enumeration type, there is no member type. Otherwise (T is an incomplete enumeration type), the program is ill-formed. (since C++20) Wherher UB or not, there is no std::underlying_type_t<int>. You can use SFINAE such that the specialization that does use std::underlying_type_t<int> gets discarded: #include <type_traits> template <typename T, typename = void> struct UnderlyingType { using type = T; }; template <typename T> struct UnderlyingType<T,std::enable_if_t<std::is_enum_v<T>>> { using type = std::underlying_type_t<T>; }; template<class T> using UnderlyingType_t = typename UnderlyingType<T>::type; template< typename T > constexpr UnderlyingType_t<T> toUnderlying( T val ) { static_assert( std::is_integral_v<T> || std::is_enum_v<T>, "T must be an enum, or an integral type" ); return val; } enum ExampleEnum { ZERO = 0, ONE, TWO, THREE }; int main() { UnderlyingType_t<ExampleEnum> underlying = toUnderlying( ZERO ); // compiles and works fine UnderlyingType_t<ExampleEnum> actual = toUnderlying( 0 ); // error: no matching function for call to 'toUnderlying(int)' }
73,198,653
73,200,002
Creating custom boost serialization output archive
I'm trying to use Boost serialization to serialize objects into a buffer. The objects are large (hundreds of MB) so I don't want to use binary_oarchive to serialize them into an std::stringstream to then copy-them into their final destination. I have a Buffer class which I would like to use instead. The problem is, binary_oarchive takes an std::ostream as parameter, and this class's stream operator is not virtual, so I can't make my Buffer class inherit from it to be used by binary_oarchive. Similarly, I haven't found a way to inherit from binary_oarchive_impl that would let me use something else than std::ostream to serialize into. So I looked into how to create an archive from scratch, here: https://www.boost.org/doc/libs/1_79_0/libs/serialization/doc/archive_reference.html, which I'm putting back here for reference: #include <cstddef> // std::size_t #include <boost/archive/detail/common_oarchive.hpp> ///////////////////////////////////////////////////////////////////////// // class complete_oarchive class complete_oarchive : public boost::archive::detail::common_oarchive<complete_oarchive> { // permit serialization system privileged access to permit // implementation of inline templates for maximum speed. friend class boost::archive::save_access; // member template for saving primitive types. // Specialize for any types/templates that require special treatment template<class T> void save(T & t); public: ////////////////////////////////////////////////////////// // public interface used by programs that use the // serialization library // archives are expected to support this function void save_binary(void *address, std::size_t count); }; But unless I misunderstood something, it looks like by defining my archive this way, I need to overload the save method for every single type I want to store, in particular STL types, which kind of defies the point of using Boost serialization altogether. If I don't define save at all, I'm getting compilation errors indicating that a save function could not be found, in particular for things like std::string and for boost-specific types like boost::archive::version_type. So my question is: how would you make it possible, with Boost serialization, to serialize in binary format into a custom Buffer object, while retaining all the power of Boost (i.e. not having to redefine how every single STL container and boost type is serialized)? This is something I've done pretty easily in the past with the Cereal library, unfortunately I'm stuck with Boost for this particular code base.
Don't create your own archive class. Like the commenter said, use the streambuf interface to your advantage. The upside is that things will work for any of the archive implementations, including binary archives, and perhaps more interestingly things like the EOS Portable Archive implementation. The streambuf interface can be quite flexible. E.g. i've used it to implement hashing/equality operations: Generate operator== using Boost Serialization? In that answer I used Boost Iostreams with its Device concept to make implementing things simpler. Now if your Buffer type (which you might have shown) has an interface that resembles most buffers (i.e. one or more (void*,size) pairs), you could use existing adapters present in Boost IOstreams. E.g. Boost: Re-using/clearing text_iarchive for de-serializing data from Asio:receive() where I show how to use Serialization with a re-usable fixed buffer. Here's the Proof Of Concept: #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/serialization/serialization.hpp> #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/stream.hpp> #include <sstream> namespace bar = boost::archive; namespace bio = boost::iostreams; struct Packet { int i; template <typename Ar> void serialize(Ar& ar, unsigned) { ar & i; } }; namespace Reader { template <typename T> Packet deserialize(T const* data, size_t size) { static_assert(boost::is_pod<T>::value , "T must be POD"); static_assert(boost::is_integral<T>::value, "T must be integral"); static_assert(sizeof(T) == sizeof(char) , "T must be byte-sized"); bio::stream<bio::array_source> stream(bio::array_source(data, size)); bar::text_iarchive ia(stream); Packet result; ia >> result; return result; } template <typename T, size_t N> Packet deserialize(T (&arr)[N]) { return deserialize(arr, N); } template <typename T> Packet deserialize(std::vector<T> const& v) { return deserialize(v.data(), v.size()); } template <typename T, size_t N> Packet deserialize(boost::array<T, N> const& a) { return deserialize(a.data(), a.size()); } } template <typename MutableBuffer> void serialize(Packet const& data, MutableBuffer& buf) { bio::stream<bio::array_sink> s(buf.data(), buf.size()); bar::text_oarchive ar(s); ar << data; } int main() { boost::array<char, 1024> arr; for (int i = 0; i < 100; ++i) { serialize(Packet { i }, arr); Packet roundtrip = Reader::deserialize(arr); assert(roundtrip.i == i); } std::cout << "Done\n"; }
73,198,732
73,198,899
Using V8 Isolate in separate thread
I have a program that uses a v8 isolate to execute javascript code. I would like to spawn a separate thread and execute code in the isolate there too. The thread does not need to run in parallel, I am only using the separate thread so I can cancel it from a signal handler on the main thread. I am currently using pthreads to create the separate thread. Like this: Isolate *isolate = Isolate::New(params); int thread_id; pthread_create(&thread_id, NULL, call, isolate); pthread_join(thread_id, NULL); Where call is the following very basic code to test locking the isolate. void *call(void* vargs) { Isolate *isolate = (thread_args *) vargs; try { v8::Locker lock(isolate); isolate->Enter(); v8::HandleScope handle_scope(isolate); v8::Isolate::Scope scope(isolate); /* use isolate exclusively in here */ isolate->Exit(); } catch catch (int err) { /* log error */ } } The above yields the following stack trace: # # Fatal error in ../src/api/api.h, line 409 # Debug check failed: blocks_.empty(). # # # #FailureMessage Object: 0x16b612c88 ==== C stack trace =============================== 0x0000000115378eb0 v8::base::debug::StackTrace::StackTrace() + 24 0x0000000115354f3c v8::platform::(anonymous namespace)::PrintStackTrace() + 116 0x0000000115362d1c V8_Fatal(char const*, int, char const*, ...) + 268 0x0000000115362740 std::__1::enable_if<((!(std::is_function<std::__1::remove_pointer<char>::type>::value)) && (!(std::is_enum<char>::value))) && (has_output_operator<char, v8::base::CheckMessageStream>::value), std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>::type v8::base::PrintCheckOperand<char>(char) + 0 0x00000001153f69e4 v8::internal::HandleScopeImplementer::Free() + 216 0x000000011567c02c v8::internal::ThreadManager::FreeThreadResources() + 164 0x000000011567c484 v8::Locker::~Locker() + 76 0x0000000115340ca0 call(void*) + 144 0x000000018f2e626c _pthread_start + 148 0x000000018f2e108c thread_start + 8 It looks like the Locker destructor is trying to free resources that haven't been allocated properly. Is there a data structure or method I need to call to ensure these resources a properly allocated when using threads and lockers?
The thread does not need to run in parallel You do not need to lock with v8::Locker lock(isolate); Debug check failed: blocks_.empty(). You don't seem to enter the isolate v8::Isolate::Scope scope(isolate); after the lock. void *call(void* vargs) { Isolate *isolate = (thread_args *) vargs; try { v8::Locker lock(isolate); v8::Isolate::Scope scope(isolate); /* use isolate exclusively in here */ } catch catch (int err) { /* log error */ } return nullptr; } Just tried. Can not reproduce. Works well. void call(v8::Isolate *isolate) { v8::Locker lock(isolate); v8::Isolate::Scope scope(isolate); } int main(int argc, char *argv[]) { auto platform = v8::platform::NewDefaultPlatform(); v8::V8::InitializePlatform(platform.get()); v8::V8::Initialize(); v8::V8::SetFlagsFromCommandLine(&argc, argv, true); auto *allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); v8::Isolate::CreateParams params; params.array_buffer_allocator = allocator; auto *isolate = v8::Isolate::New(params); std::thread thread(call, isolate); thread.join(); isolate->Dispose(); v8::V8::Dispose(); v8::V8::DisposePlatform(); }
73,199,078
73,199,416
Set every nth bit in an integer without for loop
Is there a way to set every nth bit in an integer without using a for loop? For example, if n = 3, then the result should be ...100100100100. This is easy enough with a for loop, but I am curious if this can be done without one. -- For my particular application, I need to do this with a custom 256-bit integer type, that has all the bit operations that a built-in integer has. I'm currently using lazily initialized tables (using for loops) and that is good enough for what I'm doing. This was mostly an exercise in bit-twidling for me, but I couldn't figure out how to do it in a few steps/instructions, and couldn't easily find anything online about this.
… I need to do this with a custom 256-bit integer type. Set r to 256 % n. Set d to ((uint256_t) 1 << n) - 1. Then the binary representation of d is a string of n 1 bits. Set t to UINT256_MAX << r >> r. This removes the top r bits from UINT256_MAX. UINT256_MAX is of course 2256−1. This leaves t as a string of width-r 1 bits, and width-r is some multiple of n, say k*n. Set t to t/d. As a string of k*n 1 bits divided by a string of n 1 bits, this produces a quotient that is 000…0001 repeated k times, where each 000…0001 is n-1 0 bits followed by one 1 bit. Now t is the desired bit pattern except the highest desired bit may be missing if r is not zero. To add this bit, if needed, OR t with t << n. Now t is the desired value. Alternately: Set t to 1. OR t with t << n. OR t with t << 2*n. OR t with t << 4*n. OR t with t << 8*n. OR t with t << 16*n. OR t with t << 32*n. OR t with t << 64*n. OR t with t << 128*n. Those shifts must be defined (shifting by zero would suffice) or suppressed when the shift amount exceeds the integer width, 256 bits.
73,199,739
73,199,839
Is it safe to call exit() from a C++ function to terminate the program?
I've read several questions here on Stack Overflow, Microsoft docs, and cplusplus.com. Some claim that exit() terminates the program normally, just as a return 0; would from main. Others claim that exit() doesn't call all the destructors, etc. So I was wondering if someone could help. edit: As someone asked, I added some blocks of code for which I would like to terminate the program. I use C++20 HKEY newKey; RegOpenKey(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Run)", &newKey); LONG result = RegSetValueEx(newKey, value, 0, REG_SZ, (LPBYTE)filePath, lstrlen(filePath)); RegCloseKey(newKey); if(result != ERROR_SUCCESS){ MessageBox(nullptr, "Could not add to startup", "Error", MB_ICONERROR); exit(1); } int i = line.find(':'); if(i == std::string::npos){ MessageBox(nullptr, "File is incorrectly formatted", "Error", MB_ICONERROR); exit(1); } info.open(infoPath); if(info.fail()){ MessageBox(nullptr, "info.txt did not open", "Error", MB_ICONERROR); exit(1); } I link the posts I've read about this: How to end C++ code https://cplusplus.com/forum/beginner/4589/ How to exit program execution in C++? https://learn.microsoft.com/en-us/cpp/cpp/program-termination?view=msvc-170 https://cplusplus.com/reference/cstdlib/exit/ Thanks in advance
Some claim that exit() terminates the program normally, just as a return 0; would from main std::exit gets called anyway, as part of standard application lifecycle. Quote from CPPReference: Returning from the main function, either by a return statement or by reaching the end of the function performs the normal function termination (calls the destructors of the variables with automatic storage durations) and then executes std::exit, passing the argument of the return statement (or ​0​ if implicit return was used) as exit_code. Others claim that exit() doesn't call all the destructors, etc It's true, but it doesn't cancel the first statement. I.e. if destructors of you classes don't have any side effects that can survive the program, it doesn't matter whether local were destroyed properly or not, since entire memory of your process is freed after program termination. std::exit however calls destructors of objects with static and thread local storage duration: The destructors of objects with thread local storage duration that are associated with the current thread, the destructors of objects with static storage duration, and the functions registered with std::atexit are executed concurrently
73,199,996
73,200,081
How to produce a compilation error if a pointer to a particular object is deleted?
I have a pretty large and verbose codebase and I am trying to find a trick to discover if an object of a particular class has gone through a delete anywhere in the code, preferably by giving me a compilation error if this is the case. I found out that you can overload the delete operator as in: void operator delete(void*) and put this in the private section of the class of interest (so that whenever there is delete on a pointer of that class it will fail compilation). This could be the perfect solution, but alas it emits an error also when I use new on that object. The compiler probably tries to generate the delete operator automatically once a new is present. I don't want to alert on the new CLASS appearances, just the delete. Any other ideas what I can do?
You cannot new an object for which the corresponding operator delete is unusable because construction of the new object or the initializer of the new-expression may throw exceptions and then the new expression must be able to call operator delete to free the memory again. Also note that often the global allocation and deallocation functions are used explicitly, so that your class-specific overload will be ignored. (Specifically with ::new and ::delete instead of new and delete.) Furthermore, a lot of library functions (e.g. allocator-aware containers) do not use allocating new/delete expressions to construct dynamic storage duration objects, but instead allocate untyped memory first and then use placement-news and explicit destructor calls to construct and destroy objects. In this case also often the global allocation/deallocation functions are used explicitly. You can't in general forbid specifically destruction of dynamic storage duration objects of a class type. A class should generally be agnostic to how its lifetime is managed. You can only e.g. delete the destructor, but then almost all uses of the class will be impossible. You can of course also simply make an accessible overload of operator new and operator delete (as well as the array overloads operator new[] and operator delete[]) in the class and log calls to them at runtime by having them e.g. print a message. But as mentioned above this will still not catch a lot of cases, only uses of delete (and delete[]) exactly and it will also log cases of a new expression calling operator delete.
73,200,721
73,200,742
Why don't temporary return types of rvalue functors cause undefined behavior?
I'm new to rvalues and lvalues so please forgive me. Say I have the following code: int&& temp() { return 5400; } int x = temp(); This code compiles just fine with MSVC. When I print out x, it prints 5400. Shouldn't this not be possible, since temp() returns a reference to a destroyed object?
It does cause undefined behavior because you are returning and accessing a reference to an object that is destroyed when the function returns, specifically a temporary int object materialized from the 5400 prvalue in the return statement to bind the reference in the return value to. Whether the return type is a (const) lvalue reference or a rvalue reference does not matter at all. Undefined behavior means that there are no guarantees on the behavior of the program. It seemingly working is one possible outcome when no guarantees are given, but so is any other outcome as well, and none can be relied upon.
73,201,708
73,201,780
std::array's data member is public in a standard library implementation. Why?
I was trying to study standard library implementation of the containers that are part of the C++ standard library. I have Microsoft Visual Studio 2022 on my machine and I could go to the header file definition of std::array class. While I reached the end of the class definition of std::array class, I noticed that the data member is not declared private and above it were all the public member functions, so that make the data member public as well. So to test it, I tried to access it in my std::array object defined in main() and to my surprise I could access it and it printed the proper value in the output too! #include <array> #include <iostream> int main() { std::array<int, 5> staticArray{0,1,2,3,4}; std::cout << staticArray._Elems[1] << std::endl; } Is this allowed?! Anybody can corrupt the data, right?
It is required that std::array have a public member to satisfy the requirement that std::array be an aggregate. An array is an aggregate that can be list-initialized with up to N elements whose types are convertible to T. https://eel.is/c++draft/array#overview-2 It doesn't however specify what the public member should be named, since the only requirement is that it is an aggregate that can be list-initialized. _Elems won't necessarily be compatible with other standard library implementations. With respect to your concern of anyone being able to corrupt the data, anyone can already do that via any of the mutable accessors: data(), operator[], etc
73,201,859
73,205,159
Is it okay to bind the same OpenGL object twice?
I've been writing some code to check if a texture, buffer, or shader is currently bound, and avoid binding it twice if it is. if (lastShaderBound != shaderName) { lastShaderBound = shaderName); glUseProgram(shaderName); } However, there's a potential pitfall; if any of these objects are deleted while bound, OpenGL will implicitly unbind them and allow their GLuint name to be reused. This could result in my "state" of what's bound diverging from OpenGL's, (unless I try to duplicate this behavior, which is fairly complex). I'm wondering if any of this is even necessary? If OpenGL is smart enough to unbind deleted buffers, perhaps it's already doing what I'm trying to do, or perhaps it's not the binding calls that are expensive in the first place? Should I just freely bind things without worrying about the same thing being bound multiple times in a row?
It is technically legal to bind the same shader or texture again. There would be costs associated with either binding overheads or branching. Consider following code QElapsedTimer elapsetimer; elapsetimer.start(); ResourceManager::GetShader("Screen").Use(); // glUseProgram(this->ID); for (int i = 0; i < 1000; i++) { if (ResourceManager::GetShader("Screen").ID != id) ResourceManager::GetShader("Screen").Use(); } qDebug() << elapsetimer.nsecsElapsed(); If i use branching condition than i have about 2000 - 3000 nanoSeconds lesser than binding the shader(very basic shader program) again and again. But this will vary based from shader to shader. On my platform branching is cheaper than binding the shader again , but for this difference i have to have atleast 1000 iterations.
73,201,872
73,201,955
Forward declare instantiated template class
We forward declare class in the api.h files, like the struct Abc in example below, because we only use std::shared_ptr<Abc> This has the advantage we can change the definition of struct Abc without recompiling api.h related files. But this forward declaration doesn't seem to work with instantiated template class, like the commented using Xyz = std::map<int, int> Can anybody explain why it is so? and how we can forward delare something like std::map<int, int>? We have a "work-around": instead of using Xyz = std::map<int, int>, we can do class Xyz : std::map<int, int>, this is the only line we need to change. But it is strongly recommended not derive from STL. So any other suggestions? // lib.h #pragma once #include <memory> #include <map> namespace ABC { struct Abc { int abc; }; using AbcPtr = std::shared_ptr<const Abc>; int impl(const AbcPtr& o); // using Xyz = std::map<int, int>; // using XyzPtr = std::shared_ptr<const Xyz>; // int impl2(const XyzPtr& o); } // ------------ // lib.cpp #include "lib.h" int ABC::impl(const ABC::AbcPtr& o) { return o->abc; } // int ABC::impl2(const ABC::XyzPtr& o) { // return static_cast<int>(o->size()); // } // ------------ // api.h #pragma once #include <memory> namespace ABC { struct Abc; using AbcPtr = std::shared_ptr<const Abc>; // class Xyz; // using XyzPtr = std::shared_ptr<const Xyz>; } namespace Api { int api(const ABC::AbcPtr& o); // int api2(const ABC::XyzPtr& o); } int main(); // ------------ // api.cpp #include "api.h" #include "lib.h" int Api::api(const ABC::AbcPtr& o) { return ABC::impl(o); } // int Api::api2(const ABC::XyzPtr& o) { // return ABC::impl2(o); // } int main() { auto obj = std::make_shared<ABC::Abc>(); obj->abc = 100; int res1 = Api::api(obj); // auto obj2 = std::make_shared<ABC::Xyz>(); // obj2->insert({ 3, 4 }); // int res2 = Api::api2(obj2); return res1; }
But this forward declaration doesn't seem to work with instantiated template class, like the commented using Xyz = std::map<int, int>. Can anybody explain why it is so? Because typedeffing a template does not instantiate the template. Note that when we instantiate a class template for the first time a new type like C<int> is introduced. But since a typedef-name does not introduce a new type(according to the below quoted statement), the statement using P = C<int>; does not instantiate the class template here. Same goes for using Xyz = std::map<int, int>. For example, template<typename T> struct C { }; using P = C<int>; //this does no instantiation //Also note P is an alias for the specialization C<int> and not for the class template named `C` In the above example, using P = C<int>; does not instantiate the class template. This can be seen from dcl.typedef#1 which says: A name declared with the typedef specifier becomes a typedef-name. A typedef-name names the type associated with the identifier ([dcl.decl]) or simple-template-id ([temp.pre]); a typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration ([class.name]) or enum declaration ([dcl.enum]) does. (emphasis mine) Additionally, note that P in the above example is an alias for the specialization C<int> and not for the class template named C. A class template is not a class-type by itself. Only the specialization C<int>(etc) is the class type.
73,202,178
73,202,285
uint8 array passing value fail - only one uint8_t sent
I try to start a array in the header file rs485.h class RS485 { public: uint8_t off[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; void sendmsg(uint8_t* cmd); }; rs485.cpp void RS485::sendmsg(uint8_t* cmd) { //digitalWrite(ENTX_PIN, HIGH); // enable to transmit Serial.println("sending message------------"); Serial2.write(cmd[0]); Serial.println(cmd[0], HEX); Serial2.write(cmd[1]); Serial.println(cmd[1], HEX); Serial2.write(cmd[2]); Serial.println(cmd[2], HEX); Serial2.write(cmd[3]); Serial.println(cmd[3], HEX); Serial2.write(cmd[4]); Serial.println(cmd[4], HEX); Serial2.write(cmd[5]); Serial.println(cmd[5], HEX); Serial2.write(cmd[6]); Serial.println(cmd[6], HEX); Serial2.write(cmd[7]); Serial.println(cmd[7], HEX); Serial.println("--------------------------"); } main.cpp void callback(char *topic, byte *payload, unsigned int length) { '''omit''' if (cmd) { Serial.print("cmd: "); Serial.println(cmd); if (cmd == 700) { rs485.sendmsg(rs485.off); } else if (cmd == 701) { rs485.sendmsg(rs485.on); } '''omit''' } '''omit''' } complier have an error message of "too many initializer values". When I try to use uint8_t off[8] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; it build normally. The problem is when in use this variable in main.cpp and pass it to rs485.cpp only one element off[0] is pass normally. rs485.sendmsg(rs485.off); I have use serial print to check all value it can all print out but the rs485 cannot tx all char. Serial2.write(cmd[0]); Serial.println(cmd[0], HEX); Serial2.write(cmd[1]); Serial.println(cmd[1], HEX); Serial2.write(cmd[2]); Serial.println(cmd[2], HEX); Serial2.write(cmd[3]); Serial.println(cmd[3], HEX); Serial2.write(cmd[4]); Serial.println(cmd[4], HEX); Serial2.write(cmd[5]); Serial.println(cmd[5], HEX); Serial2.write(cmd[6]); Serial.println(cmd[6], HEX); Serial2.write(cmd[7]); Serial.println(cmd[7], HEX); Any result for that? add the wiring gpio26 -->DE+RE gpio21 -->DI gpio25 -->RO
A member variable declared as uint8_t off[] = { ... }; does not become an array with the number of elements in the initializer list, like when you declare a non-member variable. Instead, it then becomes a "flexible array" (a C thing that g++ enables by default in C++) - and flexible arrays can't have initializers, which is why you get "too many initializer values". The correct way is therefore to specify the number of elements: uint8_t off[8] = { ... }; I suggest that you send them all out at once and check how many that are actully written: size_t written = Serial2.write(cmd, 8); Serial.println(written); This should display 8 if the sending code works.
73,202,227
73,202,315
Getting a substr from a std::variant<std::string, std::vector<std::string>>> in C++
So I've got a map with a string key and either a string or vector value. I want to cycle through all the string values (whether they're found in a vector or they can be directly checked) in the map and check if they match a given string (it's irrelevant what the string is). If that string matches completely or partly, I will put the map that the string was found in inside a vector. The issue I'm having is that even though I'm separating strings from vectors using an if conditional the substr function thinks I'm dealing with a std::variant<std::string, std::vector<std::string>>> and therefore gives me an error. The begin functions in the else functions also tell me that variant doesn't have a member called "begin" because of this reason. I'm totally lost, any help would be great. for (std::unordered_map<std::string, std::variant<std::string, std::vector<std::string>>>::iterator h = MyMap.begin(); h != MyMap.end(); h++) { if (typeid(h->second) == typeid(std::string)) { std::string MapValueString = h->second.substr(0, TextCtrlValue.length()); if (MapValueString == TextCtrlValue) { RightSearchResultsVector.insert(RightSearchResultsVector.end(), Maps.begin(), Maps.end()); } } else { for (std::vector<std::string>::iterator f = h->second.begin(); f != h->second.end(); f++) { // Go through vector and find matching/semi matching strings } } }
Here's how to tell what type a variant holds std::string* pstr = std::get_if<std::string>(&h->second); if (pstr != nullptr) { // do stuff with string } else { std::vector<std::string>& vec = std::get<std::vector<std::string>>(h->second); // do stuff with vector } BTW you can simplify this monstrosity for (std::unordered_map<std::string, std::variant<std::string, std::vector<std::string>>>::iterator h = MyMap.begin(); by writing for (auto h = MyMap.begin(); Judicious use of auto can greatly improve the readability of your code.
73,202,376
73,202,630
Segmentation fault in Linked List code, deletion part
I am trying to code for insertion and deletion in linked list. Here is my code for basic insertion and deletion of nodes in a singly linked list. There are no errors in the code, but the output on the terminal shows segmentation fault. Can someone explain why am I getting a segmentation fault? And what changes do i make to remove the fault. I believe the segmentation fault is in the deletion part. Please help. // class is a type of user defined datatype class Node { public: int data; Node* next; //constructor Node(int data) { this -> data = data; this -> next = NULL; } // destructor ~Node() { int value = this -> data; //memory free krr rhe hain if(this -> next != NULL){ delete next; this -> next = NULL; } cout << "memory is free for node with data" << value << endl; } }; void insertAtHead(Node* &head, int data) { // creating new node called temp of type Node Node* temp = new Node(data); temp -> next = head; head = temp; } void insertAtTail(Node* &head, Node* &tail, int data) { // //New node create // Node* temp = new Node(data); // tail -> next = temp; // tail = temp; Node* temp = new Node(data); if (head == nullptr) { // If this is the first node of the list head = temp; } else { // Only when there is already a tail node tail -> next = temp; } tail = temp; } void insertAtPosition(Node* &tail, Node* &head, int position, int data) { // Insert at starting if(position == 1) { insertAtHead(head, data); return; } // Code for inserting in middle Node* temp = head; int cnt = 1; while(cnt < position-1) { temp = temp -> next; cnt++; } // Creating a node for data Node* nodeToInsert = new Node(data); nodeToInsert -> next = temp -> next; temp -> next = nodeToInsert; // Inserting at last position (tail) if(temp -> next == NULL) { insertAtTail(head,tail, data); return; } } void deleteNode(int position, Node* &head) { //deleting first or starting node if(position == 1) { Node* temp = head; head = head -> next; //memory free start node temp -> next = NULL; delete temp; } else { // deleting any middle node Node* curr = head; Node* prev = NULL; int cnt = 1; while(cnt <= position) { prev = curr; curr = curr -> next; cnt++; } prev -> next = curr -> next; curr -> next = NULL; delete curr; } } void print(Node* &head) { Node* temp = head; while(temp != NULL) { cout << temp -> data << " "; temp = temp -> next; } cout << endl; } int main() { Node* head = nullptr; // A list has a head Node* tail = head; // a tail. insertAtHead(head, 10); // pass the head insertAtTail(head, tail, 20); insertAtTail(head, tail, 30); insertAtHead(head, 5); print(head); // Print the whole list cout << "head" << head -> data << endl; cout << "tail" << tail -> data << endl; deleteNode(1, head); print(head); }
The problem is not with the delete function since even commenting it out leads to segmentation fault. The problem is that you are initializing tail = head which is set to nullptr at the start. However, when you insertAtHead, you set the value of head but leave the tail to nullptr. You need to do tail = head when adding the first node (when head == nullptr). Refer below for working code: // Online C++ compiler to run C++ program online #include <iostream> using namespace std; // class is a type of user defined datatype class Node { public: int data; Node* next; //constructor Node(int data) { this -> data = data; this -> next = NULL; } // destructor ~Node() { int value = this -> data; //memory free krr rhe hain if(this -> next != NULL){ delete next; this -> next = NULL; } cout << "memory is free for node with data" << value << endl; } }; void insertAtHead(Node* &head,Node* &tail, int data) { // creating new node called temp of type Node Node* temp = new Node(data); temp -> next = head; if (head == nullptr) tail = temp; //inializing tail head = temp; } void insertAtTail(Node* &head, Node* &tail, int data) { // //New node create // Node* temp = new Node(data); // tail -> next = temp; // tail = temp; Node* temp = new Node(data); if (head == nullptr) { // If this is the first node of the list head = temp; } else { // Only when there is already a tail node tail -> next = temp; } tail = temp; } void insertAtPosition(Node* &tail, Node* &head, int position, int data) { // Insert at starting if(position == 1) { insertAtHead(head,tail, data); return; } // Code for inserting in middle Node* temp = head; int cnt = 1; while(cnt < position-1) { temp = temp -> next; cnt++; } // Creating a node for data Node* nodeToInsert = new Node(data); nodeToInsert -> next = temp -> next; temp -> next = nodeToInsert; // Inserting at last position (tail) if(temp -> next == NULL) { insertAtTail(head,tail, data); return; } } void deleteNode(int position, Node* &head) { //deleting first or starting node if(position == 1) { Node* temp = head; head = head -> next; //memory free start node temp -> next = NULL; delete temp; } else { // deleting any middle node Node* curr = head; Node* prev = NULL; int cnt = 1; while(cnt <= position) { prev = curr; curr = curr -> next; cnt++; } prev -> next = curr -> next; curr -> next = NULL; delete curr; } } void print(Node* &head) { Node* temp = head; while(temp != NULL) { cout << temp -> data << " "; temp = temp -> next; } cout << endl; } int main() { Node* head = nullptr; // A list has a head Node* tail = head; // a tail. insertAtHead(head,tail, 10); // pass the head insertAtTail(head, tail, 20); insertAtTail(head, tail, 30); insertAtHead(head,tail, 5); print(head); // Print the whole list cout << "head" << head -> data << endl; cout << "tail" << tail -> data << endl; deleteNode(1, head); print(head); }
73,202,679
73,202,874
Problem using std::transform with lambdas VS std::transform with std::bind
I am using Clang 14.0.0 and C++20. My goal is to write a general function in order to use std::lerp on a set of elements. So I came up with this: template <typename InputIterator, typename OutputIterator> constexpr OutputIterator lerp_element(InputIterator first, InputIterator last, OutputIterator result, std::iter_value_t<InputIterator> const& a, std::iter_value_t<InputIterator> const& b) { return std::transform(first, last, result, [&a, &b] (auto const &t) { return std::lerp(a, b, t); }); } This works well, however - in an attempt to find a better/alternative way - I thought that maybe a version with std::bind could be more concise and elegant: template <typename InputIterator, typename OutputIterator> constexpr OutputIterator lerp_element(InputIterator first, InputIterator last, OutputIterator result, std::iter_value_t<InputIterator> const& a, std::iter_value_t<InputIterator> const& b) { return std::transform(first, last, result, std::bind(std::lerp(a, b, std::placeholders::_3))); } Lastly I found that std::bind_front allows me to be even less verbose: template <typename InputIterator, typename OutputIterator> constexpr OutputIterator lerp_element(InputIterator first, InputIterator last, OutputIterator result, std::iter_value_t<InputIterator> const& a, std::iter_value_t<InputIterator> const& b) { return std::transform(first, last, result, std::bind_front(std::lerp(a, b))); } The problem is when I try to compile the two latter versions (the ones that use std::bind and std::bind_front), Clang throws this error message at me: Here is the calling code: int main() { std::vector<double> v = { 0.11, 0.53, 0.32, 0.29, 0.77, 0.45, 0.96, 0.0, 1.0 }; std::vector<double> results; lerp_element(std::begin(v), std::end(v), std::back_inserter(results), 10.0, 20.0); for (auto x : results) { std::cout << x << ' '; } return 0; } Godbolt Since I have the version with the lambda working, it seems the issue must be in the way I am using std::bind. I have been reading everything I could find online on how to properly use std::bind and std::placeholders, but obviously I must not be getting it. I understand the problem has to do with std::lerp not receiving consistent argument types in order to resolve the overload, so: why does that happen? how do I modify the std::bind/std::bind_front versions to make it compile and work as expected?
The function argument to std::bind or std::bind_front should not be invoked, but rather the function itself is passed as the first argument: using T = std::iter_value_t<InputIterator>; using F = T (*)(T, T, T) noexcept; return std::transform(first, last, result, std::bind_front<F>(std::lerp, a, b)); Godbolt
73,202,732
73,203,881
Slight acos precision difference between Clang and Visual C++
I have some cross platform code I'm working with. On the Mac it's compiled with Clang, on Windows it's compiled with Visual C++. There is a calculation that can be sensitive, and there was a difference between Mac and Windows that was triggering asserts. It ends up there is a difference between acos results, but I'm not clear why. On both platforms, the input to acos is exactly -1.0f. In Visual C++, acos(-1.0f) is 3.14159274. That's the value of pi as a float, which is what I'd expect. But on macOS: float value = acos(-1.0f); ...evaluates to 3.1415925. Thats just enough of an accuracy difference to trigger issues in the code. acos is an operation that can be imprecise with float - I understand that. And different compilers can have different implementations of acos. I'm just unclear why Clang seems to have issues with such a simple acos result while Visual C++ doesn't. A float is capable of representing 3.14159274, but that's not the result I'm getting. It is possible to get an accurate/Visual C++ aligned value out of Xcode's version of Clang with: float value = (float)acos((double)-1.0f); So I can fix the issue by moving to higher accuracy, and then down casting the value back to float to preserve the same rounding as Windows. I'm just looking for a justification as to why the extra precision is necessary when the VC++ compiler doesn't seem to have a precision issue. It could be differences between the Clang/Xcode/VC++ math libraries as well. I just assumed that acos(-1.0) might be more settled across the compilers. I couldn't find any difference in round modes (even though rounding should not be necessary) and fresh projects in Xcode and Visual Studio show the same difference. Both machines are Intel.
If you look at the binary representation of these floating point values you can see that the mac/clang's value A is the next lowest floating-point number than windows/msvc's value B A 3.14159250 0x40490FDA B 3.14159274 0x40490FDB Whilst B is closest to the true value of π, it is actually greater than π as @njuffa points out in their comment. Reading the specification, it looks like acosf is supposed to return a value in the closed range [0,π]. Technically A meets this criteria whilst B doesn't. In summary - A is the closest value to, but less than, π B is the closest value to π The difference in these may be as a result of a deliberate decision of the respective standard library implementors. I'd also observe that both values are true inverses of cosf as both cosf(A) and cosf(B) equal -1.0f. Generally speaking, though, it is unwise to rely on exact bit-level accuracy with any floating point calculations. If you are not already aware of it, the document What Every Computer Scientist Should Know About Floating-Point Arithmetic explains why. Edit: I was curious and found what might be relevant Apple source code here. Return value: ... Otherwise: ... Returns a value in [0, pi] (C 7.12.4.1 3). Note that this prohibits returning a correctly rounded value for acosf(-1), since pi rounded to a float lies outside that interval.
73,202,761
73,202,784
What does this do in C++? []() {}()
I am unit testing for code coverage, making sure that every possible code path is executed by a unit test. I find that a switch/case element which merely contains a break can be breakpointed, but that the break is never hit, control just jumps to the end of the switch, presumably because of compiler optimization. A colleague is arguing that that I have not adequately unit test that path. So, I searched and found an S.O question - which I can not longer find - about C++ code that does nothing. The only answer that didn't also get optimized away of generate compiler or static code analysis errors was []() {}(). This works, insomuch as a breakpoint on it will be hit. Problem solved, I guess, but what does that actually do?
This is an empty lambda that gets executed and does nothing. Usually to set a breakpoint in debugging, at the end of a function or another code block. [] () { } () ^^^ ------------------- no captures ^^^ ---------------- no parameters ^^^------------ function body ^^ ------- call operator (operator()) with no arguments. Compare this with a Lambda that actually does something: int x = 5; auto lambda = [&x](int i){ x=x*i; }; lambda(2); std::cout << "x is now: " << x << "\n"; // prints x=10 If a function gets optimised out or not is compiler specific. I composed a small example on godbolt #include <iostream> inline void nothing(){} int main(){ int x = 5; [](){}(); nothing(); std::cout << x+3 << "\n"; } Depending on the optimisation -O0 or -O1, ... and if the nothing() function is marked inline or not, you can see a difference in the assembly. In gcc12.1 and -O1 the empty lambda is optimised out as well as the call to nothing(). If you remove the inline keyword, even the nothing() declaration disappears as well
73,202,795
73,425,351
vector<int> pushback causes runtime error?
For some reason, if I don't have a certain line commented out my code doesn't work. Here are my three files: Maze.hpp, Kruskal.cpp, main.cpp, #include <vector> #include <utility> #include <cstdlib> using namespace std; class KruskalGenerator{ private: void GetNextDirection(); public: }; #include "Maze.hpp" void KruskalGenerator::GetNextDirection(){ vector<int> pIndex = {}; pIndex.push_back(1); // <----- This for some goddamn reason causes runtime error } #include <iostream> #include "Maze.hpp" using namespace std; int main(){ //Maze picture = Maze{10}; KruskalGenerator kSolver; //kSolver.Reset(picture); cout << "X\n"; return 0; } If I don't compile the code with that line commented out pIndex.push_back(i) in Generators/Kruskal.cpp then running the executable does not return "X" as it should. Otherwise, if I do comment it out then it prints X just fine. Why could compiling that uncommented code specifically cause a run time error? I was originally working with a vector of pairs when I found this issue, but I realized something was horribly wrong when even a vector of integers wasn't behaving. What am I doing wrong? I've tried forcing the version with --std=c++17, and even different warning flags. Nothing. Not even a "Segmentation fault" response from running the executable, even though that error is the only one I know which is similar to this type of empty response. Edit: Running it in gdb gives me a During startup program exited with code 0xc0000139 error code. It could be related to an environment variable issue, but I've raised MinGw bin to the highest in my path, so I'm not sure if it's that. I'm on GCC version 12.1.0 if that helps anyone. Also of note is that my other projects compile and run fine, except for this one.
The issue was that there were two DLLs on my machine. One was old and outdated, the other new and updated. Windows was defaulting to the old one, so I overwrote that DLL with the new one. A better solution was most likely to simply delete the old DLL that way it wouldn't conflict, but since for some reason the old one was packaged with Git and I rely on Git a lot I didn't want to break anything.