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
70,515,157
70,519,392
Trouble Creating a GLFW OpenGL Window in C++
Here is the current bit of code I'm working on: int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", NULL, NULL); if (nullptr == window) { std::cout << "Failed to create GLFW Window" << std::endl; glfwTerminate(); return EXIT_FAILURE; } At runtime, the window is not created, and I get the failure message. I am not understanding why window is a nullptr, when I defined it. Am I missing something?
According to the GLFW documentation, the value for the GLFW_OPENGL_PROFILE window hint must be GLFW_OPENGL_ANY_PROFILE if the requested OpenGL context version is less than 3.2 (and GLFW has a platform-independent check built-in whenever glfwCreateWindow is called). See: https://www.glfw.org/docs/3.3/window_guide.html#GLFW_OPENGL_PROFILE_hint GLFW_OPENGL_PROFILE specifies which OpenGL profile to create the context for. Possible values are one of GLFW_OPENGL_CORE_PROFILE or GLFW_OPENGL_COMPAT_PROFILE, or GLFW_OPENGL_ANY_PROFILE to not request a specific profile. If requesting an OpenGL version below 3.2, GLFW_OPENGL_ANY_PROFILE must be used. If OpenGL ES is requested, this hint is ignored. In particular the part: "If requesting an OpenGL version below 3.2, GLFW_OPENGL_ANY_PROFILE must be used." You will get a GLFW error in your case. In particular, exactly this one - regardless of the platform/OS, which you would see if you had setup a GLFW error handler function via glfwSetErrorCallback().
70,515,349
70,516,422
glm::rotate() changes the rotation axis, but why?
Easy test code glm::mat4 m = glm::rotate(glm::mat4(1.0f), 0.78f, glm::vec3(0,1,0)); while (true) { glm::vec3 axis = glm::normalize(glm::vec3(m[0])); // right vector PRINT_VEC("{0:.3f} {1:.3f} {2:.3f}", axis.x, axis.y, axis.z); m = glm::rotate(m, glm::radians(5.f), axis); // 5 degrees each iteration } So, assume that I have a model matrix rotated from identity by 0.78 radians around the y axis, then every frame I'm going to rotate around the local right vector, which is the first column of the matrix (assume a right-handed system). Since the right vector is the axis around which I rotate, I expect it to be constant, but that's not true. I don't understand why glm::rotate also changes the rotation axis. The output changes quite drastically so I don't think it's floating point precision errors. 0.657 -0.424 -0.623 0.643 -0.482 -0.595 0.626 -0.539 -0.563 0.608 -0.593 -0.527 0.588 -0.646 -0.487 0.566 -0.696 -0.442 0.543 -0.742 -0.393 0.518 -0.785 -0.339 0.491 -0.824 -0.281 0.464 -0.858 -0.219 0.435 -0.887 -0.153 0.406 -0.910 -0.084 0.377 -0.926 -0.012 0.347 -0.936 0.063 0.319 -0.937 0.140 0.292 -0.931 0.218 0.267 -0.917 0.296 0.244 -0.895 0.374 0.224 -0.864 0.450 0.208 -0.826 0.524
m[0] isn't truly the 'local right vector'. The local right vector is vec3(1,0,0), which is what you should use to achieve the desired rotation: glm::mat4 m = glm::rotate(glm::mat4(1.0f), 0.78f, glm::vec3(0,1,0)); while (true) { glm::vec3 axis = glm::normalize(glm::vec3(m[0])); // right vector PRINT_VEC("{0:.3f} {1:.3f} {2:.3f}", axis.x, axis.y, axis.z); m = glm::rotate(m, glm::radians(5.f), glm::vec3(1,0,0)); // 5 degrees each iteration } Prints: 0.711 0.000 -0.703 0.711 0.000 -0.703 0.711 0.000 -0.703 ... What your code does instead, is to transform the vector vec3(1,0,0) into the world coordinate system, and then applies a local rotation around that numeric vector. Note that GLM transformation functions, like glm::rotate, apply the transformation on the right; i.e. m = m * glm::rotate(glm::mat4(1.0f), glm::radians(5.f), axis); Therefore the space rotation is applied (local) ends up different from the space you calculated your vector in (world). Consequently, when interpreted in the local coordinate system, axis is just some arbitrary vector. Alternatively, you can use the world vector axis to rotate in the world space around that same vector; you do that by multiplying on the left: m = glm::rotate(glm::mat4(1.0f), glm::radians(5.f), axis) * m; which gives the same result as the first version above. EDIT: Column vectors rendered using the correct vs incorrect code:
70,515,424
70,515,823
Can't push element into priority queue, when element type is std::pair<int, const std::string &>
I want to order some strings by their indexes. And I don't want to use two different types of priority queue. #include <string> #include <queue> #include <utility> int main() { const std::string &a = "hello"; std::pair<int, const std::string &> p = std::make_pair(1, a); std::priority_queue<std::pair<int, const std::string &>> pq; pq.push(p); return 0; } So how to let it work? Can't be compiled by clang or gcc. clang++ -o /cplayground/cplayground /cplayground/code.cpp -I/cplayground/include -L/cplayground/lib -std=c++14 -O0 -Wall -no-pie -lm -pthread In file included from /cplayground/code.cpp:5: In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/queue:62: /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_heap.h:141:29: error: object of type 'std::pair<int, const std::__cxx11::basic_string<char> &>' cannot be assigned because its copy assignment operator is implicitly deleted *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __parent)); ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_heap.h:215:12: note: in instantiation of function template specialization 'std::__push_heap<__gnu_cxx::__normal_iterator<std::pair<int, const std::__cxx11::basic_string<char> &> *, std::vector<std::pair<int, const std::__cxx11::basic_string<char> &>, std::allocator<std::pair<int, const std::__cxx11::basic_string<char> &> > > >, long, std::pair<int, const std::__cxx11::basic_string<char> &>, __gnu_cxx::__ops::_Iter_comp_val<std::less<std::pair<int, const std::__cxx11::basic_string<char> &> > > >' requested here std::__push_heap(__first, _DistanceType((__last - __first) - 1), ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_queue.h:643:7: note: in instantiation of function template specialization 'std::push_heap<__gnu_cxx::__normal_iterator<std::pair<int, const std::__cxx11::basic_string<char> &> *, std::vector<std::pair<int, const std::__cxx11::basic_string<char> &>, std::allocator<std::pair<int, const std::__cxx11::basic_string<char> &> > > >, std::less<std::pair<int, const std::__cxx11::basic_string<char> &> > >' requested here std::push_heap(c.begin(), c.end(), comp); ^ /cplayground/code.cpp:14:8: note: in instantiation of member function 'std::priority_queue<std::pair<int, const std::__cxx11::basic_string<char> &>, std::vector<std::pair<int, const std::__cxx11::basic_string<char> &>, std::allocator<std::pair<int, const std::__cxx11::basic_string<char> &> > >, std::less<std::pair<int, const std::__cxx11::basic_string<char> &> > >::push' requested here pq.push(p); ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_pair.h:315:17: note: copy assignment operator is implicitly deleted because 'pair<int, const std::__cxx11::basic_string<char> &>' has a user-declared move constructor constexpr pair(pair&&) = default; ///< Move constructor ^ In file included from /cplayground/code.cpp:5: In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/queue:62: /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_heap.h:145:32: error: object of type 'std::pair<int, const std::__cxx11::basic_string<char> &>' cannot be assigned because its copy assignment operator is implicitly deleted *(__first + __holeIndex) = _GLIBCXX_MOVE(__value); ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_pair.h:315:17: note: copy assignment operator is implicitly deleted because 'pair<int, const std::__cxx11::basic_string<char> &>' has a user-declared move constructor constexpr pair(pair&&) = default; ///< Move constructor ^ 2 errors generated.
This const std::string& a = "hello"; std::pair<int, const std::string&> p = std::make_pair(1, a); This will result in a dangling reference, because the type returned by make_pair is pair<int, string>, but you use pair<int, const string&> to receive it, which makes const string& bind the string in the newly created pair<int, string>, and it will be destroyed after make_pair ends. In addition, because your pair contains a reference type, the copy assignment operator of the pair is implicitly deleted, and pq.push(p) will call this deleted operator to copy a pair, which is forbidden. You can use std::reference_wrapper to wrap the const string&: #include <string> #include <queue> #include <utility> using ref_pair = std::pair<int, std::reference_wrapper<const std::string>>; int main() { const std::string& a = "hello"; ref_pair p = {1, a}; auto cmp = [](ref_pair x, ref_pair y) { return x.first == y.first ? x.second.get() < y.second.get() : x.first < y.first; }; std::priority_queue<ref_pair, std::vector<ref_pair>, decltype(cmp)> pq(cmp); pq.push(p); } Demo.
70,516,508
70,516,645
casting int32_t to std::complex<float>
I receive some data over a wire protocol. One of the packets I receive has some int32_t values that represent complex numbers. i.e. 10 complex numbers come in the form of 20 int32_t values (real,imag). I need to convert the int32_t's to float's and copy these values into a vector<std::complex<float>>. I am not sure of the preferred method to do this. this works but sure is ugly and highly questionable. This is a sudo realtime system and I need as fast an operation as possible. float coefBuffer[20]; std::transform(packet.coef,packet.coef+20,coefBuffer, [](int32_t x) { return (float)x;}); std::memcpy(complexFloatVector.data(),coefBuffer,sizeof(float)*20); I tried many kinds of casting and could not come up with a better solution. Any suggestions appreciated.
Don't overthink it complexFloatVector.resize(10); for (size_t i = 0; i < 10; i++) { complexFloatVector[i] = std::complex<float>((float)(packet.coef[i * 2]), (float)(packet.coef[i * 2 + 1])); } I'm assuming complexFloatVector is a std::vector<std::complex<float>> type and packet.coef is an array of 20 integers.
70,516,557
70,516,599
C++ reference wrapper as function argument
From my understanding, reference wrapper is just a wrapper on reference, nothing too special about it. But why it is treated as the reference itself (rather than the wrapper) inside the function when passed as a function argument? #include <iostream> #include <functional> using namespace std; void f(int& x){ cout<<"f on int called"<<endl; } void f(reference_wrapper<int>& x){ cout<<"f on wrapper called"<<endl; } int main(){ int x = 10; f(ref(x)); // f on int called, why? reference_wrapper<int> z = ref(x); f(z); // f on wrapper called, this makes sense though } why does ref(x) treated as x itself inside function call? I come to this problem because I was trying to understand the use of ref() when passing data among different threads. I think the ref() is necessary so any function argument with '&' need not be rewritten to avoid threads interfere with each other. But why the threads can treat ref(x) as x without using x.get()?
f(ref(x)); // f on int called, why? Because std::reference_wrapper has a conversion operator to the stored reference; ref(x) returns an std::reference_wrapper, which could be converted to int& implicitly. void f(reference_wrapper<int>& x) takes lvalue-reference to non-const, std::ref returns by-value, i.e. what it returns is an rvalue which can't be bound to lvalue-reference to non-const. Then f(ref(x)); calls the 1st overloaded f instead of the 2nd one. If you change it to void f(reference_wrapper<int> x) or void f(const reference_wrapper<int>& x) then it'll be called. LIVE
70,516,584
70,516,840
Is erasing a range more efficient than erasing each of the elements separately?
If you have defined a range of elements you want to "erase", is it more efficient to call vector::erase(iterator) for every element in the range, or to call vector::erase(iterator,iterator once?
Of course it depends on circumstance but you can have a feeling by running some specifics. Let's see one example: #include <iostream> #include <vector> uint64_t now() { return __builtin_ia32_rdtsc(); } template< typename T > void erase1( std::vector<T>& vec ) { while ( !vec.empty() ) { vec.erase( vec.begin() ); } } template< typename T > void erase2( std::vector<T>& vec ) { while ( !vec.empty() ) { vec.erase( vec.begin()+vec.size()-1 ); } } template< typename T > void erase3( std::vector<T>& vec ) { vec.erase( vec.begin(), vec.end() ); } int main() { for ( unsigned N = 1; N< (1<<20); N*=2 ) { std::vector<int> vec; vec.resize( N ); for ( uint32_t j=0; j<N; ++j ) vec[j] = N; uint64_t t0 = now(); erase1( vec ); uint64_t t1 = now(); vec.resize( N ); for ( uint32_t j=0; j<N; ++j ) vec[j] = N; uint64_t t2 = now(); erase2( vec ); uint64_t t3 = now(); vec.resize( N ); for ( uint32_t j=0; j<N; ++j ) vec[j] = N; uint64_t t4 = now(); erase3( vec ); uint64_t t5 = now(); std::cout << (t1-t0) << " " << (t3-t2) << " " << (t5-t4) << std::endl; } } erase1() will erase one by one from the front. erase2() will erase item by item from the back and erase3() will erase on the entire range. The results of this run are: Program stdout 54 46 22 1144 66 24 230 116 22 362 74 24 596 108 24 924 128 22 2906 230 38 4622 270 24 11648 542 22 31764 960 34 94078 1876 24 313308 3874 32 1089342 7470 34 4967132 14792 34 25695930 14720 24 134255144 61492 24 585366944 122838 34 3320946224 115778 22 17386215680 484930 24 Results are in cycles. You can see that erasing from the front is very costly. From the back is way faster but still apparently O(N). And erasing the range is almost instantaneous and O(1).
70,517,333
70,583,289
How to store Key / Value Pair wxDataViewListCtrl without using wxDataViewModel
I have below sample data available in database SrNo | String 1 | Data1 2 | Data2 3 | Data3 4 | Data2 5 | Data1 String column value can be duplicate. User can also filter data displayed in wxDataViewListCtrl using wxSearchCtrl, so ID number displayed inside wxDataViewListCtrl might change based on filter used by user. https://docs.wxwidgets.org/3.0/classwx_data_view_list_ctrl.html Using example shown above link, inserting data from database into listctrl with a while loop. sample code is below. wxDataViewListCtrl *listctrl = new wxDataViewListCtrl( parent, wxID_ANY ); listctrl->AppendTextColumn( "String Data" ); wxVector<wxVariant> data; data.push_back( wxVariant("Data1") ); listctrl->AppendItem( data ); data.clear(); data.push_back( wxVariant("Data2") ); listctrl->AppendItem( data ); How to get SrNo of Selected row? in below code? Do I need to use wxDataViewModel? I didn't find any examples for the same if(listctrl->GetSelectedRow() != wxNOT_FOUND){ wxLogMessage("Select Item Id: %i -",listctrl->RowToItem(listctrl->GetSelectedRow()).GetID() ); }else{ wxMessageBox("Please Select row", strappName,wxICON_INFORMATION|wxCLOSE); } Tried below sample code but it crashes with segmentation fault. Looking for sample code listctrl->SetItemData(wxDataViewItem (reinterpret_cast<void *>(iRowCount)),std::stoi(SrNo))
Use the "wxUIntPtr" parameter in AppendItem/InsertItem etc... to store your internal index. wxVector<wxVariant> data; data.push_back( wxVariant("Data1") ); listctrl->AppendItem( data, wxUIntPtr(1) ); // <<HERE, your index 1>> data.clear(); data.push_back( wxVariant("Data2") ); listctrl->AppendItem( data, wxUIntPtr(2) ); // <<and HERE, your index 2>> Then use RowToItem(int row) to get a wxDataViewItem for your row and use GetItemData to get the wxUIntPtr and convert that back to your id. For example // Get the wxDataViewItem for "GetSelectedRow" (Warning, not tested for wxID_NOTFOUND) auto idx=listctrl->RowToItem(GetSelectedRow()); // Now get the item data, which was added as 2nd parameter for Append/InsertItem auto your_index_asUIntPtr=listctrl->GetItemData(idx); // and in your case convert it back to an int int your_index_as_it=(int)your_index_asUIntPtr; That should to the trick. In general, most wxWidgets list functions have an additional void* or wxUIntPtr that you can use to add your own data to a specific entry in the list. You have to either cast this parameter to your own primitive datatype (int, long etc...). Or you can use this pointer to point to an actual complex data type (pointer casts are needed still), but the list controls will never take ownership of the pointer. So something like this listctrl->InsertItem(something, (wxUIntPtr)new std::string("Hey, additional string") will result in a memory leak.
70,517,433
70,517,479
Why does this code have different outputs if pointers are incremented differently c++
#include <iostream> using namespace std; int main() { int num=10; int *ptr=NULL; ptr=&num; num=(*ptr)++; //it should increase to 11 num=(*ptr)++; //it should increase to 12 but im getting 10 //if i dont initialize num and just use (*ptr)++ it gives me 11 cout<<num<<endl; return 0; } I want to know why is this happening and why am I getting 10 as output.
(*ptr)++ increases num to 11 but returns its previous value (10), because the ++ is postfix. So with num = (*ptr)++, you are temporarily increasing num to 11, but then (re)assigning it with 10.
70,517,692
70,650,632
C++ Apache Orc is not filtering data correctly
I am posting a simple c++ Apache orc file reading program which: Read data from ORC file. Filter data based on the given string. Sample Code: #include <iostream> #include <list> #include <memory> #include <chrono> // Orc specific headers. #include <orc/Reader.hh> #include <orc/ColumnPrinter.hh> #include <orc/Exceptions.hh> #include <orc/OrcFile.hh> int main(int argc, char const *argv[]) { auto begin = std::chrono::steady_clock::now(); orc::RowReaderOptions m_RowReaderOpts; orc::ReaderOptions m_ReaderOpts; std::unique_ptr<orc::Reader> m_Reader; std::unique_ptr<orc::RowReader> m_RowReader; auto builder = orc::SearchArgumentFactory::newBuilder(); std::string required_symbol("FILTERME"); /// THIS LINE SHOULD FILTER DATA BASED ON COLUMNS. /// INSTEAD OF FILTERING IT TRAVERSE EACH ROW OF ORC FILE. builder->equals("column_name", orc::PredicateDataType::STRING, orc::Literal(required_symbol.c_str(), required_symbol.size())); std::string file_path("/orc/file/path.orc"); m_Reader = orc::createReader(orc::readFile(file_path.c_str()), m_ReaderOpts); m_RowReader = m_Reader->createRowReader(m_RowReaderOpts); m_RowReaderOpts.searchArgument(builder->build()); auto batch = m_RowReader->createRowBatch(5000); try { std::cout << builder->build()->toString() << std::endl; while(m_RowReader->next(*batch)) { const auto &struct_batch = dynamic_cast<const orc::StructVectorBatch&>(*batch.get()); /** DO CALCULATIONS */ } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } auto end = std::chrono::steady_clock::now(); std::cout << "Total Time taken to read ORC file: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " ms.\n"; return 0; } I tried searching on google for almost a week and tried to convert every possible java program into c++ to make my code works. I tried to use the example in the STACKOVERFLOW LINK which has a similar issue but didn't work for me. **Question:** 1. Am I wiring filtering code correctly. If yes then why it is not filtering data based on the given string. 2. Where can I find the C++ or 'relevant Java code' for row-level or strip-level filter.
Finally after trying multiple scenarios, I have resolved the above issue with ORC data filtering. It was because of using the incorrect column number, I am not sure why there is a difference between the column id of the columns to fetch and columns to filter. In above example I tried to filter data with column name and issue of filtering ORC with column name is still there. But unfortulately it is working fine with column number. New Code: #include <iostream> #include <list> #include <memory> #include <chrono> // Orc specific headers. #include <orc/Reader.hh> #include <orc/ColumnPrinter.hh> #include <orc/Exceptions.hh> #include <orc/OrcFile.hh> int main(int argc, char const *argv[]) { auto begin = std::chrono::steady_clock::now(); orc::RowReaderOptions m_RowReaderOpts; orc::ReaderOptions m_ReaderOpts; std::unique_ptr<orc::Reader> m_Reader; std::unique_ptr<orc::RowReader> m_RowReader; auto builder = orc::SearchArgumentFactory::newBuilder(); std::string required_symbol("FILTERME"); // <-- HERE COLUMN IDS ARE STARTING FROM 0-N. --> std::list<uint64_t> cols = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; m_RowReaderOpts.include(cols); int column_id = 7; // IN cols ABOVE, THIS COLUMN_ID 7 IS ACTUALLY 6. WHICH MEANS COLUMN_ID TO FILTER COLUMN IS +1 OF COLUMN ID PROVIDED IN DATA FETCH. builder->equals(column_id, orc::PredicateDataType::STRING, orc::Literal(required_symbol.c_str(), required_symbol.size())); std::string file_path("/orc/file/path.orc"); m_Reader = orc::createReader(orc::readFile(file_path.c_str()), m_ReaderOpts); m_RowReader = m_Reader->createRowReader(m_RowReaderOpts); m_RowReaderOpts.searchArgument(builder->build()); auto batch = m_RowReader->createRowBatch(5000); try { std::cout << builder->build()->toString() << std::endl; while(m_RowReader->next(*batch)) { const auto &struct_batch = dynamic_cast<const orc::StructVectorBatch&>(*batch.get()); /** DO CALCULATIONS */ } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } auto end = std::chrono::steady_clock::now(); std::cout << "Total Time taken to read ORC file: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << " ms.\n"; return 0; } As per my understanding while resolving above issue is, column ids for fetching data starts from 0-N and for filtering it is 1-N. This is why you should provide 1, when you require to filter data at column 0.
70,517,866
70,517,997
Bit shifting a floating-point
I am working on a project of converting any real number into fixed point. For example, the code below: float ff = 8.125f; std::cout << std::bitset<32>(ff) << std::endl; //print binary fotmat Output: 00000000000000000000000000001000 Only the integer part is printed out. When I do: float ff = 8.125f; int va = ff * (1 << 8); //8bits shift left std::cout << std::bitset<32>(va) << std::endl; //print binary fotmat The output is: 00000000000000000000100000100000 Where the fraction part is printed out too. I don't understand why.
Only the integer part is printed out. Well, of course, because that's all you've given the bitset: there is no std::bitset constructor that takes a float argument, so your ff is being converted to an unsigned long long, which will lose the fractional part (as any conversion of a floating-point type to an integral type will). Turning on compiler warnings will alert you to this; for example, for your first code snippet, the MSVC compiler shows: warning C4244: 'argument': conversion from 'float' to 'unsigned __int64', possible loss of data In your second example, you are multiplying the float value by 256 and converting to the integer value, 2080 - which is what gets passed to the bitset. If you want the full bitwise representation of your float variable in the bitset, you need to first copy that data into an unsigned long long variable and pass that to the constructor: unsigned long long ffdata = 0; std::memcpy(&ffdata, &ff, sizeof(ff)); std::cout << std::bitset<32>(ffdata) << std::endl; Output: 01000001000000100000000000000000
70,517,952
70,518,420
How flutter determine written code is for android or ios?
Could anyone please explain behind the scenes of the flutter determines written code is for android or ios.
Dart is ahead-of-time (AOT) compiled into fast native X86 or ARM code for Android and iOS devices. Flutter can also call out to Android and use Android features only available in Java (same with iOS). Flutter is written in DART so we can't call that it compiles but DART does and it's rendering engine does. Flutter Framework provides all widgets and packages whereas Flutter SDK allows you to build apps for android and IOS The engine’s C/C++code is compiled with Android’s NDK or iOS’ LLVM. Both pieces are wrapped in a “runner” Android and iOS project, resulting in an apk or ipa file respectively. On app launch, any rendering, input, or event is delegated to the compiled Flutter engine and app code. I thought images would be much clear instead of writing many things. More of these: https://docs.flutter.dev/resources/faq#run-android
70,518,554
70,519,302
How to invoke method which using c++ operate
I wante to invoke method operator id () const below ,which writing by C++ opreate struct CKBoxedValue { CKBoxedValue() noexcept : __actual(nil) {}; // Could replace this with !CK::is_objc_class<T> CKBoxedValue(bool v) noexcept : __actual(@(v)) {}; CKBoxedValue(int8_t v) noexcept : __actual(@(v)) {}; CKBoxedValue(uint8_t v) noexcept : __actual(@(v)) {}; CKBoxedValue(int16_t v) noexcept : __actual(@(v)) {}; CKBoxedValue(uint16_t v) noexcept : __actual(@(v)) {}; CKBoxedValue(int32_t v) noexcept : __actual(@(v)) {}; CKBoxedValue(uint32_t v) noexcept : __actual(@(v)) {}; CKBoxedValue(int64_t v) noexcept : __actual(@(v)) {}; CKBoxedValue(uint64_t v) noexcept : __actual(@(v)) {}; CKBoxedValue(long v) noexcept : __actual(@(v)) {}; CKBoxedValue(unsigned long v) noexcept : __actual(@(v)) {}; CKBoxedValue(float v) noexcept : __actual(@(v)) {}; CKBoxedValue(double v) noexcept : __actual(@(v)) {}; CKBoxedValue(SEL v) noexcept : __actual([NSValue valueWithPointer:v]) {}; CKBoxedValue(std::nullptr_t v) noexcept : __actual(nil) {}; // Any objects go here CKBoxedValue(__attribute((ns_consumed)) id obj) noexcept : __actual(obj) {}; // Define conversions for common Apple types CKBoxedValue(CGRect v) noexcept : __actual([NSValue valueWithCGRect:v]) {}; CKBoxedValue(CGPoint v) noexcept : __actual([NSValue valueWithCGPoint:v]) {}; CKBoxedValue(CGSize v) noexcept : __actual([NSValue valueWithCGSize:v]) {}; CKBoxedValue(UIEdgeInsets v) noexcept : __actual([NSValue valueWithUIEdgeInsets:v]) {}; operator id () const { return __actual; }; private: id __actual; };
You can call the user-defined conversion function operator id() const; like any other member function: // (Assuming `x` is some value of type `CKBoxedValue`) x.operator id(); But it is usually called during a type conversion, for example: // Explicit conversions: id(x) static_cast<id>(x) id value(x); // Implicit conversions: // With `void function_taking_an_id(id arg);` function_taking_an_id(x) id value = x;
70,518,606
70,518,683
Why does a compiler allow a user to change the type of an 'auto' variable?
I expected the auto keyword to deduce the type of a variable from an intializer once and keep that type throughout the code. To my surprise, my compiler (g++ 9.3.0) allows me to change it's type and it still works. This is sort of acceptable to me when I first use the variable as an int and then as a float. But when I use the auto keyword to declare a string and then assign a float value to that variable, the compiler doesn't throw an error but also doesn't print the value after the float assignment. Can someone explain why it allows assigning a float value to a string variable in the first place? Does the compiler just accept the new assignment each time? Or does it throw some kind of exception that I am not able to catch? Code below - #include <iostream> int main() { auto x = '2'; std::cout << x << std::endl; x = 3.0; // Why is this allowed? std::cout << x << std::endl; // This won't print return 0; }
To show you what's going on I extended the example with some compile time type checks: #include <type_traits> #include <iostream> int main() { auto x = '2'; // decltype(x) is the type for variable x // compare it at compile time with char type static_assert(std::is_same_v<decltype(x), char>); std::cout << x << std::endl; x = 3.0; // Why is this allowed? because it does a narrowing conversion from double to char // my compiler even gives this warning : // main.cpp(11,6): warning C4244: '=': conversion from 'double' to 'char', possible loss of data // type of x is still the same and it is still a char static_assert(std::is_same_v<decltype(x), char>); std::cout << static_cast<int>(x) << std::endl; // the cast is here to be able to print the actual value of the char return 0; }
70,519,306
70,519,738
fill an array of type class inside another class
I am new in c++ recently i started learning poo I want to create a class movies and a class. directors a class movie should have an array of directors and I want to fill that array from the console. When I run the code it show me the first and second line and stop executing : enter image description here this is my code: #include<iostream> #include<string> using namespace std; class directors{ string name; string lastname; public: directors(){ } directors(string a,string b){ name=a; lastname=b; } void createdirector(){ cout<<"name of director:"<<endl; cin>>name; cout<<"last name:"<<endl; cin>>lastname; } }; class movie{ string name; directors* director; public: film(){ directors* director=new directors[20]; }; void creatmovie(){ cout<<"name of movie"<<endl; cin>>name; director[0].createdirector(); } }; int main(){ movie a; a.creatmovie(); }
A better way wold be to use std::vector as shown below. The advantage of using a std::vector is that you don't have to worry about manual memory management(like using new and delete explicitly). vector will take care of it(memory management). You can use the below given example as a reference. #include<iostream> #include<string> #include <vector> class director{ std::string name; std::string lastname; public: director(){ } //use constructor initializer list director(std::string a,std::string b): name(a), lastname(b){ } void createDirector() { std::cout<<"Enter name of director:"<<std::endl; std::cin>>name; std::cout<<"Enter last name:"<<std::endl; std::cin>>lastname; } void displayDirector() const { std::cout << "Firstname: "<<name<<" Lastname: "<<lastname<<std::endl; } }; class movie{ std::string name; std::vector<director> directors; //vector of director objects public: //constructor that creates vector directors of size vecSize movie(size_t vecSize): directors(vecSize) { std::cout << "Enter name of movie: "<<std::endl; std::cin >> name; //iterate through the vector and call method createDirector on each element for(director &elem: directors) { elem.createDirector(); } } void displayMovie() { std::cout<<"Movie's name is: "<<name<<std::endl; //iterate through the vector and call displayDirector on each object for(const director& elem: directors) { elem.displayDirector(); } } }; int main(){ movie a(4); //create an object of type movie. Note i have passed 4 as argument you can pass other numbers like 3,2 etc a.displayMovie();//display movie info } Some of the modifications that i made are: Used constructor initializer list in class director added a method called displayDirector in class director added a method called displayMovei in class movie added a data member called directors that is a std::vector<director> in class movie. added a constructor for class movie that initializes the data member directors. removed unnecessary method namedfilm from class movie not used using namespace std; which is a recommended practice The output of the above program can be seen here.
70,520,081
70,520,296
How to change the widgets property if I use QT Designer
I am using Visual Studio 2022 and C++ QT 5.14.2. I used QT Designer to setup a PushButton and a LineEdit, and I gave them some initial property. But I met problem in button clicked signal slot function, this is my code: void SocketChat::on_connectButton_clicked() { appendMessage(ui.connectButton->text()); // output button's text if (ui.addrEdit->isEnabled() && ui.portEdit->isEnabled()) { // disabled ui.addrEdit->setEnabled(false); ui.connectButton->setText(QStringLiteral("Disconnect")); appendMessage(ui.connectButton->text()); // output button's text } if (ui.addrEdit->isEnabled() && !ui.portEdit->isEnabled()) { ui_notification->setText(QStringLiteral("Please stop listening.")); } if (!ui.addrEdit->isEnabled() && ui.portEdit->isEnabled()) { // enabled ui.addrEdit->setEnabled(true); ui.connectButton->setText(QStringLiteral("Connect")); } } Button's text was assigned to 'Connect' in QT Designer, and after the function finished, the button's text is still 'Connect'. appendMessage function output two words for every time I clicked: Connect Disconnect The click function works properly but and the button's text was changed successfully in this function. But after the function finished, everything recovered. The button's text is still 'Connect'. I tried repaint() and update(), they're unable to work. How can I change the widgets' property? It seems that these properties cannot be initialized once they have been changed.
You are missing some else keywords. Note that when your button is clicked the first if-block (labeled "// disabled") is execute and it disables the ui.addrEdit button. Due to the missing else keyword the program then also checks the conditions of the other if statements. And since the button is now disabled the last condition evaluates to true and therefore the block labeled "// enabled" is also run. This is not what you want.
70,520,112
70,522,191
Compiler doesn't see the C++11 identifiers
When I was trying to build the Google test c++ project I caught the errors Error C3861 't1': identifier not found Error C2065 't1': undeclared identifier Error C2039 'thread': is not a member of 'std' Error C2065 'thread': undeclared identifier Error C2146 syntax error: missing ';' before identifier 't1' My test code is: #include <future> #include <thread> #include "pch.h" TEST(...) { // preconditions here std::thread t1([&] { Sleep(100); testee.enqueue(item); }); t1.join(); // other logic } Why I cannot use the std::thread and other C++11 features in my project? How can I do it?
#include "pch.h" must be first. Other #include directive prior #include "pch.h" are ignored.
70,520,308
70,520,560
C++ variant containing a map of itself
I would like to be able to create a variant that contains a std::map<std::string, MyVariant> as one of its cases. The ideal would be able to write something like using MyVariant = std::variant<int, std::string, std::map<std::string, MyVariant>>; but this requires forward declaration. I'm aware that similar questions have been asked previously, e.g. here and here, but these have mainly been focused on the case of std::vector, and since C++17 std::vector is allowed to use incomplete types, while std::map does not. In particular, I'm wondering if the fixed-point combinator solution in this answer would work in this case? Adapting the code from that answer: #include <map> #include <string> #include <variant> // non-recursive definition template<typename T> using VariantImpl = std::variant<int, std::string, std::map<std::string, T>>; // fixed-point combinator template<template<typename> typename K> struct FixCombinator : K<FixCombinator<K>> { using K<FixCombinator>::K; }; using MyVariant = FixCombinator<VariantImpl>; However if there's another way to do it, I would be interested with that also.
This is not possible (at least by standard guarantees), since std::variant requires the used types to be complete and std::map requires key and value type to be complete types at the point of instantiation. But your construction will be complete only after it's instantiation. The only standard containers allowing such a recursive construction (at least to some degree) are std::vector, std::list and std::forward_list. If you want to use std::map and have standard guarantees for it, you need to add one level of indirection at some point.
70,520,869
70,520,941
How to make a class public only to another class
I have two separate distinct classes in C++, Node and Graph. I want to make the contents of Node accessible via the methods in graph but not public, how do I do this?
You can use a friend declaration to specify classes or functions that you'd like to give full access to the private and protected members. Example: class Node { // ... private: friend class Graph; int x; }; class Graph { public: void foo(Node& n) { n.x = 1; // wouldn't work without `friend` above } }; int main() { Graph g; Node n; g.foo(n); }
70,521,298
70,521,978
Is this correct: std::views::reverse on infinite range?
See this example code: #include <ranges> int main() { for(auto i : std::ranges::iota_view(1) | std::views::reverse) break; } It compiles on gcc (I cannot check on clang/msvc - since they do not support ranges). Of course -- it runs "forever" and does nothing. I also checked that doing std::ranges::rbegin(inf) or std::ranges::rend(inf) on infinite range is not allowed (it does not compile). I am not sure if this is correct c++ code? And I am curious about std::ranges::reverse implementation - looks like rbegin/rend is not used to implement this view -- so how this implementation works?
According to [iterator.requirements.general-10]: A sentinel s is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == s. If s is reachable from i, [i, s) denotes a valid range. And [iterator.requirements.general-12]: The result of the application of library functions to invalid ranges is undefined. Since ranges::iota_view(1) is not a valid range, applying views::reverse to it is undefined behavior.
70,521,545
70,521,638
Why is my C++ output not showing in VS Code Terminal (GCC)
Trying to get the output of my basic C++ program in VS Code but it's not displaying in terminal Using the run icon This is what is being in the terminal Terminal screenshot However, if I do this, then the output is shown as usual Using Run tab and debugging Final-Terminal Please let me know what is happening here, I don't understand why it's happening this way but not the other way Also, I have this extension installed in case it makes a difference Extension
Your source code file is named "full pyramid". This is causing the compiler to try to compile it as two separate files, called "full" and "pyramid". Try naming the file "full_pyramid" instead.
70,521,607
70,523,009
How do I set up a CMake project with subfolders?
I'm new to CMake so I apologize if my question turns out to be a noob one. I'm trying to set up a project in C++ with a directory structure similar to what Maven would create if I was coding in Java (src directory and build directory): root ├── build (where to build) ├── CMakeLists.txt (main one) ├── compile_commands.json -> ./build/compile_commands.json ├── doc ├── Doxyfile └── src ├── CMakeLists.txt ├── common │   └── Terminal.hpp ├── fsa │   ├── CMakeLists.txt │   ├── Machine.cpp │   ├── Machine.hpp │   └── MachineState.hpp └── main.cpp I don't know how to properly set CMake so to recognize, compile and link all the files. In particular, I think I should use (a mix of) add_subdirectory(), add_executable(), link_directories(), target_link_libraries(), add_library() and target_include_directories(), but I'm not sure I got how. I provide later my CMakeLists.txt files, but when I configure and compile, I get: /usr/bin/ld: fsa/libfsalib.a(Machine.cpp.o): in function `Machine::addState(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool, bool)': Machine.cpp:(.text+0xd1): undefined reference to `MachineState::MachineState(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool)' collect2: error: ld returned 1 exit status make[2]: *** [src/CMakeFiles/elr1.dir/build.make:98: src/elr1] Error 1 make[1]: *** [CMakeFiles/Makefile2:115: src/CMakeFiles/elr1.dir/all] Error 2 make: *** [Makefile:91: all] Error 2 What do I do wrong? EDIT: turned out it was a very stupid mistake of mine, I forgot to add an implementation. However, some questions remain: Can you please tip me if this project/cmake structure is best practice or not? I dind't get the where i should use link_directories() and target_include_directories(). More in general, how can I keep my codebase tidy and compile my project? Thanks in advance My commands are to configure: "cmake -S /path_to_root_project -B /path_to_root_project/build -D CMAKE_EXPORT_COMPILE_COMMANDS=ON" to compile: "cmake --build /path_to_root_project/build" root_project/CMakeLists.txt: cmake_minimum_required(VERSION 3.10) # set the project name project(elr1 VERSION 0.1) set(CMAKE_CXX_STANDARD 11) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) add_subdirectory(src) root_project/src/CMakeLists.txt: add_subdirectory(fsa) # add the executable add_executable(elr1 main.cpp) link_directories(fsa) target_link_libraries(elr1 #target in which link fsalib #library name ) root_project/src/fsa/CMakeLists.txt: add_library(fsalib #name Machine.cpp #files MachineState.hpp ) target_include_directories(fsalib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} )
Can you please tip me if this project/cmake structure is best practice or not? There are none, or endless, best practices, and every day someone invents a new one. Especially as to how to structure your project, which is unrelated to CMake. Structure it in a way that you want, and you judge is the best. Your structure seems completely fine. Look a look at endless google results. What's a good directory structure for larger C++ projects using Makefile? and http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1204r0.html project. As for CMake you can take a look at the ultimate https://github.com/friendlyanon/cmake-init , https://github.com/cmake-lint/cmake-lint , https://gist.github.com/mbinna/c61dbb39bca0e4fb7d1f73b0d66a4fd1 . where i should use link_directories() and target_include_directories(). Generally you should prefer target stuff, i.e. target_link_directories over non-target. Use target_include_directories to add a path to #include <thishere> search path. Use target_link_directories to add a library path to the search path target_link_libraries(... this_library_here). Usually you want to use add_library(... IMPORTED), then find_library, instead of target_link_directories. See man ld. In your project there are no external shared .so nor static .a libraries. I see no reason to use link_directories at all. how can I keep my codebase tidy and compile my project? Well, you can work hard and cleanup your project often. Remember about regular exercise, sleep and to eat healthy. Instead of set(CMAKE_CXX_STANDARD 11) prefer target_set_properties(. .. CXX_STANDARD 11).
70,522,231
70,522,361
How to know if some data type is from std?
Is there any list of types inside std namespace? I'm writing translator from uml diagram to c++ code, that should add std:: when it's needed. How my program should know that string has prefix std:: and int doesn't.
Is there any list of types inside std namespace? All of them are mentioned in the standard, as well as any documentation that covers the standard. There's no plain list that I know of however. How my program should know that string has prefix std:: and int doesn't. Your program should know that int isn't in a namespace because it is a keyword. You can find a list of all keywords in the [tab:lex.key] table in the standard. However, just because an identifier is string, doesn't mean that it is in the std namespace. Example: namespace not_std { struct string {}; string s; // this isn't std::string } #include <string> using std::string; string s; // this is std::string Adding the std:: qualifier would be correct only in the latter case. I'm writing translator from uml diagram to c++ code In my opinion, your translator should translate string into string and std::string into std::string. Let the author of the diagram ensure that their names are correctly qualified. If the translator has to make guesses, then there will be cases where it guesses incorrectly.
70,522,630
70,522,885
Why do gcc and clang give different results in aggregate initialization?
#include <iostream> struct U { template<typename T> operator T(); }; template<unsigned I> struct X : X<I - 1> {}; template<> struct X<0> {}; template<typename T> constexpr auto f(X<4>) -> decltype(T(U{}, U{}, U{}, U{}), 0u) { return 4u; } template<typename T> constexpr auto f(X<3>) -> decltype(T(U{}, U{}, U{}), 0u) { return 3u; } template<typename T> constexpr auto f(X<2>) -> decltype(T(U{}, U{}), 0u) { return 2u; } template<typename T> constexpr auto f(X<1>) -> decltype(T(U{}), 0u) { return 1u; } template<typename T> constexpr auto f(X<0>) -> decltype(T{}, 0u) { return 0u; } struct A { void* a; int b; double c; }; int main() { std::cout << f<A>(X<4>{}) << std::endl; } The code above is accepted by both of gcc and clang. However, gcc gives the expected output 3; other than the unexpected output 1 given by clang. See: https://godbolt.org/z/YKnxWah1a Related Q&A: Why does Clang 12 refuse to initialize aggregates in the C++20 way? Which is correct in this case?
U is a type which claims convertibility to any other type. And "any other type" includes whatever T is provided to the f templates. Therefore, 1 is always a potentially legitimate overload; SFINAE permits it to exist. A is an aggregate of 3 elements. As such, it can be initialized by an initializer list containing anywhere from 0 to 3 elements. C++20 allows aggregates to undergo aggregate initialization with constructor syntax. Therefore, 3, 2, 1, and 0 are all potentially legitimate overloads; SFINAE permits them to exist. Under pre-C++20 rules, none of these would be aggregate initialization, so none of them (save 1, which works because of the aforementioned property of U) would be valid SFINAE overloads. Clang doesn't implement C++20's rule for aggregate initialization as of yet, so as far as Clang is concerned, the only available overload is X<1>. For more fully functional C++ compilers, the question is this: which overload is better by C++'s overload resolution rules? Well, all of the available overloads involve implicit conversions from the argument type X<4> to one of its base classes. However, overload resolution based on base class conversions gives priority to base classes that are closer to the type of the argument in the inheritance graph. As such, X<3> is given priority over X<2> even though both are available. Therefore, by C++20's rules and overload resolution, 3 ought to be the right answer.
70,522,815
70,523,024
Right-angled triangle pattern with recursion numbers C++
I'm trying to print a right angled triangle with ascending and descending numbers using recursion only. void straightTriangular(int num) { if (num == 0) { return; } straightTriangular(num - 1); for (int i = 1; i <= num; i++) { cout << i; } cout << endl; } How can I do this with recursion only without "for" loop? if the user input number is 4 then I want the output to be this: 1 121 12321 1234321 my output using the code I posted: 1 12 123 1234
You can have: a printTriangleRec function that goes on printing every line recursively, two printAscendingRec and printDescendingRec functions that print the two halves of each line recursively. [Demo] #include <iostream> // cout void printAscendingRec(int cur, int top) { std::cout << cur; if (cur != top) { printAscendingRec(cur + 1, top); } } void printDescendingRec(int cur) { if (cur) { std::cout << cur; printDescendingRec(cur - 1); } } void printTriangleRec(int cur, int top) { printAscendingRec(1, cur); printDescendingRec(cur - 1); std::cout << "\n"; if (cur != top) { printTriangleRec(cur + 1, top); } } void printTriangle(int num) { if (num < 1) { std::cout << "Error: num < 1\n"; return; } printTriangleRec(1, num); } int main() { printTriangle(4); }
70,523,110
70,523,168
Memory leak warning when using dependency injection using a unique_ptr containing a mocked interface
My main question is about a specific gmock error but to provide some background. I have been working on a larger project where I have different implementations of the same interface. I want to be able to instantiate a class using the interface and choose which interface implementation it has to use (when creating the class instance). The interface is not shared and each instance of the interface is only used by one class instance. In order to do this I use dependency injection and I store the interface instance in a unique_ptr. This works properly and gives me the desired behavior. To unit test some the class I used gmock to mock the interface and then injected the mocked interface into my class under test. To my surprise gmock informed me that I had a memory leak which I do not understand. A simplified piece of code produces the same error: #include "gtest/gtest.h" #include "gmock/gmock.h" class Base { public: virtual int something() = 0; }; class Mock : public Base { public: MOCK_METHOD(int, something, ()); }; class test : public ::testing::Test { protected: void SetUp() override { mock = std::make_unique<Mock>(); EXPECT_CALL(*mock, something()).WillOnce(testing::Return(1)); } std::unique_ptr<Mock> mock; }; TEST_F(test, test) { std::unique_ptr<Base> base = std::move(mock); EXPECT_EQ(base->something(), 1); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } The test passes but produces the warning: ERROR: this mock object (used in test test.test) should be deleted but never is. Its address is @0122CA60. ERROR: 1 leaked mock object found at program exit. Expectations on a mock object are verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock. Process finished with exit code 1 My question is 2 fold. 1 why is the memory being leaked and 2 how should I improve my design? Note that the dependency injection is not shown in the example. Assigning the pointer to the interface would be a constructor which moves the pointer into the class and abstracts from the implementation of the interface.
std::unique_ptr<Base> base = std::move(mock); is where the memory leak happens: *base will be destroyed as a Base, not a Mock, when base is destroyed. The best fix is to add a virtual destructor (virtual ~Base() = default;), which you should have for a struct that has any other virtual members.
70,523,134
70,523,572
Global variable and static global variable
Is there any difference in C++ between global variable/const and global static variable/const? Declared in cpp file or a header file. static const int x1 = someFunction(5); const int x2 = someFunction(6); static int x3 = someFunction(5); int x4 = someFunction(6); int main() { ...
Case I: For const objects Similarity In both versions, the variables have internal linkage. That is, both x1 and x2 have internal linkage. Difference In case of static const int x1 the variable is explicitly static while in case of const int x2 the variable is implicitly static. But note that they both still have internal linkage. Case II:For nonconst objects Similarity Both x3 and x4 are nonconst meaning we can modify them. Difference The variable x3 has internal linkage while the variable x4 has external linkage.
70,523,217
70,523,478
How does gcc compile C functions in a constexpr context?
Given that the C++ standard library doesn't (currently) provide constexpr versions of the cmath functions, consider the program below. #include <cmath> #include <cstring> int main() { constexpr auto a = std::pow(2, 10); constexpr auto b = std::strlen("ABC"); } As expected, MSVC++ and clang++ fail to compile this, because constexpr variables are initialized from functions that are not declared constexpr. g++, however, compiles this. The version of g++ doesn't seem to matter. (See them all in compiler explorer) How does g++ achieve this? Is this correct (allowed) compiler behavior?
The resolution of LWG 2013 was that implementations are not allowed to declare non-constexpr functions as constexpr, so gcc is non-conformant by allowing these to be evaluated at compile time. That said, GCC does not actually mark the needed functions as constexpr. What it instead does is replace those calls very early on with __builtin_pow and __builtin_strlen, which it can compute at compile time (the std:: versions call the libc versions, which can't). This is a compiler extension. If you compile with -fno-builtin, it also fails to compile both std::pow and std::strlen, but you can make both clang and GCC compile this by explicitly writing out __builtin_pow(2, 10) and __builtin_strlen("ABC").
70,523,455
70,523,581
Assignement and addition overload for template objects
I am trying to learn templates and overloads at the same time. I have wrote the code below but I fail to do assignement of the data object with built-in types. What am I dooing wrong and how to solve it and yet better what is the best practice that can result in no intemediate-copy constructors to be called? I want to have all the possible arithmetic operations. I think if I get it right for one of them (e.g. +) then others would be the same principles. Do I need Copy/Move constructor and assignements? #include <iostream> #include <concepts> template<typename T> requires std::is_arithmetic_v<T> class Data { private : T d; public: Data(const T& data) : d{data}{ std::cout << "Constructed Data with: " << d << std::endl; } Data(const Data& other) = default; ~Data() { std::cout << "Destructed: " << d << std::endl; } void operator+(const T& other) { this->d += other; } Data operator+(const Data& other) { return (this->d + other.d); } Data operator=(const Data& other) { return(Data(d + other.d)); } void operator=(const T& t) { this->d += t; } Data operator=(const T& t) { // FAIL return Data(this->d + t); } }; int main() { Data a = 1; Data b = 2; Data c = a + b; Data d = 10; d = c + 1; // how to do this? FAIL } Compile Explorer Link
For starters you may not overload an operator just by the return type as void operator=(const T& t) { this->d += t; } Data operator=(const T& t) { // FAIL return Data(this->d + t); } As for other problem then in this statement d = c + 1; the expression c + 1 has the return type void due to the declaration of the operator void operator+(const T& other) { this->d += other; } The operator should be declared and defined like Data operator +(const T& other) const { return this->d + other; } The operators can be overloaded as it is shown below template<typename T> requires std::is_arithmetic_v<T> class Data { private: T d; public: Data( const T &data ) : d{ data } { std::cout << "Constructed Data with: " << d << std::endl; } Data( const Data &other ) = default; ~Data() { std::cout << "Destructed: " << d << std::endl; } Data operator +( const T &other ) const { return this->d + other; } Data operator +( const Data &other ) const { return this->d + other.d; } Data & operator =( const Data &other ) { this->d = other.d; return *this; } Data & operator=( const T &t ) { this->d = t; return *this; } };
70,523,731
70,523,846
I am getting C++ compilation issues while compiling my project
I am trying to implement the zoom sdk and want to prevent my screen to be captured and by screen shots for this purpose they have given some functions to be placed inside the project. When I place the code inside the function I start getting some errors and when I remove then the errors are gone. The code which need to be placed inside the project is as follows: BOOL CALLBACK EnumWindowsCB(HWND hwnd, LPARAM lParam) { SetWindowDisplayAffinity(hwnd, WDA_MONITOR); return TRUE; } void CZoomSDKeDotNetWrap::DisableScreenRecord() { DWORD pid = GetCurrentProcessId(); EnumWindows(EnumWindowsCB, pid); uint8_t* func_data = (uint8_t*)GetProcAddress(GetModuleHandle(L"user32.dll"), "SetWindowDisplayAffinity"); } Please let me know what these errors mean and how to resolve them. The errors are: enter image description here
You need to add a reference to the respective library(dll) you're using in the function you're trying to put inside the library. As seen in your code above you're trying to use standard Windows libraries. Have you tried editing your project properties then linker input options to include user32.lib?
70,523,821
70,524,136
(C++) Writing and reading a dynamic array to a binary file
I'm new here so forgive me if I make some mistakes. Anyway, I've got this code here: class List{ private: int dim; Reservations *res; //Dynamic array of reservations that composes "List" public: List(); List(int dm, Reservations *resv); ~List(); int getDim(); void setDim(int dm); void readNwrite(List &ls); }; This is a class and I need to write and read the Reservations array in a binary file. The Reservations class is composed of other types of data (two strings, an integer and also another class). Here you can see the Reservations class: class Reservations{ private: DateTime dt; string name, phone; int codVisit; public: Reservations(); Reservations(DateTime datT, string nm, string tel, int cod); ~Reservations(); DateTime getDt(); void setDt(DateTime datT); string getName(); void setName(string nm); string getTel(); void setTel(string tel); int getCodVisit(); void setCodVisit(int cod); void read(); void print(); }; And here's the class DateTime: class DateTime{ private: Date d; int sec, min, hrs; public: DateTime(); DateTime(int s, int m, int o, int d, int ms, int y); ~DateTime(); void getDt(); void setDt(int g, int ms, int y); int getSec(); void setSec(int s); int getMin(); void getMin(int m); int getOre(); void getOre(int o); void print(); void read(); int validate(); int compare(DateTime dt1); friend void Anglform(DateTime dt); }; This is how I've done created and read the binary file in the List class: void List::readNwrite(List &ls){ ofstream file("list.dat", ios::binary); file.write(reinterpret_cast<char*>(res), sizeof(Reservations) * dim); file.close(); ifstream fileF("list.dat", ios::binary); ls.setDim(dim); ls.res = new Reservations[ls.dim]; fileF.read(reinterpret_cast<char*>(ls.res), sizeof(Reservations) * dim); file.close(); } I've tried it but it isn't working. I know that the second instance is getting the contents of the first one, but in the end the program always crashes...
To be able to read/write a structure to/from a file as a binary blob, that structure must be standard layout type (aka POD) and not contain any pointers within. Your structure obviously does not satisfy that requirement (std::string object is not a standard layout type and does contain a pointer(s) inside) so you have to write reading/writing methods to load/store data member by member or use a library designed for that purpose. Note: your class Reservations violates the rule of 3/5/0 and you have memory leak right there on this line: ls.res = new Reservations[ls.dim]; You better use std::vector for dynamic array or if you cannot at least a smart pointer.
70,523,952
70,524,035
Why am i getting numbers in scientific form in simple calculations?
Background: So I basically googled projects for beginners for C++ and one recommendation was currency converter. So I decided to do this, at first I tried to do it by creating a class, objects etc but I got lost with constructors and header files etc but that's a story for another day. I am very new to programming and this is my first "project". So I decided to go the simple route and did this: #include <iostream> int main(){ double euro; //creating all the variables and conversions double eur2dol = euro * 1.13; double eur2pound = euro * 0.84; double eur2rup = euro * 84.49; double eur2yuan = euro * 7.2322769; double eur2btc = euro * 0.0000237; double eur2eth = euro * 0.00029956; // creating an array with the name of the currency i am converting to std::string curname[6] = { " Dollars\n", " Pounds\n", " Rupees\n", " Yuan\n", " Bitcoin\n", " Etherium\n"}; // creating an array with the conversions i want to do double currencies[6] = { eur2dol, eur2pound, eur2rup, eur2yuan, eur2btc, eur2eth }; //accepting input from the user std::cout << "Amount in euros: " << std::endl; std::cin >> euro; // for loop to loop through every item in the currencies array and the corresponding name of the currency from the curname array for(int i = 0; i < 5; i++){ std::cout << euro << " Euro is " << currencies[i] << curname[i]; }; return 0; } Now, I know there is no point in doing this other than practicing because the values constantly change but I am getting the same result no matter the value I type in and in scientific form. How can I fix it so i get the correct result and what is the problem?
A typical case of uninitialized variable. Here you are operating on euro variable before asking(cin) value for it, The correct implementation would be something like: #include <iostream> int main() { double euro = 0; //always put some values beforehand //accepting input from the user std::cout << "Amount in euros: " << std::endl; std::cin >> euro; //creating all the variables and conversions double eur2dol = euro * 1.13; double eur2pound = euro * 0.84; double eur2rup = euro * 84.49; double eur2yuan = euro * 7.2322769; double eur2btc = euro * 0.0000237; double eur2eth = euro * 0.00029956; // creating an array with the name of the currency i am converting to std::string curname[6] = { " Dollars\n", " Pounds\n", " Rupees\n", " Yuan\n", " Bitcoin\n", " Etherium\n"}; // creating an array with the conversions i want to do double currencies[6] = { eur2dol, eur2pound, eur2rup, eur2yuan, eur2btc, eur2eth }; // for loop to loop through every item in the currencies array and the corresponding name of the currency from the curname array for(int i = 0; i < 5; i++){ std::cout << euro << " Euro is " << currencies[i] << curname[i]; }; return 0; } Note: Uninitiazed variable is a bad practice. If you initialized the variable like double euro = 0; earlier, it will alteast not return arbitrary values even for the wrong code.
70,524,164
70,524,204
CMAKE_C_COMPILER not set, after EnableLanguage
I installed CMake on windows in addition to gcc and g++ compiler I added the variables to the path but still getting the following error could you please help. -- Building for: NMake Makefiles CMake Error at CMakeLists.txt:6 (project): Running 'nmake' '-?' failed with: The system cannot find the file specified CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage -- Configuring incomplete, errors occurred! See also "C:/Users/DEANHOS/Desktop/peer/cmake tutorial/codeAndTech/sample/CMakeFiles/CMakeOutput.log".
These variables need to be passed on the command line as: $ cmake -DCMAKE_CXX_COMPILER=/pathto/g++ -DCMAKE_C_COMPILER=/pathto/gcc /pathto/source or set up before the project() line in CMakeLists.txt: set( CMAKE_CXX_COMPILER "/pathto/g++" ) set( CMAKE_C_COMPILER "/pathto/gcc" ) project(mytest) ... or alternatively brought in with the -C <toolchain> command as # mygcc.cmake # toolchain file set( CMAKE_CXX_COMPILER "/pathto/g++" ) set( CMAKE_C_COMPILER "/pathto/gcc" ) $ cmake -C /pathto/mygcc.cmake /pathto/source
70,524,574
70,524,808
How to return a string with no overhead inside helper function
I want to put this logic into a helper function: std::stringstream ss; std::string str = "some str"; if (do_check(str)) { ss << str; } else { ss << do_edit(str); } and instead write it like std::string edit_str(const std::string &str) { if (do_check(str)) { return str; } return do_edit(str); } main() { std::stringstream ss; std::string str = "some str"; ss << edit_str(str); } However, this creates a copy when I return str. Is there any way to write this as a helper function with no/minimal overhead? I'm open to changing the parameter/return type, using output parameters, templates, etc., but I would like to avoid using macros.
The standard library sets the standard for how to do this with functions like std::quoted. The function actually does no work; it just stores references to the arguments into an object, called the IO manipulator. Then the operator<< for that object is what does the actual work. We can simply follow their example. struct edited { // playing a little fast-and-loose; instead of a dedicated function we just aggregate-initialize this struct with a function-like syntax (requires C++20) std::string const &str; friend std::ostream &operator<<(std::ostream &out, edited const &thiz) { // you can put whatever block of code you'd like to factor out in here if (do_check(thiz.str)) out << thiz.str; else out << do_edit(thiz.str); return out; } }; int main() { std::string str = "some string"; std::cout << edited(str); } You do have to be careful not to accidentally use edited(str) like a string. The only thing you should be doing with it is <<ing it into a stream. If you need a std::string from it at some point, make a std::stringstream and use that to collect the output. Also, it may be beneficial to inline do_edit into operator<< and adjust it so it does not return an intermediate string that then gets output but can just output directly, too.
70,524,923
70,525,269
C++ - Convert any number of nested vector of vector to equivalent vector of span
following situation: I work with data that falls into the categories of std::vector<T> data1; std::vector<std::vector<T>> data2; std::vector<std::vector<std::vector<T>>> data3; //etc... T usually refers to numerical data like double. Sometimes I would like to get the data in a form where the last std::vector is replaced by a std::span<T> pointing to the same data. std::span<T> data1; std::vector<std::span<T>> data2; std::vector<std::vector<std::span<T>>> data3; //etc... It's not hard to define individual functions for every single level of nesting, but could I somehow also define a single function that could do this automatically for any level of nesting?
You might do: template <typename T, typename F> auto transform(std::vector<T>& v, F func) { std::vector<std::decay_t<decltype(func(v[0]))>> res; res.reserve(v.size()); std::transform(v.begin(), v.end(), std::back_inserter(res), func); return res; } template <typename T> std::span<T> to_span(std::vector<T>& v) { return v; } template <typename T> auto to_span(std::vector<std::vector<T>>& v) { return transform(v, [](auto& inner){ return to_span(inner); }); } Demo
70,525,253
70,525,712
std::set of MyElement with MyElement::SomeMethod as custom comparator
I have a simple MyElement class, and I would like to use a bool MyElement::SomeMethod(...) {...} as the custom comparator for a std::set of MyElement items. I have made my research, and I am already aware of some alternative solutions, which I list below. I also know how to change, for example, the comparator with std::greater instead of the default std::less, with code like this: std::set<MyElement, std::greater<MyElement> > s; My exact problem is that I want to use bool MyElement::SomeMethod(...) {...} as custom comparator. The only solution I come up with is analogous to the last one in the list below, namely the solution for boolean function: using Cmp = std::integral_constant<decltype(&MyElement::SomeMethod), &MyElement::SomeMethod>; std::set<MyElement, Cmp> my_set; This solution only works for a static MyElement::SomeMethod, though. I am wondering if there is an analgous, or more concise, way for a non static method. List of alternative solutions: method for C++20 auto cmp = [](const MyElement& lhs, const MyElement& rhs) { return ... }; std::set<MyElement, decltype(cmp)> s; method for C++11 auto cmp = [](const MyElement& lhs, const MyElement& rhs) { return ... }; std::set<MyElement, decltype(cmp)> s(cmp); function instead of a lambda bool cmp(const MyElement& lhs, const MyElement& rhs) { return ...; } and then std::set<MyElement, decltype(cmp)*> s(cmp); or std::set<int, decltype(&cmp)> s(&cmp); struct and operator() struct cmp { bool operator() (const MyElement& lhs, const MyElement& rhs) const { return ... } }; and then std::set<MyElement, cmp> s; boolean function bool cmp(const MyElement& lhs, const MyElement& rhs) { return ...; } and then #include <type_traits> using Cmp = std::integral_constant<decltype(&cmp), &cmp>; std::set<MyElement, Cmp> s;
You can use std::mem_fn to bind a member function. #include <functional> #include <iostream> #include <set> #include <utility> struct S { int i; bool cmp(const S& other) const { return i < other.i; } }; // Define make function to avoid having to write out template types. template <typename T, typename Cmp> std::set<T, Cmp> make_set(Cmp&& cmp) { return std::set<T, Cmp>{std::forward<Cmp>(cmp)}; } int main(int argc, char* argv[]) { auto s = make_set<S>(std::mem_fn(&S::cmp)); s.emplace(S{0}); std::cout << s.begin()->i << std::endl; return 0; }
70,525,450
70,525,555
Why move constructor and assignement not being called for initializing a vector with initialize_list
I have the class below and tried to add copy and move constructor and assignment operator. My goal is to have least amount of copy and be as optimized as possible. I expect the vectors to be filled in place, that is no copy constructors be called while creating the vector. What am I doing wrong and how to force it to use move constructor or assignment? #include <iostream> #include <concepts> #include <vector> template<typename T> requires std::is_arithmetic_v<T> class Data { private : T mA = 0; T mB = 0; public: Data(const T& data) : mA{data}{ // from single T std::cout << "Constructed Data with: " << mA << ", " << mB << std::endl; } Data(const Data<T>& other) : mA{other.mA}, mB{other.mB} { std::cout << "COPY Constructed Data with: " << mA << ", " << mB << std::endl; } Data(Data<T>&& other) : mA{other.mA}, mB{other.mB} { std::cout << "MOVE Constructed Data with: " << mA << ", " << mB << std::endl; } Data(const std::initializer_list<T>& list) { std::cout << "Constructed Data with list: "; if(list.size() >= 2) { mA = *list.begin(); mB = *(list.begin() + 1); std:: cout << mA << ", " << mB << std::endl; } } ~Data() { std::cout << "Destructed: " << mA << ", " << mB << std::endl; } const Data operator=(const Data& other) { mA = other.mA; mB = other.mB; return *this; } Data operator=(Data&& other) { mA = other.mA; mB = other.mB; return *this; } }; int main() { std::cout << "** With initilizer_list **" << std::endl; { auto vec = std::vector<Data<int>>{{1,1}, {2,2}}; } std::cout << "\n**With element**" << std::endl; { auto vec = std::vector<Data<int>>{1,2}; } std::cout << "\n**With push**" << std::endl; { auto vec = std::vector<Data<int>>(); vec.push_back(1); vec.push_back(2); } } Output: ** With initilizer_list ** Constructed Data with list: 1, 1 Constructed Data with list: 2, 2 COPY Constructed Data with: 1, 1 COPY Constructed Data with: 2, 2 Destructed: 2, 2 Destructed: 1, 1 Destructed: 1, 1 Destructed: 2, 2 **With element** Constructed Data with: 1, 0 Constructed Data with: 2, 0 COPY Constructed Data with: 1, 0 COPY Constructed Data with: 2, 0 Destructed: 2, 0 Destructed: 1, 0 Destructed: 1, 0 Destructed: 2, 0 **With push** Constructed Data with: 1, 0 MOVE Constructed Data with: 1, 0 Destructed: 1, 0 Constructed Data with: 2, 0 MOVE Constructed Data with: 2, 0 COPY Constructed Data with: 1, 0 Destructed: 1, 0 Destructed: 2, 0 Destructed: 1, 0 Destructed: 2, 0 CompilerExplorer Link
I expect the vectors to be filled in place Both push_back and the initializer list constructor expect that the element is already constructed and passed through the parameter. Therefore the elements must first be constructed via conversion and then moved/copied into the vector's storage. If you don't want that, then use emplace_back instead, which takes constructor arguments for the element's constructor and creates the element in-place. This doesn't resolve all cases of copy and moves, since the vector must move objects to new storage if the old one becomes too small to hold more elements. To avoid this completely, first call vec.reserve(...) where ... is at least as large as the maximum size that the vector will have. The reason copy instead of move is used in case of reallocation is because you didn't mark your move constructor noexcept. std::vector prefers the copy constructor if the move constructor is not noexcept, because if a move constructor throws while moving the objects to new storage, then std::vector cannot guarantee that it will be able to roll-back to the previous state, as it would usually do. Declaring copy/move constructor/assignment or a destructor in a class is always a bit risky. Firstly, because how easy it is to cause undefined behavior, see rule of three/five and secondly because it often results in worse results than the implicitly generated versions if not carefully written. If you don't have a specific reason, e.g. because you manage a raw resource in the class, then don't declare any of these special members. (Only) Then the implicit ones will do the correct and most-likely best possible thing automatically ("rule of zero").
70,525,752
70,525,904
Is it possible to check the type of a derived class from an array element which is of the base type?
I created two objects from derived classes (Dog and Cat), which I assigned to one common array, which is the Animal type. Now I want to check a single element of the array to see if it is a dog. If there is, I want it to execute a method from Dog class and bark. #include <iostream> using namespace std; class Animal{ public: Animal() {} virtual ~Animal() {} }; class Dog : public Animal{ public: Dog() {} virtual ~Dog() {} void soundOf(){ cout << "Woof woof" << endl; } }; class Cat : public Animal{ public: Cat() {} virtual ~Cat() {} void soundOf(){ cout << "Meoow" << endl; } }; int main() { Animal animals[2]; Dog dog; Cat cat; animals[0] = dog; animals[1] = cat; Animal *ptr = animals+0; Dog* dg = dynamic_cast<Dog*>(ptr); if(dynamic_cast<Dog*>(ptr) != nullptr){ cout << "This is a dog" << endl; dg->soundOf(); }else if(dynamic_cast<Cat*>(ptr) != nullptr){ cout << "This is a cat" << endl; dg->soundOf(); } return 0; In "if", I also used the following method if(Dog* dg = dynamic_cast<Dog*>(ptr)) But the effect was the same. It returned NULL every time. When I wrote the same application in Java, it was enough to use "instanceof", but here I can't do it.
Others have commented as to why you are having this issue but have not really suggested a fix. You should get into the habit of using dynamically allocated objects and ensuring they behave nicely by using std::shared_ptr and std::vector. #include <iostream> #include <vector> #include <memory> using namespace std; class Animal { public: Animal() {} virtual void soundOf() {} virtual ~Animal() {} }; class Dog : public Animal { public: Dog() {} virtual ~Dog() {} void soundOf() { cout << "Woof woof" << endl; } }; class Cat : public Animal { public: Cat() {} virtual ~Cat() {} void soundOf() { cout << "Meoow" << endl; } }; typedef std::shared_ptr<Animal> AnimalPtr; int main() { std::vector<AnimalPtr> animals; AnimalPtr dog = std::make_shared<Dog>(); AnimalPtr cat = std::make_shared<Cat>(); animals.push_back(dog); animals.push_back(cat); AnimalPtr ptr = animals[0]; if (dynamic_cast<Dog *>(ptr.get()) != nullptr) { cout << "This is a dog" << endl; ptr->soundOf(); } else if (dynamic_cast<Cat *>(ptr.get()) != nullptr) { cout << "This is a cat" << endl; ptr->soundOf(); } return 0; } this might seem long winded but will scale much better (and provides the functionality you want)
70,526,117
72,820,737
How to patch 3rd party .so file, to access non-exported symbol (C++)
I have some binary .fic files in a proprietary format , I have a wd250hf64.so from this vendor that contains a C++ method CComposanteHyperFile::HExporteXML(wchar_t* const path) that I can see using nm $ nm --demangle wd250hf64.so --defined-only 0000000000118c90 t CComposanteHyperFile::HExporteXML(wchar_t const*) the unmangled version _ZN20CComposanteHyperFile11HExporteXMLEPKw is identical to what I have using my local g++ version readelf gives readelf -Ws wd250hf64.so | grep _ZN20CComposanteHyperFile11HExporteXMLEPK 19684: 0000000000118c90 119 FUNC LOCAL DEFAULT 11 _ZN20CComposanteHyperFile11HExporteXMLEPKw now I try writing a very simple program class CComposanteHyperFile { public: static void HExporteXML(wchar_t const*); }; int main() { CComposanteHyperFile::HExporteXML(L"file.fic"); return 0; } but when I compile it with g++ toto.cpp -L. -l:wd250hf64.so I got toto.cpp:(.text+0x10): undefined reference to 'CComposanteHyperFile::HExporteXML(wchar_t const*)' I don't have more luck with dlopen #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; void (*exportXML)(wchar_t const*); char *error; handle = dlopen("wd250hf64.so", RTLD_LAZY); *(void **) (&exportXML) = dlsym(handle, "_ZN20CComposanteHyperFile11HExporteXMLEPKw"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); exit(EXIT_FAILURE); } dlclose(handle); exit(EXIT_SUCCESS); } gcc -rdynamic -o foo toto.c -ldl ./foo wd250hf64.so: undefined symbol: _ZN20CComposanteHyperFile11HExporteXMLEPKw I understand that as it is not shown by nm with --extern-only it may be that this symbol is not "exported" and so it's not supposed to work normally my question is What is the hackish way of making the program to compile, by all means, even if it means manually patching the .so file ?
If you really want to be able to get at that symbol in any way possible, you could try to get its address relative to that of a known exported symbol, assuming that they're in the same section. For example, I made a simple dummy library with one exported function and one non-exported function. 0x0000000000003890 12 FUNC GLOBAL DEFAULT 16 function_we_exported 0x00000000000038a0 12 FUNC LOCAL HIDDEN 16 function_we_forgot_to_export Because this library was contrived just for this answer, the non-exported function happens to be right next to it, 0x10 after function_we_exported. Using this information, we can hackily do this. const auto address = reinterpret_cast<char*>(dlsym(library, "function_we_exported")); reinterpret_cast<your_function_type>(address + 0x10)(...); As you can probably tell, this is pretty hacky, but if you have no other choice, I suppose this can be a way. Another way may be to patch the library and forcibly export it. Considering that they show up as GLOBAL/LOCAL and DEFAULT/HIDDEN, it's probably a flip of a flag or something, but I don't know how to do that at the moment. I'll update this answer if I do.
70,526,654
70,526,711
Where is the rvalue coming from?
I learning about references and value categories because the latter are mentioned in some C++ errors. I have a function, referenceToDouble that takes in references to double. From watching this video on value categories, I believe that left and right below are lvalue references to double. In main when I make variables a and b of type double, I don't get an error. Code below shows a and b of type float which gives me an error. #include <cassert> double referenceToDouble(double& left, double& right) { if (left >= right) { right = left; } else { left = right; } return left; } int main() { float a = 55.5; float b = 55.5; assert(55.5 == referenceToDouble(a, b)); } When I switch the data type of a and b to float, I get this error. checkReferences.cpp: In function 'int main()': checkReferences.cpp:18:35: error: cannot bind non-const lvalue reference of type 'double&' to an rvalue of type 'double' 18 | assert(55.5 == referenceToDouble(a, b)); | ^ checkReferences.cpp:3:34: note: initializing argument 1 of 'double referenceToDouble(double&, double&)' 3 | double referenceToDouble(double& left, double& right) { | ~~~~~~~~^~~~ My questions are: where is the rvalue coming from? Is there a temporary variable that contains the double value of a that was cast from float? And is this temporary then the rvalue? Or is the error referring to the 55.5 which is a literal and therefore an rvalue? Is the return type not involved here? I think it isn't because this is a return by value and not by reference. I tried reading the answer to this question that had a similar error but I wasn't able to dispel my doubts. I also think I know what the solution (use double) is but I am trying to understanding what is going on under the hood.
Is there a temporary variable that contains the double value of a that was cast from float? And is this temporary then the rvalue? Yes. left and right with type double& can't bind to floats directly. They have to be converted to doubles firstly, which are temporaries (rvalues) and can't be bound to lvalue-reference to non-const. If you change the type of left and right to const double& then it'll work fine. The converted double temporaries (rvalues) could be bound to lvalue-reference to const.
70,526,932
70,527,714
How to understand the coalesced access in this CUDA matrix copy code?
__global__ void Matrixcopy(float *odata, const float *idata) { // threadblock size = (TILE_DIM, BLOCK_ROWS) = (32, 8) // each block copies a 32 * 32 tile int x = blockIdx.x * TILE_DIM + threadIdx.x; int y = blockIdx.y * TILE_DIM + threadIdx.y; int width = gridDim.x * TILE_DIM; for (int j = 0; j < TILE_DIM; j+= BLOCK_ROWS) odata[(y+j)*width + x] = idata[(y+j)*width + x]; } I'm quite confused about the concept of coalesced access for the multi-dim arrays. The definition of the coalesced global memory access is Sequential memory access is adjacent according to the literature Learn CUDA Programming. For 1-dim arrays, It's easy to understand the threads are indexed as threadIdx.x + blockDim.x * blockIdx.x, which could easily be mapped to the real 1-dim array: the adjacent threads within a warp access the adjacent physical address of the 1-dim array. Yet for 2-dim array or a matrix and a 2-dim threadblock like the code above, I'm not sure if I understand it correctly: The adjacent threads within a warp are located in the same row, i.e. same y value, different x values. If y = 0, the contiguous threads are x = [1, 2, 3, 4, 5, 6...], and they access contiguous address [1, 2, 3, 4, 5, 6...] if j = 0. So this code is with coalesced access. Am I correctly understood? And this is just a simple cuda code, if we have a complex cuda kernel, how can we quickly determine whether an access is coalesced or not?
So this code is with coalesced access. Am I correctly understood? Yes, pretty much. I would have said the threads are x = [0, 1, 2, 3, 4, 5, 6...], and they access contiguous addresses [0, 1, 2, 3, 4, 5, 6...] but basically we are in agreement. if we have a complex cuda kernel, how can we quickly determine whether an access is coalesced or not? You can look at any index construction and use the following test: If the threadIdx.x variable is included in the index as an additive factor, and it has no multiplicative factors on it, then the access will coalesce in typical usage (where you have square-ish threadblocks). Any index that can be expressed as: idx = f + threadIdx.x where f is arbitrary, but does not include threadIdx.x will result in coalesced access. Adjacent threads "in x" will access adjacent locations in memory. For "non-square-ish" threadblocks, you can develop a similar rule with threadIdx.y. For example, a threadblock of dimensions (1,32) will require that threadIdx.y be included as an additive-only factor.
70,526,946
70,527,266
Best way to display hierarchal data using Windows API (like that of the Registry Editor)
What is the best way to display data hierarchally, like that of the registry editor, with the Win32 API? Are there any controls that could do this? I know of this method in .NET, but I really don't feel like creating a ton of interactions between managed code and C++.
After you have created the TreeView control and added it to your window (see link in comments), you can load the registry keys like this. You would need some more code to add the values in a list view. void LoadRegRec(HWND tree_view, HTREEITEM parent, HKEY root) { DWORD index = 0; TCHAR name[512]; while (ERROR_SUCCESS == RegEnumKey(root, index++, name, sizeof(name) / sizeof(name[0]))) { TV_INSERTSTRUCT tvinsert = { 0 }; tvinsert.hParent = parent; tvinsert.hInsertAfter = TVI_LAST; tvinsert.item.mask = TVIF_TEXT; tvinsert.item.pszText = name; HTREEITEM node = (HTREEITEM)SendMessage(tree_view, TVM_INSERTITEM, 0, (LPARAM)&tvinsert); HKEY next_key; RegOpenKey(root, name, &next_key); LoadRegRec(tree_view, node, next_key); RegCloseKey(next_key); } } void LoadRegistry(HWND tree_view) { HKEY root; RegOpenKey(HKEY_CURRENT_USER, TEXT("Software"), &root); LoadRegRec(tree_view, NULL, root); RegCloseKey(root); }
70,527,237
70,527,731
Why does assigning 256 to a char raise a warning, but assigning 255 don't, but both result in integer overflow?
Consider this example: #include <iostream> int main() { char c = 256; std::cout << static_cast<int>(c); } Raise a warning: warning: overflow in conversion from 'int' to 'char' changes value from '256' to ''\000'' [-Woverflow] But this: #include <iostream> int main() { char c = 255; std::cout << static_cast<int>(c); } don't, but the std::cout in both cases doesn't print 256 and 255, so it shows char can't hold 256 and 255, but the warning only raise when the char c is 256? You can toy around with it here
It is important to specify whether char is signed in your example or not, but going by your link it is signed. If you write char c = 256; 256 has type int, so to store the value in c a conversion to char has to happen. For signed target types such integer conversions produce the same value if it is representable in the target type. That would with the typical bit size and representation of a signed char be -128 to 127. What happens if the source value is not representable in the target type depends on a few factors. First, since C++20 two's-complement is guaranteed, meaning that the resulting value is guaranteed to be the unique value such that the it and the source value are equal modulo 2^n with n the bit size of the target type (typically 8 for char). Before C++20 it was implementation-defined what happens in such a case, but it is very likely that the implementation would just have specified behavior equivalent to the C++20 one. So, the warning is not meant to prevent undefined behavior or even implementation-defined behavior since C++20, but just to notify the user about likely mistakes. I can't be sure why GCC chooses to warn only for values larger than 255, but my guess is that it is done because a statement like char c = 255; makes sense if you interpret the right-hand side as an unsigned char. The conversion rule explained above would not change the character represented before and after the conversion. However char c = 256; doesn't even make sense if the right-hand side is interpreted as unsigned char. So the likelihood that this is a mistake seems higher. But maybe I am also guessing in the wrong direction. There is an open bug report for GCC concerning this behavior of the -Woverflow warning. From reading the comments there it is not clear to me what the reasoning for the behavior was originally. Clang for example consistently warns about all out-of-range values. So there seem to be different thoughts put into the warnings.
70,527,832
70,527,928
safe way to get the n-th element of a union
I am writing a variant class(yes i know about std::variant, its just for fun), and this is what i have so far template<typename First, typename... Rest> union Variant<First, Rest...> { template<size_t N> using Types = typename Type<N, First, Rest...>::_Type; First first; Variant<Rest...> rest; uint16_t activeIndex; template<size_t N> Types<N>& get() { } }; the Type struct just allows me to find the type of the n-th element. I know that all the union's members are at the same memory address so can i just return *(Types<N>*)&first in the get function? is this safe? or is there some other way to do this. any help would be appreciated.
What you essentially want to know is if the operation: *(Types<N>*)&first adheres to strict aliasing. The answer is yes, so long as the type returned by Types<N> is a compatible type: The types T and U are compatible, if they are the same type (same name or aliases introduced by a typedef) In your example i am guessing that this is passed onto the user in some way by saying that the value must be set and retrieved using the same type. If this is the case and the user adheres to this rule, then it is safe. If you want to go above and beyond, you can look at the implementation of std::variant. The std::variant::get function actually throws if you try to retrieve a value that was not set correctly. To achieve this, you could think of using the reverse of Types<N> to get the index, and store it when setting. Then check that this is the index you are using when you get, if they are not the same, then throw.
70,528,043
70,528,077
Shellcode execution in C++
Working on some test projects, and I have this code, which works fine: #include <windows.h> #include <iostream> using namespace std; int main(int argc, char** argv) { char shellcode[] = "..snip..\xa0\x4e\xbc\x0b\x45\xee\xb3\x1b\xf9..snip.."; void* exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); ((void(*)())exec)(); return 0; } But I am trying to pass the dynamic sized byte array with the shellcode and this doesn't execute the code: int main(int argc, char** argv) { std::string(test) = "..snip..\xa0\x4e\xbc\x0b\x45\xee\xb3\x1b\xf9..snip.."; char* shellcode = new char[test.size()]; memcpy(shellcode, test.data(), test.size()); //std::copy(test.begin(), test.end(), shellcode); //delete[] shellcode; //std::cout << shellcode; void* exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); ((void(*)())exec)(); //return 0; } Could anyone point out where is a problem? Or how could I improve this?
In your first example, sizeof shellcode is the size of the array itself. In your second example, sizeof shellcode is the size of the pointer. It will always be either 4 or 8. Change the VirtualAlloc and subsequent memcpy statements to this: void* exec = VirtualAlloc(0, test.size(), MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, test.size());
70,528,232
70,528,360
implementing a cpp const iterator crashes and burns
Many posts about const iterators (example), but none in the context of loops like: for (const auto it: container) { ... } When I started implementing, I was encouraged by the compiler's complaints about missing begin and end, hoping such complaints can guide me to fill in the missing pieces. I was wrong. The following code compiles fine though it surely lacks the equivalent of both operator++ and operator!=: #include <iostream> template<class T> class List { public: const T *head; const List<T> *tail; List(const T *h, const List<T> *t):head(h),tail(t){} const T *operator*() const { return head; } }; template<class T> const List<T> *begin(const List<T> *l) { return l; } template<class T> const List<T> *end (const List<T> *l) { return nullptr; } class Person { public: int age; Person(int a):age(a){} }; typedef List<Person> Persons; int main(int argc, char **argv) { Person *p1 = new Person(16); Person *p2 = new Person(27); Person *p3 = new Person(38); Persons *persons = new Persons(p1, new Persons(p2, new Persons(p3, nullptr))); for (const auto p: persons) { std::cout << (*p)->age << "\n"; } return 0; } How come this code compiles?
You have not defined ++ and !=, but they are perfectly well-defined for your iterator type, const List<T>*, because is a pointer type. However, the default behavior of ++ does not do what you want, which would be to follow the tail pointer. To imbue your iterator with special knowledge of how ++ should be implemented, you would want to use a separate, custom iterator class, rather than using a pointer. I also made some other changes to your code: The List type is made iterable, not List*. That means the begin and end functions are not defined on pointers, but on the List object itself, and we iterate over *persons rather than persons. In for (const auto p : *persons), p is a Person, not a pointer. godbolt.org link #include <iostream> template<class T> class List { public: const T *head; const List<T> *tail; List(const T *h, const List<T> *t):head(h),tail(t){} const T *operator*() const { return head; } class const_iterator { const List<T>* cur = nullptr; public: explicit const_iterator(const List<T>* list) : cur(list) {} const_iterator& operator++() { cur = cur->tail; return *this; } bool operator!=(const const_iterator& other) const { return cur != other.cur; } const T& operator*() const { return *cur->head; } }; const_iterator begin() const { return const_iterator(this); } const_iterator end() const { return const_iterator(nullptr); } }; class Person { public: int age; Person(int a):age(a){} }; typedef List<Person> Persons; int main(int argc, char **argv) { Person *p1 = new Person(16); Person *p2 = new Person(27); Person *p3 = new Person(38); Persons *persons = new Persons(p1, new Persons(p2, new Persons(p3, nullptr))); for (const auto p: *persons) { std::cout << p.age << "\n"; } return 0; }
70,528,885
70,565,337
How do I assign a value from a SQL query to a variable? QT
void Registration::introductionDate(QString email){ QSqlQuery *query = new QSqlQuery(); int dailyCalorieIntake = query->prepare("SELECT dailyCalorieIntake FROM [dbo].[User] WHERE email = :email"); query->bindValue(":email", email); int dailyProteinIntake = query->prepare("SELECT dailyProteinIntake FROM [dbo].[User] WHERE email = :email"); query->bindValue(":email", email); int dailyIntakeOfCarbohydrates = query->prepare("SELECT dailyIntakeOfCarbohydrates FROM [dbo].[User] WHERE email = :email"); query->bindValue(":email", email); int dailyIntakeOfFats = query->prepare("SELECT dailyIntakeOfFats FROM [dbo].[User] WHERE email = :email"); query->bindValue(":email", email); float bmi = query->prepare("SELECT bmi FROM [dbo].[User] WHERE email = :email"); query->bindValue(":email", email); if (!query->exec()) { QMessageBox::critical(this, "Programm", query->lastError().text()); } days->getUi().proteinsEaten->setText("0/" + QString::number(dailyProteinIntake)); days->getUi().calorieEaten->setText("0/" + QString::number(dailyCalorieIntake)); days->getUi().carbohydratesEaten->setText("0/" + QString::number(dailyIntakeOfCarbohydrates)); days->getUi().fatsEaten->setText("0/" + QString::number(dailyIntakeOfFats)); days->getUi().bmiValue->setText("0/" + QString::number(bmi)); } I need to assign some value to my variable using QSqlQuery. The value can be in the database. From there I need to take the value and assign it to my variable. How to do it?
void Registration::introductionDate(QString email, Days *daysArg){ QSqlQuery *query = new QSqlQuery(daysArg->getDataBaseKnowFood()); query->prepare("SELECT dailyCalorieIntake FROM [dbo].[User] WHERE email = :email"); query->bindValue(":email", email); if (!query->exec()) { QMessageBox::critical(this, "Programm", query->lastError().text()); } query->first(); float dailyCalorieIntake = query->value("dailyCalorieIntake").toFloat(); daysArg->getUi().calorieEaten->setText("0/" + QString::number(dailyCalorieIntake)); QSqlQuery *query2 = new QSqlQuery(daysArg->getDataBaseKnowFood()); query2->prepare("SELECT dailyProteinIntake FROM [dbo].[User] WHERE email = :email"); query2->bindValue(":email", email); if (!query2->exec()) { QMessageBox::critical(this, "Programm", query2->lastError().text()); } query2->first(); float dailyProteinIntake = query2->value("dailyProteinIntake").toFloat(); daysArg->getUi().proteinsEaten->setText("0/" + QString::number(dailyProteinIntake)); QSqlQuery *query3 = new QSqlQuery(daysArg->getDataBaseKnowFood()); query3->prepare("SELECT dailyIntakeOfCarbohydrates FROM [dbo].[User] WHERE email = :email"); query3->bindValue(":email", email); if (!query3->exec()) { QMessageBox::critical(this, "Programm", query3->lastError().text()); } query3->first(); float dailyIntakeOfCarbohydrates = query3->value("dailyIntakeOfCarbohydrates").toFloat(); daysArg->getUi().carbohydratesEaten->setText("0/" + QString::number(dailyIntakeOfCarbohydrates)); QSqlQuery *query4 = new QSqlQuery(daysArg->getDataBaseKnowFood()); query4->prepare("SELECT dailyIntakeOfFats FROM [dbo].[User] WHERE email = :email"); query4->bindValue(":email", email); if (!query4->exec()) { QMessageBox::critical(this, "Programm", query4->lastError().text()); } query4->first(); float dailyIntakeOfFats = query4->value("dailyIntakeOfFats").toFloat(); daysArg->getUi().fatsEaten->setText("0/" + QString::number(dailyIntakeOfFats)); QSqlQuery *query5 = new QSqlQuery(daysArg->getDataBaseKnowFood()); query5->prepare("SELECT bmi FROM [dbo].[User] WHERE email = :email"); query5->bindValue(":email", email); if (!query5->exec()) { QMessageBox::critical(this, "Programm", query5->lastError().text()); } query5->first(); float bmi = query5->value("bmi").toFloat(); daysArg->getUi().bmiValue->setText(QString::number(bmi)); QSqlQuery *query6 = new QSqlQuery(daysArg->getDataBaseKnowFood()); query6->prepare("SELECT login FROM [dbo].[User] WHERE email = :email"); query6->bindValue(":email", email); if (!query6->exec()) { QMessageBox::critical(this, "Programm", query6->lastError().text()); } query6->first(); QString login = query6->value("login").toString(); daysArg->getUi().usernameInfo->setText(login); }
70,529,228
70,555,421
Using a user-defined class as template type and using it's non-static data members for decision making. Is it possible?
I have class like this : class B{ public: const char* const getX() const {return X_;} const char* const getY() const {return Y_;} const char* const getZ() const {return Z_;} protected: B(const char* const x, const char* const y, const char* const z) : X_(x), Y_(y), Z_(z) {} private: const char *const X_ = nullptr; const char *const Y_ = nullptr; const char *const Z_ = nullptr; }; class D : public B{ public: D() : B("X","Y","Z") {} }; class D1 : public B{}; //Similar to D Now, I want to use this class/classes as template for functions present in another class : class S { public: template<class T> int S1(some args); }; template<class T> int S::S1(some args) { //Do something based on template non-static member if(T::getX() == "X") //Getting error here -- illegal call of non-static member function {} } Calling this function like below : std::unique_ptr<S> s_ptr; int rval = s_ptr->S1<D>(); Is it possible to achieve this kind of functionality? Better way of doing things? Please help! Thank you.
The idea here was not to go with non-static type but rather I could achieve this by using CRTP. #include <string> class Types {}; template <typename T> class BaseTempl : public Types { public: static std::string A; static std::string B; static std::string C; static std::string D; }; class Derived1 : public BaseTempl<Derived1> { }; template <> std::string BaseTempl<Derived1>::A = "A-Derived1"; template <> std::string BaseTempl<Derived1>::B = "B-Derived1"; template <> std::string BaseTempl<Derived1>::C = "C-Derived1"; template <> std::string BaseTempl<Derived1>::D = "D-Derived1"; class Derived2 : public BaseTempl<Derived2> { }; template <> std::string BaseTempl<Derived2>::A = "A-Derived2"; template <> std::string BaseTempl<Derived2>::B = "B-Derived2"; template <> std::string BaseTempl<Derived2>::C = "C-Derived2"; template <> std::string BaseTempl<Derived2>::D = "D-Derived2"; This allowed me to use polymorphic user-defined-class as template parameters and then use values inside these user-defined-template-type for some decision making.
70,529,499
70,530,947
In-class initialization of vector with size
struct Uct { std::vector<int> vec{10}; }; The code above creates vector that contains single element with value 10. But I need to initialize the vector with size 10 instead. Just like this: std::vector<int> vec(10); How can I do this with in-class initialization?
I think there are 2 aswers: std::vector<int> vec = std::vector<int>(10); as said in the comments and: std::vector<int> vec{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; this is less preferable since it's less readable and harder to adjust later on, but I think it's faster (before c++17) because it doesn't invoke a move constructor as said in the comments. That being said Uct(): vec(10){}; is also a perfectly viable option with the same properties(I think).
70,530,736
70,530,841
C++: How to override method of a specific class with same interface
I have a situation where I need to inherit from two classes with same interface, but to override them separately and I definitely cannot tweak interfaces. See code example below template<typename T> struct Foo { virtual ~Foo() = default; virtual void foo() = 0; }; struct Derived : public Foo<int>, public Foo<double> { #if 0 // having something like this would be great, but unfortunately it doesn't work void Foo<int>::foo() override { std::cout << "Foo<int>::foo()" << std::endl; } void Foo<double>::foo() override { std::cout << "Foo<double>::foo()" << std::endl; } #endif };
You can always define intermediate classes that declare their own interfaces: template<typename T> struct Foo { virtual ~Foo() = default; virtual void foo() = 0; }; struct ProxyFooInt : public Foo<int> { virtual void fooInt() = 0; void foo() override { return fooInt(); } }; struct ProxyFooDouble : public Foo<double> { virtual void fooDouble() = 0; void foo() override { return fooDouble(); } }; struct Derived : public ProxyFooInt, public ProxyFooDouble { void fooInt() override { std::cout << "Foo<int>::foo()" << std::endl; } void fooDouble() override { std::cout << "Foo<double>::foo()" << std::endl; } }; A more advanced solution would be to use CRTP: template<typename D> struct CrtpFooInt : public Foo<int> { void foo() override { return static_cast<D*>(this)->fooInt(); } }; template<typename D> struct CrtpFooDouble : public Foo<double> { void foo() override { return static_cast<D*>(this)->fooDouble(); } }; struct Derived : public CrtpFooInt<Derived>, public CrtpFooDouble<Derived> { void fooInt() { std::cout << "Foo<int>::foo()" << std::endl; } void fooDouble() { std::cout << "Foo<double>::foo()" << std::endl; } };
70,531,120
70,531,706
Generate truly random numbers with C++ (Windows 10 x64)
I am trying to create a password generator. I used the random library, and after reading the documentation, I found out that rand() depends on an algorithm and a seed (srand()) to generate the random number. I tried using the current time as a seed (srand(time(0))), but that is not truly random. Is there a way to generate truly random numbers? Or maybe get the current time very accurately (like, in microseconds)? My platform is Windows 10 x64.
It is true that PCs cannot generate truly random numbers without dedicated hardware, however remember that each PC has at least one hardware random generator attached to it - that device is you, the user sitting in front of the computer. Human is a very random thing. Each one has its own speed of key presses, mouse movement patterns etc. This can be leveraged to your advantage. On Linux you have a special device, /dev/random which uses exactly this. While you work on the PC, it collects random data (not security sensitive of course), such as how fast you tap the keyboard, and in addition hardware related data, such as intervals between interrupts, and some disk IO info. This all generates entropy, which is later used to generate pseudo random data, which is still not 100% random, but is based on much stronger random seed. I am not an expert on Windows, but a quick search shows that Windows provides CryptGenRandom API, with somewhat similar functionality. If you want to generate cryptographically strong random data, I suggest you start from this. Remember, this is still not as strong as dedicated hardware random generator. But this is good enough for most real world use cases.
70,531,728
70,532,033
Transfer data from library to upper level and then back without naming it inbetween
I need to get some complex data from a library then use this data at the upper level. The data consists of 2 parts: while evaluating the data A, i get some additional data B, and the data B should be returned back in the library "as is" in order to not reevaluate it again. So to simplify this: i get data A and data B from the library, transfer both to the upper level, use A, but then i should transfer data B back to the library. The problem is (apart from this weird architecture) i don't want my upper level to know anything about data B, so what mechanism should i use to avoid defining library-specific data types in the upper level code? Data should be passed as a pointer. Im thinking about void*, but C++17 allows to use std::any which i dont understand quite enough. Can i use std::unique_ptr<std::any>? Or is it just std::any instead? Should it be like that? std::any GetDataAandB() { std::unique_ptr ret = std::make_unique<LibraryType>(1, ""); return std::make_any<std::unique_ptr<LibraryType>>( ret); }
How about using LibraryData = std::pair<A, std::any>; // Get aata of type A and B, store B in std::any -> hiding it's type // and return both values, but with B's type hidden LibraryData GetDataAandB() { A someValue; B someValueB_HiddenType; return LibraryData(A, std::any(B)); } // Work with the first part of the Data void ConsumeData(const LibraryData &data) { // return the data to the library callLibrary(data); // or do something with the individual part A const A& dataOfTypeA = data.first; dataOfTypeA.SomeMethod(); // Cannot really do anything with 'B', since its type is hidden const std::any& dataOfUnknownType = data.second; // create a new LibraryData object LibraryData newData(dataOfTypeA, dataOfUnknownType); callLibrary(newData); // Or, in case we can "guess" the type: try { B shouldBeB=std::any_cast<B>(data.second); // do something with B } catch (std::exception &e) { // Nope, it's not of type B. // std::any_cast will throw a bad_any_cast exception } } std::any takes care of any pointers required, so you don't have to add a unique_ptr
70,532,063
70,535,300
Make right wall of a maze in c++
I want to make a maze in C++, however I keep running into a problem with the right outer wall. I was wondering if you guys know a way so I can make the outer wall. Ive been trying to work from up to down using \n, but when \n is used the next symbol just goes to the left wall. Thanks in advance! #include <iostream> #include <vector> #include <stack> /* class Maze { public: void makeMaze(); void Print() const; private: std::vector <std::vector <char>> Maze; }; */ int main(int argc, char* argv[]) { const int WIDTH = 4; const int HEIGHT = 4; /* std::string seedValue = " "; HEIGHT = atoi(argv[1]); WIDTH = atoi(argv[2]); if (argc > 3) { seedValue = argv[3]; } */ // row, column std::vector <std::vector <std::string>> Maze (WIDTH + 1, std::vector<std::string> (HEIGHT + 1)); // Roof for (int column = 0; column < WIDTH; column++) { Maze[0][column] = "+---"; } // Left Wall for (int row = 1; row < HEIGHT + 1; row++) { Maze[row][0] = "|\n+"; } // Floor for (int i = 1; i < WIDTH + 1; i++) { Maze[HEIGHT][i] = "---+"; } // Right Wall // FIXME // Print Maze for (int i = 0; i < Maze.size(); i++) { for (int j = 0; j < Maze.at(0).size(); j++) { std::cout << Maze[i][j]; } std::cout << std::endl; } }
You may want to treat your printable maze as a matrix of chars instead of strings: You can consider each cell of the maze border having a horizontal fill +--- and a vertical fill +|, and a cell_width and cell_height. Your maze would be then defined as a matrix of chars sized maze_height * cell_height + 1 and maze_width * cell_width + 1. That extra one is needed for the right and bottom borders. In order to fill the border, you can define two helper functions, fill_horizontal_border_cell and fill_vertical_border_cell. These functions just copy the contents of the strings horizontal_border_fill and vertical_border_fill respectively to the maze matrix. Finally, you'd need to separately fill the bottom left border corner. All this code should be properly encapsulated into classes (e.g. MazeView for the printable maze, MazeBorderView for the printable maze border, and so on). [Demo] #include <iostream> // cout #include <string> #include <vector> int main(int argc, char* argv[]) { // Border const std::string horizontal_border_fill{"+---"}; const std::string vertical_border_fill{"+|"}; auto cell_width{horizontal_border_fill.size()}; auto cell_height{vertical_border_fill.size()}; // Maze const size_t maze_width = 6; const size_t maze_height = 5; std::vector<std::vector<char>> maze(maze_height * cell_height + 1, std::vector<char>(maze_width * cell_width + 1, ' ')); // + 1 for the right and bottom borders // Fill border auto fill_horizontal_border_cell = [&maze, &horizontal_border_fill, &cell_width, &cell_height](size_t row, size_t col) { row *= cell_height; col *= cell_width; for (auto& c : horizontal_border_fill) { maze[row][col++] = c; } }; auto fill_border_vertical_cell = [&maze, &vertical_border_fill, &cell_width, &cell_height](size_t row, size_t col) { row *= cell_height; col *= cell_width; for (auto& c : vertical_border_fill) { maze[row++][col] = c; } }; for (size_t col{0}; col < maze_width; ++col) { // horizontal borders fill_horizontal_border_cell(0, col); // top fill_horizontal_border_cell(maze_height, col); // bottom } for (size_t row{0}; row < maze_height; ++row) { // vertical borders fill_border_vertical_cell(row, 0); // top fill_border_vertical_cell(row, maze_width); // bottom } maze[maze_height * cell_height][maze_width * cell_width] = horizontal_border_fill[0]; // bottom left border corner // Print maze for (size_t row{0}; row < maze.size(); ++row) { for (size_t col{0}; col < maze[0].size(); ++col) { std::cout << maze[row][col]; } std::cout << "\n"; } } // Outputs: // // +---+---+---+---+---+---+ // | | // + + // | | // + + // | | // + + // | | // + + // | | // +---+---+---+---+---+---+
70,532,083
70,532,313
Generic overflow detection in C++ types
I want to have a generic method that can detect overflows in all types such as char, unsigned char, short, unsigned short, int32, unsigned int32, long, unsigned long, int64, unsigned int64 etc On later C++ we can use __builtin_add_overflow_p to detect the overflow on addition. The macro can be like this #define ADD_OVERFLOW(a, b) __builtin_add_overflow_p (a, b, (__typeof__ ((a) + (b))) 0) The issue is this will not detect overflow in 8bit or 16bit types such as char or short. Need a generic and efficient mechanism to detect the overflow. Efficient means fewer cpu cycles as possible because the check need to be put in many places. Inefficient check can slow down the program. Therefore Efficiency is a must I tried this also #define ADD_OVERFLOW(a, b) ((__typeof__(a))(a + b) < a) It did not work for some signed types eg, int32 Is there a generic solution that works for all types in C++?
__builtin_add_overflow_p does work with 8 and 16 bit types. The problem is that (__typeof__ ((a) + (b))) is int, and it doesn't overflow in int. What you probably want is for a and b to be the same type and to check if the addition overflows in that type: template<typename T> constexpr bool add_overflow(T a, T b) { return __builtin_add_overflow_p(a, b, T{0}); } static_assert(add_overflow((signed char) 125, (signed char) 100)); static_assert(!add_overflow((signed char) 125, (signed char) -3)); // Or if you *must* use a macro: #define ADD_OVERFLOW(a, b) __builtin_add_overflow_p(a, b, \ std::enable_if_t< \ std::is_same_v<std::decay_t<decltype(a)>, std::decay_t<decltype(b)>>, \ std::decay_t<decltype(a)>>{0})
70,532,241
70,532,373
how can i hold pointer object in array?
I'm a newbie. since my code is so long I can't edit it for being reproducible so I will show you what I did in a simple way I have a Team class. I want to hold all my objects in an array so that I can reach them somewhere else and map for some data. so I did a function basically doing this (exactly this part b[1] = a;) int* a; // represent my object int *b = new int[2]; //represent my static object pointer b[1] = a; error saying cant assign int = *int yes absolutely true but I have to hold my object in the array. and I thought this could work but no... is there a way to hold an object in an array or can I say give me space for *int, during pointer initializing?
A better way would be to use std::vector to hold your class objects. The advantage of using a std::vector is that then you won't have to deal with memory management explicitly. vector will take care of it. In addition, i will also recommend using smart pointers. To solve your error above you can use the following example: int i = 0, j = 0;//int objects int* p = &i, *q = &j; //pointer to int objects int **b = new int*[2]; //note i have added * on both the left and right hand side. b[0] = p; b[1] = q; //dont forget to use delete below Note you should use std::vector and smart pointers, but i have added an example so that you can see how to remove the error and use this example as a reference.
70,532,488
70,533,609
What is the best way to return value from promise_type
I'm a bit stuck with coroutines in C++20. My attempt to create an asynchronous task: template <typename T> struct Task { public: struct promise_type { using Handle = std::coroutine_handle<promise_type>; promise_type() = default; ~promise_type() = default; Task get_return_object() { return Task{Handle::from_promise(*this)}; } std::suspend_never initial_suspend() { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_value(T val) noexcept { value_ = val; } void unhandled_exception() { std::cout << "Unhandled exception in coroutine\n"; } T value_; }; explicit Task(typename promise_type::Handle coro) : coro_(coro) {} std::optional<T> Get() { return coro_.done() ? std::make_optional(coro_.promise().value_) : std::nullopt; } private: typename promise_type::Handle coro_; }; Dummy usage example: Task<int> Coro() { co_await std::suspend_never(); co_return 1; } int main() { auto task = Coro(); std::cout << *task.Get(); return 0; } The problem is in Task::Get() method. When I'm trying to get a value from promise_type it is already destroyed. I'm trying to connect Task and promise_type with a pointer, but it looks a bit ugly. I believe there is some standard and simple approach for this. UPDATE: This happens only if the coroutine is not suspended. In this case the promise_type is destroyed before Get() call.
I'm just learning coroutines myself, but I believe that the way to fix this is to change how the Task is destroyed. At the moment, you have final_suspend return std::suspend_never. So control returns immediately to the caller (main) and the promise is destroyed. In that case, you have to do something like this: I'm trying to connect Task and promise_type with a pointer, but it looks a bit ugly Basically so that the promise can write its return_value into the Task. But we could do it a little bit differently. You could always suspend: std::suspend_always final_suspend() noexcept { return {}; } And ensure that the Task itself destroys the coroutine: ~Task() { if (coro_) coro_.destroy(); } This way, the promise isn't destroyed until task is destroyed, which means that task.Get() isn't accessing a dangling... coroutine. You can see the difference here.
70,532,514
70,532,802
Undefined reference to a virtual function
booking.h #ifndef _BOOKING_H_ #define _BOOKING_H_ #include <string> class Event { private: std::string event_option; public: Event(std::string event_option); virtual ~Event(); void list_specific_event_details(); virtual void list_details(); }; class Films : public Event { private: std::string movie_option; public: Films(std::string movie_option); void list_details(); }; class Live_Music : public Event { private: std::string live_music_option; public: Live_Music(std::string live_music_option); void list_details(); }; class Standup_Comedy : public Event { private: std::string comedy_option; public: Standup_Comedy(std::string comedy_option); void list_details(); }; #endif booking.cpp #include "booking.h" #include <string> Event::Event(std::string event_option) { this->event_option = event_option; } Event::~Event() { } void Event::list_specific_event_details() { return list_details(); } Films::Films(std::string movie_option) : Event("Films") { this->movie_option = movie_option; } void Films::list_details() { //some code ... return; } Live_Music::Live_Music(std::string live_music_option) : Event("Live_Music") { this->live_music_option = live_music_option; } void Live_Music::list_details() { //some code... return; } Standup_Comedy::Standup_Comedy(std::string comedy_option) : Event("Standup_Comedy") { this->comedy_option = comedy_option; } void Standup_Comedy::list_details() { //some code... return; } main.cpp #include "booking.h" #include <iostream> #include <vector> #include <string> int main() { std::vector <Event *> choice; choice.push_back(new Films("f")); choice.push_back(new Live_Music("l")); choice.push_back(new Standup_Comedy("s")); for(unsigned i = 0; i < choice.size(); i++) { choice[i] -> list_specific_event_details(); } for (Event * e: choice) delete e; choice.clear(); } I have written the above block of codes and got an error when I tried to compile it. The error is as follows: usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: /tmp/ccuWXzBM.o:booking.cpp:(.rdata$_ZTV5Event[_ZTV5Event]+0x20): undefined reference to `Event::list_details()' collect2: error: ld returned 1 exit status Why am I getting this error, and how can I solve it?
You have not defined your method Event::list_details(). If you only want to declare the function but do not want to implement it, that is what is called an Interface, you can make it a pure virtual method with: class Event { ... virtual void list_details() = 0; ... };
70,532,706
70,533,674
Is there any difference in passing &arr(address of entire block) or just passing name of array (address of first element)?
void func1(int* ptr) { printf("func1 :%d\n",++ptr); } int main() { int arr[4] = {0,1,2,3}; printf("Addr enter code here`f arr: %d\n",arr); func1(arr); // first way: func1(&arr); // second way: How this will be different from func1(arr). }
The difference between &arr and arr is that the type of former is a pointer to an array int (*)[4], and the type of latter is an array int[4] which can decay to pointer to the first element int*. Both the pointer to the array, and the decayed pointer to the first element point to the same address because the first byte of the array is also the first byte of the first element of the array. The difference between func1(&arr) and func1(arr) is that former is ill-formed because int (*)[4] doesn't implicitly convert to int*. In order to be able to call func1(&arr), you would have to accept a pointer of correct type: void func1(int (*ptr)[4]) printf("func1 :%d\n",++ptr); printf("Addr enter code here`f arr: %d\n",arr); Both of these calls result in undefined behaviour. The type of the variadic argument must match the type required by the format specifier. You used the format specifier %d which requires the argument to be of type int (or similar). The type of the (decayed) argument here is int* which isn't int.
70,532,839
70,533,181
Discrepancy in result of Intrinsics vs Naive Vector reduction
I have been comparing the run times of Intrinsics vector reduction, naive vector reduction and vector reduction using openmp pragmas. However, I found the result to be different in these scenarios. The code is as follows - (intrinsics vector reduction taken from - Fastest way to do horizontal SSE vector sum (or other reduction)) #include <iostream> #include <chrono> #include <vector> #include <numeric> #include <algorithm> #include <immintrin.h> inline float hsum_ps_sse3(__m128 v) { __m128 shuf = _mm_movehdup_ps(v); // broadcast elements 3,1 to 2,0 __m128 sums = _mm_add_ps(v, shuf); shuf = _mm_movehl_ps(shuf, sums); // high half -> low half sums = _mm_add_ss(sums, shuf); return _mm_cvtss_f32(sums); } float hsum256_ps_avx(__m256 v) { __m128 vlow = _mm256_castps256_ps128(v); __m128 vhigh = _mm256_extractf128_ps(v, 1); // high 128 vlow = _mm_add_ps(vlow, vhigh); // add the low 128 return hsum_ps_sse3(vlow); // and inline the sse3 version, which is optimal for AVX // (no wasted instructions, and all of them are the 4B minimum) } void reduceVector_Naive(std::vector<float> values){ float result = 0; for(int i=0; i<int(1e8); i++){ result += values.at(i); } printf("Reduction Naive = %f \n", result); } void reduceVector_openmp(std::vector<float> values){ float result = 0; #pragma omp simd reduction(+: result) for(int i=0; i<int(1e8); i++){ result += values.at(i); } printf("Reduction OpenMP = %f \n", result); } void reduceVector_intrinsics(std::vector<float> values){ float result = 0; float* data_ptr = values.data(); for(int i=0; i<1e8; i+=8){ result += hsum256_ps_avx(_mm256_loadu_ps(data_ptr + i)); } printf("Reduction Intrinsics = %f \n", result); } int main(){ std::vector<float> values; for(int i=0; i<1e8; i++){ values.push_back(1); } reduceVector_Naive(values); reduceVector_openmp(values); reduceVector_intrinsics(values); // The result should be 1e8 in each case } However, my output is as follows - Reduction Naive = 16777216.000000 Reduction OpenMP = 16777216.000000 Reduction Intrinsics = 100000000.000000 As it can be seen, only Intrinsic functions calculated it correctly and others are faced with precision issues. I am fully aware of the precision issues one might face using float due to rounding off, so my question is, why did the intrinsics get the answer correct even though it too in fact is floating value arithmetic. I am compiling it as - g++ -mavx2 -march=native -O3 -fopenmp main.cpp Tried with version 7.5.0 as well as 10.3.0 TIA
Naïve loop adds by 1.0, and it stops adding at 16777216.000000, since there's not enough significant digits in binary32 float. See this Q&A: Why does a float variable stop incrementing at 16777216 in C#? When you add computed horizontal sum, it will add by 8.0, so the number since when it will stop adding is about 16777216*8 = 134217728, you just don't reach it in your experiment.
70,532,961
70,533,006
Comparison of two Character Arrays in C++ using Comparison Operator
How does the comparison operator work when doing a comparison between two character arrays? Consider the following program, #include <iostream> using namespace std; int main() { char arr1[5] = { 'T','e','s','t' }; char arr2[10] = { 't','e' }; if (arr1 < arr2) cout << "Yes"; else if (arr1 > arr2) cout << "No"; else cout << "0"; } The way I know is it should print Yes because the first character of arr1 has an ASCII value of 84 while the ASCII value of first character of arr2 is 116so technically it should print Yes. However, this program gives the output of No when run on Visual Studio. I thought that it might be comparing the addresses of character arrays. To test this, I swapped the variable names and ran this program, #include <iostream> using namespace std; int main() { char arr2[5] = { 'T','e','s','t' }; char arr1[10] = { 't','e' }; if (arr1 < arr2) cout << "Yes"; else if (arr1 > arr2) cout << "No"; else cout << "0"; } But this again gave Yes as output, meaning the addresses of character arrays did not matter in the comparison. Can anyone tell how is this comparison being done?
In the condition of the if statement if (arr1 < arr2) the both arrays are implicitly converted to pointers to their first elements and these addresses are compared that results in undefined behavior for the operator <. Pay attention to if you will compare string literals like if ( "Hello" == "Hello" ) //... then the value of the expression can be either true or false dependent on compiler options: whether identical string literals are stored as one string literal or as separate string literals. As for the comparison of character arrays that do not contain strings then you can use the standard algorithm std::lexicographical_compare. Otherwise if character arrays contain strings as in your example then you can use the standard C string function strcmp. Here is a demonstration program #include <iostream> #include <algorithm> #include <cstring> int main() { char arr1[5] = { 'T','e','s','t' }; char arr2[10] = { 't','e' }; if (std::lexicographical_compare( arr1, arr1 + 4, arr2, arr2 + 2 )) { std::cout << "The array arr1 is less than the array arr2\n"; } if ( std::strcmp( arr1, arr2 ) < 0 ) { std::cout << "The array arr1 is less than the array arr2\n"; } } The program output is The array arr1 is less than the array arr2 The array arr1 is less than the array arr2
70,533,382
70,533,616
Questions about CUDA macro __CUDA_ARCH__
I have a simple cuda code in ttt.cu #include <iostream> __global__ void example(){ printf("__CUDA_ARCH__: %d \n", __CUDA_ARCH__); } int main(){ example<<<1,1>>>(); } with CMakeLists.txt: cmake_minimum_required(VERSION 3.18) project(Hello) find_package(CUDA REQUIRED) cuda_add_executable(sss ttt.cu) Then I got the error: identifier "__CUDA_ARCH__" is undefined. I would like to know why does this happen and what should I do for making the __CUDA_ARCH__ valid? And can we use valid __CUDA_ARCH__ in host code within a header .h file? Update: I intended to use the following cmake for generating a 750 cuda arch, however, this always results in a __CUDA_ARCH__ = 300 (2080 ti with cuda 10.1). I tried both set_property and target_compile_options, which all failed. cmake_minimum_required(VERSION 3.18) project(Hello) find_package(CUDA REQUIRED) cuda_add_executable(oounne ttt.cu) set_property(TARGET oounne PROPERTY CUDA_ARCHITECTURES 75) #target_compile_options(oounne PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-gencode arch=compute_75,code=sm_75>)
__CUDA_ARCH__ is a compiler macro. can we use valid __CUDA_ARCH__ in host code No, it is intended to be used in device code only: The host code (the non-GPU code) must not depend on it. You cannot print a compiler macro the way you are imagining. It is not an ordinary numerical variable defined in C++. You could do something like this but that would print at compile-time, not at run-time. To print at run-time, you could do something like this: $ cat t2.cu #include <cstdio> #define STR_HELPER(x) #x #define STR(x) STR_HELPER(x) __device__ void print_arch(){ const char my_compile_time_arch[] = STR(__CUDA_ARCH__); printf("__CUDA_ARCH__: %s\n", my_compile_time_arch); } __global__ void example() { print_arch(); } int main(){ example<<<1,1>>>(); cudaDeviceSynchronize(); } $ nvcc -o t2 t2.cu $ ./t2 __CUDA_ARCH__: 520 $ Note that there are quite a few questions here on the cuda tag discussing __CUDA_ARCH__, you may wish to review some of them.
70,533,459
70,533,890
C++ n-arry tree with different elements
I want to build a n-arry tree from a document. For that i have 3 different types of elements for the tree: Struct Nodes Have a name can contain other Nodes Depth Element Node (Leaf of the tree) Have a Key Have a value Depth Element Template Node (Leaf of the tree) Have a placeholder which should be resolved later in the program Depth At the moment i think about something like this: class Node { public: Node(int depth); int depth() const; private: int depth_; }; class StructNode : public Node { ... private: std::vector<std::unique_ptr<Node>> children; }; class ElementNode : public Node { ... }; class ElementTemplateNode : public Node { ... }; The Tree will be generated from an File on Startup and reused to create an output string like this: Structname: key = value key = value Structname: key = value Structname: key = value ... Where the Key and value where directly read from the ElementNode or read from another file with the value of the placeholder inside the ElementTemplateNode Is there maybe a better Structure for the Tree? Because with the current one i have to check first if its a StructNode, ElementNode or ElementTemplateNode
This is a typical structure for implementing a tree with different kind of nodes. Another variant would be the composite pattern. The problem that you describe, is usually caused by asking the nodes about what they know, instead of telling them what to do. If you'd do it the other way round (tell, don't ask), you could get rid of those checks and benefit from polymorphism. The different kind of nodes inherit from Node. You could design your tree using a uniform interface, with virtual functions defined for Node which then can be overridden for the different types of nodes. Calling the method would then do the right things, without need for a manual type check. For generating the output string, you'd tell the root node to generate a string. If it's a structure, it would add the heading and tell its children to generate a string, but if it's a leaf it would just add the key/value pair to the string. No need from outside to know anything about each node. If the operation of exploring the tree shall not be implemented by the tree itself, the usual approach is to use a visitor pattern. The big advantage is that you write the vistor once, and it's then easy to specialize a new kind of visitor for different algorithms. Again, no need to check the type of the nodes. The pattern makes sure that the right elementary function is called for the right type of node.
70,534,022
70,535,436
SWIG Python C++ struct as in/out parameter
Honestly I read and re-read a lot of post on this site regarding to the struct theme. But I need your help. I have C-style structures struct Time { uint16_t year; // year with four digits like 2016 uint8_t month; // 1 .. 12 uint8_t day; // 1 .. 31 uint8_t hour; // 0 .. 23, 24 hour representation uint8_t minute; // 0 .. 59 uint8_t second; // 0 .. 59 }; and class with member function, which implementation is in DLL. class DeviceInterface { virtual uint32_t getTime(Time& time) = 0; }; where uint32_t value is a status code. And here is auto generated SWIG C++ code: SWIGINTERN PyObject *_wrap_getTime(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; DeviceInterface *arg1 = (DeviceInterface *) 0 ; Time *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject *swig_obj[2] ; uint32_t result; if (!SWIG_Python_UnpackTuple(args, "getTime", 2, 2, swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_DeviceInterface, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getTime" "', argument " "1"" of type '" "DeviceInterface *""'"); } arg1 = reinterpret_cast< DeviceInterface * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_Time, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "getTime" "', argument " "2"" of type '" "Time &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "getTime" "', argument " "2"" of type '" "Time &""'"); } arg2 = reinterpret_cast< Time * >(argp2); result = (uint32_t)(arg1)->getTime(*arg2); resultobj = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result)); return resultobj; fail: return NULL; } From code above I don't see what time value, i.e arg2 variable, somehow has been returned. So what I need to write in SWIG interface file to get both status code and time?
You can write a typemap to append the Time output argument. SWIG generates a proxy for the structure that can be generated as needed via SWIG_NewPointerObj(). Full example below: DeviceInterface.h (minimal implementation) #include <stdint.h> struct Time { uint16_t year; // year with four digits like 2016 uint8_t month; // 1 .. 12 uint8_t day; // 1 .. 31 uint8_t hour; // 0 .. 23, 24 hour representation uint8_t minute; // 0 .. 59 uint8_t second; // 0 .. 59 }; class DeviceInterface { public: virtual uint32_t getTime(Time& time) { time.year = 2021; time.month = 12; time.day = 30; time.hour = 9; time.minute = 47; time.second = 30; return 0; } }; test.i %module test %{ #include "DeviceInterface.h" %} %include <stdint.i> // Do not require an input parameter for Time. // Instead, SWIG will allocate one. %typemap(in,numinputs=0) Time& %{ $1 = new Time; %} // After calling the function, process Time as an output. // Convert the allocated pointer to a SWIG Python wrapper // and pass ownership to Python. Python will free the object // when it goes out of scope. %typemap(argout) Time& (PyObject* tmp) %{ // Convert C pointer to SWIG Python wrapper tmp = SWIG_NewPointerObj($1, $1_descriptor, SWIG_POINTER_OWN); // Append to existing uint32_t return value $result = SWIG_Python_AppendOutput($result, tmp); %} %include "DeviceInterface.h" Demo: >>> import test >>> d=test.DeviceInterface() >>> r=d.getTime() >>> r [0, <test.Time; proxy of <Swig Object of type 'Time *' at 0x000001ED4F866090> >] >>> r[1].year 2021 >>> r[1].month 12 If you want to customize the display of the SWIG wrapper for Time to be more human-readable, you can extend the Time object using the following: %module test %{ // Added to support the __repr__ implementation #include <string> #include <sstream> #include "DeviceInterface.h" %} %include <stdint.i> %include <std_string.i> // SWIG support for std::string. %typemap(in,numinputs=0) Time& %{ $1 = new Time; %} %typemap(argout) Time& (PyObject* tmp) %{ tmp = SWIG_NewPointerObj($1, $1_descriptor, SWIG_POINTER_OWN); $result = SWIG_Python_AppendOutput($result, tmp); %} // Extend time to suport Python's __repr__. // It must return a string representing how to display the object in Python. %extend Time { std::string __repr__() { std::ostringstream ss; ss << "Time(year=" << $self->year << ", month=" << (unsigned)$self->month << ", day=" << (unsigned)$self->day << ", hour=" << (unsigned)$self->hour << ", minute=" << (unsigned)$self->minute << ", second=" << (unsigned)$self->second << ")"; return ss.str(); } } %include "DeviceInterface.h" Demo: >>> import test >>> d=test.DeviceInterface() >>> r=d.getTime() >>> r [0, Time(year=2021, month=12, day=30, hour=9, minute=47, second=30)]
70,534,521
70,534,554
getting None instead of a integer value
I am calling c++ code from python and I was wondering why I am not getting an integer value back from my function which returns an int. I keep getting None in python. This is my c++ code: #include <wiringPi.h> #include <wiringPiI2C.h> #include <chrono> #include <iostream> #include <thread> #include <unistd.h> using namespace std; class Ultrasonic { public: int returnDistance() { int fd; fd=wiringPiI2CSetup(0x70) ;//i2c addres //unsigned char arr[2]={00,0x51};//register port and command int data; wiringPiI2CWriteReg8(fd,00, 81); sleep(1); data = wiringPiI2CReadReg8(fd,3); cout << "datatype of data is: " << typeid(data).name() << endl; return data; } }; int main(){ Ultrasonic ultrasonic; ultrasonic.returnDistance(); return 0; } extern "C" { Ultrasonic* Ultrasonic_new(){ return new Ultrasonic(); } int Ultrasonic_returnDistance(Ultrasonic* ultrasonic){ return ultrasonic -> returnDistance(); } } This is my python code: # import the modules from base64 import encode from ctypes import cdll import socket, time lib3 = cdll.LoadLibrary('./libUltra.so') class Ultrasonic(object): # constructor def __init__(self): # attribute self.obj = lib3.Ultrasonic_new() def returnDistance(self): lib3.Ultrasonic_returnDistance(self.obj) ultra = Ultrasonic() print(type(ultra)) print(type(ultra.returnDistance())) This is the output I get: <class 'main.Ultrasonic'> datatype of data is: i (which stands for integer) <type 'NoneType'> (should be integer) If it matters, I am using these commands: g++ -c -fPIC ultra.cpp -o ultra.o -lwiringPi g++ -shared -Wl,-soname,libUltra.so -o libUltra.so ultra.o -lwiringPi
Fix your Python returnDistance function to return the value: def returnDistance(self): return lib3.Ultrasonic_returnDistance(self.obj)
70,534,577
70,667,842
Specify the cuda architecture by using cmake for cuda compilation
I have the following cmake and cuda code for generating a 750 cuda arch, however, this always results in a CUDA_ARCH = 300 (2080 ti with cuda 10.1). I tried both set_property and target_compile_options, which all failed. Do we have a solution for both cuda_add_executable and cuda_add_library in this case to make the -gencode part effective? cmake_minimum_required(VERSION 3.18) project(Hello) find_package(CUDA REQUIRED) cuda_add_executable(oounne ttt.cu) set_property(TARGET oounne PROPERTY CUDA_ARCHITECTURES 75) #target_compile_options(oounne PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-gencode arch=compute_75,code=sm_75>) #include <cstdio> #define STR_HELPER(x) #x #define STR(x) STR_HELPER(x) __device__ void print_arch(){ const char my_compile_time_arch[] = STR(__CUDA_ARCH__); printf("__CUDA_ARCH__: %s\n", my_compile_time_arch); } __global__ void example() { print_arch(); } int main(){ example<<<1,1>>>(); cudaDeviceSynchronize(); }
Change my comment to an answer: project(Hello CUDA) enable_language(CUDA) set_property(TARGET oounne PROPERTY CUDA_ARCHITECTURES 75)
70,534,894
70,534,910
vector as an argument for recursive function in c++
I want to have function like one in the title, but when I declare it like this, void function(vector<int> tab, int n) { if(n > 0) { tab.push_back(n); function(tab, n - 1); } } it isn't working, because tab is still blank.
You're taking tab by value - each recursive call will operate on a new copy of tab. You'll want to pass tab by reference: void function(std::vector<int>& tab, int n) { ... }
70,535,405
70,535,555
initialisation of atomic init
So in my code there is the snippet: std::atomic<uint>* atomic_buffer = reinterpret_cast<std::atomic<uint>*>(data); const size_t num_atomic_elements = svm_data_size / sizeof(std::atomic<uint>); for (i = 0; i < num_atomic_elements; i++) { std::atomic_init(&atomic_buffer[i], std::atomic<uint>(0)); } However, on execution, the error returned is: error: no matching function for call to 'atomic_init' ... note: candidate template ignored: deduced conflicting types for parameter '_Tp' ('unsigned int' vs. 'int') atomic_init(volatile atomic<_Tp>* __o, _Tp __d) _NOEXCEPT Any one had a similar issue? Cheers.
In your code it appears that you're trying to create std::atomic<uint> objects out of "raw memory". If that's the case then you need to use placement new to begin the lifetime of such an object before using it. Also, &atomic_buffer[i] can be spelled atomic_buffer + i. So your code should be: new (atomic_buffer + i) std::atomic<uint>(0); The std::atomic_init function should only be used on default-constructed std::atomic<T> objects, and is completely unnecessary as of C++20. (Even if you don't have C++20 yet, you can already stop using std::atomic_init. Just remember to always give std::atomic<T> objects an explicit value upon construction. This will ensure that your code won't change behaviour in C++20.)
70,535,429
70,535,464
Can a using declaration refer only to a specific overload based on const qualification?
If the base class has both const and non-const version of a function, can I refer to only one or the other in the derived class by the using keyword? struct Base { protected: int x = 1; const int& getX() const {return x;} int& getX() {return x;} }; struct Derived : public Base { public: using Base::getX; // Can we refer to the const or the non-const only? }; If no, whats the simplest way to make const getX() public in Derived without repeating the function body?
using always brings the entire overload set for the given name with it. You cannot invoke using for a particular function, only for its name, which includes all uses of that name. You will have to write a derived-class version of the function, with your preferred signature, that calls the base class. The simplest way would be with decltype(auto) getX() const { return Base::getX(); }.
70,535,616
70,535,798
What's the special value of `co_yield` in contrast to a simple stateful lambda in C++20?
From the well-known C++ coroutine library (search "Don't allow any use of co_await inside the generator coroutine." in the source file generator.hpp), and from my own experiments, I know that a coroutine using co_yield cannot use co_await meanwhile. Since a generator using co_yield must be synchronous, then, what's the advantage of using co_yield over a simple stateful lambda? For example: #include <iostream> generator<int> g() { for (auto i = 0; i < 9; ++i) { co_yield i; } } int main() { auto fn_gen = [i = 0] mutable { return i++; }; // Lambda way for (auto i = 0; i < 9; ++i) { std::cout << fn_gen() << std::endl; } // co_yield way for (auto i : g()) { std::cout << i << std::endl; } } What's the special value of co_yield in contrast to a simple stateful lambda in C++20? Please See the Updated MWE: https://godbolt.org/z/x1Yoen7Ys In the updated example, the output is totally unexpected when using co_await and co_yield in the same coroutine.
For trivial generators with minimal internal state and code, a small functor or lambda is fine. But as your generator code becomes more complex and requires more state, it becomes less fine. You have to stick more members in your functor type or your lambda specifier. You have bigger and bigger code inside of the function. Etc. At the most extreme, a co_yield-based generator can hide all of its implementation details from the outside world, simply by putting its definition in a .cpp file. A stateful functor cannot hide its internal state, as its state are members of the type, which the outside world must see. The only way to avoid that is through type-erasure, such as with something like std::function. At which point, you've gained basically nothing over just using co_yield. Also, co_await can be used with co_yield. Cppcoro's generator type explicitly hoses it, but cppcoro isn't C++20. You can write whatever generator you want, and that generator can support uses of co_await for specific purposes. Indeed, you can make asynchronous generators, where sometimes you can yield a value immediately, and sometimes you can schedule the availability of a value with some asynchronous process. The code invoking your async generator can co_await on it to extract values from it, rather than treating it like a functor or an iterator pair.
70,535,707
70,535,783
C++ using template type with unordered map
I am new to C++ so this is likely a simple mistake but this code is giving me problems for hours now. I am really just not sure what to try next. EratosthenesHashMap.h #pragma once #include <unordered_map> #include <boost/functional/hash.hpp> #include "SieveOfEratosthenes.h" template<class T> class EratosthenesHashMap { public: EratosthenesHashMap(SieveOfEratosthenes& sieve); ~EratosthenesHashMap(); unsigned int addValue(T& value); unsigned int getPrime(T& value) const; private: SieveOfEratosthenes *sieve; std::unordered_map<T, unsigned int, boost::hash<T>> valueMap; }; EratosthenesHashMap.cpp #include "EratosthenesHashMap.h" EratosthenesHashMap<class T>::EratosthenesHashMap(SieveOfEratosthenes& sieve) { this->sieve = &sieve; }; unsigned int EratosthenesHashMap<T>::addValue(T& value) { return 0; } unsigned int EratosthenesHashMap<T>::getPrime(T& value) const { return 0; } Error: EratosthenesHashMap.cpp 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\utility(331,10): error C2079: 'std::pair<const T,unsigned int>::first' uses undefined class 'T' 1> with 1> [ 1> T=T 1> ] 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xhash(305): message : see reference to class template instantiation 'std::pair<const T,unsigned int>' being compiled 1> with 1> [ 1> T=T 1> ] 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xhash(304): message : while compiling class template member function 'void std::_Hash_vec<std::allocator<std::_List_unchecked_iterator<std::_List_val<std::_List_simple_types<_Ty>>>>>::_Tidy(void) noexcept' 1> with 1> [ 1> _Ty=std::pair<const T,unsigned int> 1> ] 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xhash(313): message : see reference to function template instantiation 'void std::_Hash_vec<std::allocator<std::_List_unchecked_iterator<std::_List_val<std::_List_simple_types<_Ty>>>>>::_Tidy(void) noexcept' being compiled 1> with 1> [ 1> _Ty=std::pair<const T,unsigned int> 1> ] 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xhash(1933): message : see reference to class template instantiation 'std::_Hash_vec<std::allocator<std::_List_unchecked_iterator<std::_List_val<std::_List_simple_types<_Ty>>>>>' being compiled 1> with 1> [ 1> _Ty=std::pair<const T,unsigned int> 1> ] 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\unordered_map(69): message : see reference to class template instantiation 'std::_Hash<std::_Umap_traits<_Kty,_Ty,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>>' being compiled 1> with 1> [ 1> _Kty=T, 1> _Ty=unsigned int, 1> _Hasher=boost::hash<T>, 1> _Keyeq=std::equal_to<T>, 1> _Alloc=std::allocator<std::pair<const T,unsigned int>> 1> ] 1>C:\Users\jpsie\source\repos\EratosthenesContainer\EratosthenesContainer\EratosthenesHashMap.h(20): message : see reference to class template instantiation 'std::unordered_map<T,unsigned int,boost::hash<T>,std::equal_to<T>,std::allocator<std::pair<const T,unsigned int>>>' being compiled 1> with 1> [ 1> T=T 1> ] I am trying to create a hashmap as a member variable with key type T, value type unsigned int, and I am using the boost library for a hash function.
It is rather difficult to have a template class split between header file and .cpp file and be easy to consume by callers. Instead, inline your entire template class in EratosthenesHashMap.h: template<class T> class EratosthenesHashMap { public: EratosthenesHashMap(SieveOfEratosthenes& sieve) { this->sieve = &sieve; } ~EratosthenesHashMap() { } unsigned int addValue(T& value) { return 0; } unsigned int getPrime(T& value) const { return 0; } private: SieveOfEratosthenes* sieve; std::unordered_map<T, unsigned int, boost::hash<T>> valueMap; };
70,536,066
70,536,155
c++ 2D vector(matrix) how to delete the nth row?
Here is the 2d vector [[1,3],[2,6],[8,10],[15,18]] I want to delete the 2nd row which is [2,6] I tried following to erase the 1st row matrix[1].erase(intervals[1].begin(),intervals[1].end()); after erasing the row when I printed the matrix, I got [[1,3],[],[8,10],[15,18]] I wanted to remove the brackets also, how to do that?
From what you showed, I believe the correct code would be matrix.erase( matrix.begin()+1 );
70,536,235
70,536,365
What is wrong with my C++ heap implementation?
I am trying to implement a heap structure for an online judge. I am very happy with the implementation, it stands all of my test cases, but the online judge rejects it. The insert function appends the new element and then bubbles it up the binary tree. The removeMax function replaces the greatest element with the last in the vetor and then bubbles it down. vector<int> heap; int getMax(){ return heap[0]; } int getSize(){ return heap.size(); } void insert(int element){ heap.push_back(element); int i = heap.size() - 1; while(element > heap[i / 2]) { swap(heap[i], heap[i / 2]); i = i / 2; } } void removeMax(){ heap[0] = heap[heap.size() - 1]; heap.pop_back(); int i = 0; int iGreater = heap[i * 2] > heap[i * 2 + 1] ? i * 2 : i * 2 + 1; while(i < heap.size() && heap[i] < heap[iGreater]) { swap(heap[i], heap[iGreater]); i = iGreater; iGreater = heap[i * 2] > heap[i * 2 + 1] ? i * 2 : i * 2 + 1; } }
You are using the heap equations: parent of node i is node i/2 children of node i are nodes 2*i and 2*i + 1 which only works if you use 1-based array indexing (index 1 is the first element of the array) But C++ uses 0-based indexing for vectors (and arrays), so this doesn't work. You need parent of node i is node (i-1)/2 children of node i are nodes 2*i + 1 and 2*i + 2 Your ending condition for removeMax is also wrong, causing you to run off the end of the vector and get undefined behavior.
70,536,337
70,549,910
C++ FMT issue formatting a custom abstract class
I'm working on an events system for a personal project and I'm trying to make the events be logged to a console as easy as LOG(event). In this case, events are defined by an Event class which has some methods and a virtual ToString() function that returns a string with the event info and whatever I like to output on each event. This class is expanded further by defining specific event classes that inherit from Event class and that define the ToString() function according to what each event does and what variables it has. So my LOG macro calls a static Log class' function to display the message in a console by converting the arguments into a string, like this: #define LOG(...) Log::DisplayLog(LogUtils::StringFromArgs(__VA_ARGS__)) It's done like this because DisplayLog() receives also other info parameters that are not important for my problem. The LogUtils::StringFromArgs() function converts the arguments to a string using fmt by doing the next: template<typename FormatString, typename... Args> inline std::string StringFromArgs(const FormatString& fmt, const Args &... args) { char arg_string[1024]; memset(arg_string, 0, sizeof(arg_string)); fmt::format_to(arg_string, fmt, args...); return std::string(arg_string); } So, as I use fmt for this, I thought that making the log of an event as I want it would be easy, following the fmt guidelines, the idea was to set a formatter for the event class: template<typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of<Event, T>::value, char>> : fmt::formatter<std::string> { template<typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template<typename FormatCtx> auto format(const T& event, FormatCtx& ctx) // also tried Event& instead of T& { return fmt::format_to(ctx.out(), "{0}", event.ToString()); // also tried: //return fmt::formatter<std::string>::format(event.ToString(), ctx); } }; However, this is not working, when I try to do LOG(event) of a specific event class (let's say "event" is WindowResizedEvent inheriting from Event class) I keep having the same error from fmt because it can't format the event (also I tried to add a const char*() operator in the Event class and still the same): The "Argument 2" is the "event" argument (as I said I have some other arguments in the middle that aren't important on this problem). Does anyone knows how can I get to format this without specifying a formatter for each type of event class? Because it would be always the same code for each event type.
The format string should be passed as fmt::format_string and not as a template parameter. Here's a working example (https://godbolt.org/z/xYehaMWsG): #include <fmt/format.h> struct Event { virtual std::string ToString() const = 0; }; struct MyEvent : Event { std::string ToString() const override { return "foo"; } }; template<typename T> struct fmt::formatter< T, std::enable_if_t<std::is_base_of<Event, T>::value, char>> : fmt::formatter<std::string> { auto format(const T& event, fmt::format_context& ctx) { return fmt::format_to(ctx.out(), "{}", event.ToString()); } }; #define LOG(...) fmt::print("{}", StringFromArgs(__VA_ARGS__)) template <typename... T> std::string StringFromArgs(fmt::format_string<T...> fmt, T&&... args) { return fmt::format(fmt, std::forward<T>(args)...); } int main() { LOG("{}", MyEvent()); } Note that it's better to use fmt::format instead of fmt::format_to if you are formatting to a string. In fact you can replace StringFromArgs with fmt::format.
70,536,361
70,536,599
Why does my hashing program fail the tests
Task: To register in the system, each resident must come up with a password. The password consists of letters of the Latin alphabet (uppercase and lowercase), as well as numbers from 0 to 9, that is, it is possible to use 62 characters in total. The password length is from 5 to 20 characters. The password is stored in the database in encrypted form, encryption is carried out according to the following algorithm: The number b of uppercase Latin letters is counted. For each uppercase letter character in the password, a cyclic shift to the right by bb characters is performed (for example, if b=3, then the D character is converted to the G character, the Y character to the B character). Similarly, for each lowercase character in the password, a cyclic shift to the right is performed by m characters, where m is the number of lowercase letters in the password. To quickly search for users in the database, a hash function is calculated for each encrypted password using the following algorithm: All 62 characters are ordered, numbers come first, then lowercase letters, then uppercase letters. Each character is assigned a code - the number of the character in this sequence, starting from 0. Thus, the digit codes match their values, the lowercase letter code a-10, b-11, etc. All codes are summed up, and the remainder of the resulting sum s is found from dividing by the numbers p and q. The resulting pair of numbers (s mod p,s mod q) will be the value of the hash function. A hash function is considered good if collisions rarely occur, that is, the values of the function match for different passwords. John came up with a new password. At the same time, there are already nn passwords in the database, and I would like to avoid collisions. Will John succeed? Input data The first line contains a string representing John's password. The second line contains an integer n – the number of passwords in the database. The third line contains integers p and q. The following lines store passwords in unencrypted form. Output data An integer is the number of passwords whose hash function matches the hash function of John's password. Sample Input: AabB1cd 5 13 17 Nik143pasw qeAom1 q1w2e3r4t aBoba2012 N33iEj Sample Output: 2 Note: Passwords that match John's hash function are highlighted. Processing of John's password: After cyclic shift: CefD1gh (uppercase letters are shifted by 2, lowercase by 4) The sum of the character codes is 38+14+15+39+1+16+17=140 The hash function is equal to (10,4)
You have a few logic problems in your code. When you are rotating your upper and lower-case characters to their "encrypted" forms, you iterate through the password twice, and sometimes incorrectly rotate the characters. Take for example just the line if (pas[i] + big >= 'A' && pas[i] + big <= 'Z') pas[i] = pas[i] + big; Consider the case where pas[i] == '9' and big == 8. You will end up transforming all of your 9's into As. Now consider the line in the next loop if (pas[i] + small >= 'a' && pas[i] + small <= 'z') pas[i] = pas[i] + small; Which will similarly transform some upper-case letters into lower-case if small is large enough. You can also combine these two problems. Consider the case where pas[i] is originally Y, big is 1, little is 7. You'll transform Y --> Z, and then in the next step transform Z --> a. Compartmentalize and abstract your single large main function into smaller functional blocks. This will allow you to reason about each piece individually instead of trying to keep the entirely of main() in your head. Humans have limited short-term memory. Some suggested functions would include bool is_upper(char c) bool is_lower(char c) bool is_numeric(char c) char rotate_upper(char c, int steps) char rotate_lower(char c, int steps) Instead of looping through the password twice on your transformation step, consider looping through the password once. If the character is upper-case, transform accordingly. If it's lower-case, transform accordingly. This will prevent you from double-rotating some numbers. Combining all of the above, the two encryption loops of your main function could turn from: for (int i = 0; i < pas.length(); i++) { if (pas[i] + big >= 'A' && pas[i] + big <= 'Z') pas[i] = pas[i] + big; else if (pas[i] >= 'A' && pas[i] <= 'Z') { int tempVar = big; while (tempVar > 0) { if (pas[i] == 'Z') { pas[i] = 'A'; tempVar = tempVar - 1; } tempVar = tempVar - 1; pas[i] = pas[i] + 1; } } } for (int i = 0; i < pas.length(); i++) { if (pas[i] + small >= 'a' && pas[i] + small <= 'z') pas[i] = pas[i] + small; else if (pas[i] >= 'a' && pas[i] <= 'z') { int tempVar = small; while (tempVar > 0) { if (pas[i] == 'z') { pas[i] = 'a'; tempVar = tempVar - 1; } pas[i] = pas[i] + 1; tempVar = tempVar - 1; } } } to for (int i = 0; i < pas.length(); i++) { char c = pas[i]; if (is_upper(c)) { pas[i] = rotate_upper(c, big); } else if (is_lower(c)) { pas[i] = rotate_lower(c, small); } } You can transform 30 lines of code into just under 10. That's much easier to read for both you, the developer, and for any potential reviewers.
70,536,538
70,536,578
How to correctly include classes in c++?
I would like some clarification about including classes in c++. I don't know the good way to do it because i don't know the differences between theme #pragma once #include "B.h" // Is it enough to include like this? ? class B; // what this line does ? class A : public B // what public B does here ? { // ....... }; So how do i know if i should use class b or public B or juste a #include "B.h" ? I hope i was clear enough and thanks for the help
#include "B.h" // Is it enough to include like this? ? Yes. class B; // what this line does ? This is an alternative to including B's header. Doing both is redundant. It gives you less freedom. It allows you to create pointers and references to B, but not create instances of it, nor inherit from it, nor access its members. On the other hand, class B; compiles faster, and can be used to break circular include dependencies. class A : public B // what public B does here ? Class A inherits from class B, publicly. Read about inheritance in your favorite C++ book.
70,536,642
70,537,196
C++ executing a shellcode from caesar cipher does not work
In my code example, I hardcoded my shellcode, and execution works fine: Delete pls
Your Caesar-decoded shellcode does not match your hard-coded shellcode, that is why you are getting different outputs. Let's look at the first character as an example, but this applies to the whole data as a whole: Your Caesar-encoded string begins with the ASCII _ character, which has a hex value of 0x5F. When decremented by 3, that becomes the hex value 0x5C, which is the ASCII \ character. However, your hard-coded shellcode begins with the ASCII H character, which has a hex value of 0x48. Whether you left-shift (decrement) that value by 3, or right-shift (increment) it by 3, the result won't come close to being near 0x5C or 0x5F. Left-shifted, 0x48 will be 0x45 (E). Right-shifted, it will be 0x4B (K). Which means that your Caesar-encoded string is the wrong encoding of your desired shellcode to begin with.
70,536,934
70,537,265
unsorted array, find the next greater element for every element, else print -1
the requirement is a little bit complicated let's say we have an unsorted array, for example: {12, 72, 93, 0, 24, 56, 102} if we have an odd position, we have to look for the next greater element in his right, let's say we take v[1] = 12, the nge for '12' is 24; but if we have an even position, we have to look for the next greater element in his left, let's say we take v[2] = 72, there s no number who s greater than '72', so we will print '-1'; let's take another example, v[4] = 0, the nge for '0' is 12; the output should be: 24 -1 102 12 56 72 -1 i tried to solve this in c++: #include <iostream> using namespace std; int main() { const int CONST = 10000; int n, v[CONST]; cin >> n; for (int i = 1; i <= n; i++) { cin >> v[i]; } for (int i = 1; i <= n; i++) { int next = -1; if (i % 2 != 0) { for (int j = i + 1; j <= n; j++) { if (v[j] > v[i]) { next = v[j]; break; } } cout << next << " "; } else { for (int k = 1; k <= i - 1; k++) { if (v[k] > v[i]) { next = v[k]; break; } } cout << next << " "; } } return 0; } firstly, i think that i have to sort the array and after that to use binary search for finding the next greater element
For starters instead of the array it is much better to declare an object of the type std::vector<int>. Pay attention to that indices in C++ start from 0. In this if statement if (v[j] > v[i]) { next = v[j]; break; } you are exiting the loop as soon as the first element greater than the current is found. It is evident that this approach is wrong. I can suggest the following solution. #include <iostream> #include <vector> int main() { std::vector<int> v; size_t n = 0; std::cin >> n; v.resize( n ); for (auto &item : v) { std::cin >> item; } for (size_t i = 0, n = v.size(); i < n; i++) { size_t next = i; if (i % 2 == 0) { for (size_t j = i + 1; j != n; ++j) { if (v[i] < v[j] && ( next == i || v[j] < v[next] )) { next = j; } } } else { for (size_t j = i; j-- != 0; ) { if (v[i] < v[j] && ( next == i || v[j] < v[next] )) { next = j; } } } std::cout << ( next != i ? v[next] : -1 ) << ' '; } } The program output might look like 7 12 72 93 0 24 56 102 24 -1 102 12 56 72 -1
70,537,094
70,537,095
C++ vector stack overflow in constructor
I have the following code snippet: #include <vector> struct X { std::vector<X> v; X(std::vector<X> vec) : v{vec} {} }; int main() { X{{}}; } Compiling and running this snippet locally results in a stack overflow originating from X's constructor. Inspection with gdb shows me that the constructor is somehow recursively calling itself, but that doesn't make sense because I'm not calling it recursively. Why might this be happening and what can I do to fix it?
The problem has to do with how C++ chooses which constructor to execute. Notice that X's constructor uses curly-brace syntax in the member initialization list, meaning that it's using list-initialization syntax. According to the C++ reference: When an object of non-aggregate class type T is list-initialized, two-phase overload resolution takes place. at phase 1, the candidate functions are all initializer-list constructors of T and the argument list for the purpose of overload resolution consists of a single initializer list argument if overload resolution fails at phase 1, phase 2 is entered, where the candidate functions are all constructors of T and the argument list for the purpose of overload resolution consists of the individual elements of the initializer list. If the initializer list is empty and T has a default constructor, phase 1 is skipped. In copy-list-initialization, if phase 2 selects an explicit constructor, the initialization is ill-formed (as opposed to all over copy-initializations where explicit constructors are not even considered). std::vector has an initializer-list constructor as noted here, so this constructor is prioritized in the aforementioned phase 1. In the question, the non-explicit constructor for X means that the provided vector vec can be implicitly converted to an X, and so the vector constructor can be applied. Since this implicit conversion calls X's constructor, you end up with the recursion described above. To fix this, either mark X's constructor as explicit, or switch to v(vec) syntax in the constructor.
70,537,165
70,541,517
How to override preprocessor definition for a single unit when using precompiled headers?
Initial problem: I have a bug caused by an old debug MSVCRT library. It throws an exception in debug mode for std::string initialization: std::string str{vecBuff.cbegin(), vecBuff.cend()}; The old debug runtime library detects that std::vector<char>::cend() points to an invalid address and causes an error about HEAP Courruption. It only happens within a MSI Custom Action invocation (and there's an old runtime version which I can do nothing about). In the comments to this answer there is a solution to set _ITERATOR_DEBUG_LEVEL 1. I don't want to do that for the whole library. Unfortunatelly, I can't manage to do it for the single .cpp either. This .cpp uses a precompiled header and disabling it for a single file in the properties changes nothing. I still get an error about stdafx.h missing. // stdafx.h #pragma once #include <string> // the .cpp file // Can't include before. Get a lot of warnings. #include "stdafx.h" // will not have any effect since <string> is already included in "stdafx.h" #if _MSC_VER && \ !__INTEL_COMPILER && \ _DEBUG #define _ITERATOR_DEBUG_LEVEL 1 #endif #include <string> Though I am initially trying to solve the std::string initialization problem, I'd like to know the answer to a more generic topic, since there are some other places where I might require to customize preprocessof definitions AND use a precompiled header.
Defining _ITERATOR_DEBUG_LEVEL to either 1 or 2 changes the representation of iterators. Instead of being lightweight wrappers for e.g. plain pointers into container data, iterators compiled with this option contain a pointer into the data and a pointer to a container proxy object, which contains more info about the container. Thus a program where some object are compiled with _ITERATOR_DEBUG_LEVEL set to 0 and others with _ITERATOR_DEBUG_LEVEL set to something else contains two incompatible versions of each iterator type. This is not a good idea. The compiler therefore tries to detect a mix of different debug levels and introduce a deliberate linker error if a mismatch is found. Even if you manage to inhibit this check somehow, passing iterators between functions compiled with different _ITERATOR_DEBUG_LEVEL value is usually fatal.
70,537,282
70,537,384
C++20 coroutines. When yield is called empty value is retrieved
I watched the Björn Fahller - Asynchronous I/O and coroutines for smooth data streaming - Meeting C++ online talk. Following up this presentation, I gave a try to execute a similar example myself. There is a bug in my code and when yield is called , the value that is printed is zero. Debugging the code , I detected that the yield_value comparing with await_resume, is called from different promise object. I am confused, and I do not know how to call the yield_value using the correct promise object. #include <iostream> #include <coroutine> #include <optional> #include <string> #include <memory> using namespace std; template<typename T> struct promise; template<typename T> struct task { using promise_type = promise<T>; auto operator co_await() const noexcept { struct awaitable { awaitable(promise<T> & promise) :m_promise(promise) { } bool await_ready() const noexcept { return m_promise.isready(); } void await_suspend(coroutine_handle<promise_type> next) { m_promise.m_continuation = next; } T await_resume() const { std::cout << "await_resume m_promise::" << &m_promise << std::endl; return m_promise.get(); } promise<T> & m_promise; }; return awaitable(_coroutine.promise()); } task(promise_type& promise) : _coroutine(coroutine_handle<promise_type>::from_promise(promise)) { promise.m_continuation = _coroutine; } task() = default; task(task const&) = delete; task& operator=(task const&) = delete; task(task && other) : _coroutine(other._coroutine) { other._coroutine = nullptr; } task& operator=(task&& other) { if (&other != this) { _coroutine = other._coroutine; other._coroutine = nullptr; } return *this; } static task<T> make() { std::cout << "Enter make" << std::endl; co_await suspend_always{}; std::cout << "Enter exit" << std::endl; } auto get_promise() { std::cout << "get_promise " << &_coroutine.promise() << std::endl; return _coroutine.promise(); } ~task() { if (_coroutine) { _coroutine.destroy(); } } private: friend class promise<T>; coroutine_handle<promise_type> _coroutine; }; template<typename T> struct promise { task<T> get_return_object() noexcept { return {*this}; } suspend_never initial_suspend() noexcept{return {};} suspend_always final_suspend() noexcept{return {};} bool isready() const noexcept { return m_value.has_value(); } T get() { return m_value.has_value()? m_value.value(): 0; } void unhandled_exception() { auto ex = std::current_exception(); std::rethrow_exception(ex); //// MSVC bug? should be possible to rethrow with "throw;" //// rethrow exception immediately // throw; } template<typename U> suspend_always yield_value(U && u) { std::cout << "yield_value::" << &m_continuation.promise() << std::endl; m_value.emplace(std::forward<U>(u)); m_continuation.resume(); //m_continuation. return {}; } void return_void(){} coroutine_handle<promise<T>> m_continuation; optional<T> m_value; }; template<typename T> task<T> print_all(task<T> & values) { std::cout << "print all" << std::endl; for(;;) { auto v = co_await values; std::cout << v << "\n" << std::flush; } } int main(int argc, const char * argv[]) { auto incoming = task<int>::make(); auto h = print_all(incoming); auto promise = incoming.get_promise(); promise.yield_value(4); } Any help? demo
This is returning a copy of the promise: auto get_promise() { std::cout << "get_promise " << &_coroutine.promise() << std::endl; return _coroutine.promise(); } So instead of calling into the promise for the task, you're calling into just some other, unrelated promise object. Once you fix that, you'll find that your code has an infinite loop. Your promise is "ready" when it has a value. But once it has a value, it always has a value - it's always ready. One way to fix this is to ensure that await_resume consumes the value. For instance, by changing get() to: T get() { assert(m_value.has_value()); T v = *std::move(m_value); m_value.reset(); return v; } That ensures that the next co_await actually suspends.
70,537,311
70,538,158
Friending a typedef-ed class (c++)
I am going through a bit of a crisis where I need to friend a template class that is typedefed, but I am getting loads of errors(too many to paste here). I have put the MRE here so you guys don't have to set up the files. Here are the .h files for completeness-sake: //Keyboard.h #pragma once namespace wm { namespace io { class Keyboard { //friend wm::MessageHandler; private: Keyboard(const Keyboard&) = delete; void operator=(const Keyboard&) = delete; Keyboard() = default; public: static Keyboard& Instance(); static void SomeServerFunc(); public: static void SomeClientFunc(); }; } } //Mouse.h #pragma once namespace wm { namespace io { class Mouse { //friend wm::MessageHandler; //friend class wm::MessageHandler; ?? private: Mouse(const Mouse&) = delete; void operator=(const Mouse&) = delete; Mouse() = default; public: static Mouse& Instance(); static void SomeServerFunc(); public: static void SomeClientFunc(); }; } } //MessageHandler.h #pragma once #include "Keyboard.h" #include "Mouse.h" namespace wm { template < class Keyboard, class Mouse > class _MessageHandler { public: static _MessageHandler& Instance(); _MessageHandler(const _MessageHandler&) = delete; void operator=(const _MessageHandler&) = delete; private: _MessageHandler() = default; static void SomeMsgHandelingFunc(); //calls SomeServerFunc from window and mouse }; typedef _MessageHandler<io::Keyboard, io::Mouse> MessageHandler; } As it is, above code compiles and runs fine. But I want to make the SomeServerFunc function in both keyboard and mouse classes private and make MessageHandler a friend of Keyboard and Mouse. I have tried different things but nothing has worked so far. I was doing friend class wm::MessageHandler; but I got elaborated type refers to typedef error. Then I found out after c++ 11, you can do friend wm::MessageHandler; which gives loads of error. I also tried friend wm::_MessageHandler<io::Keyboard, io::Mouse>; friend class wm::_MessageHandler<io::Keyboard, io::Mouse>; friend wm::_MessageHandler<Keyboard, Mouse>; friend class wm::_MessageHandler<Keyboard, Mouse>; No luck. Would really appreciate any help.
to make the SomeServerFunc function in both keyboard and mouse classes private and make MessageHandler a friend of Keyboard and Mouse. I add class declaration to mouse.h and keyboard.h,to make the compiler happy.Here is the code: #pragma once namespace wm { template < class Keyboard, class Mouse > class _MessageHandler; namespace io { class Keyboard; class Mouse { friend class _MessageHandler<io::Keyboard, io::Mouse>; private: Mouse(const Mouse&) = delete; void operator=(const Mouse&) = delete; Mouse() = default; public: static Mouse& Instance(); private: static void SomeServerFunc(); public: static void SomeClientFunc(); }; } } #pragma once namespace wm { template < class Keyboard, class Mouse > class _MessageHandler; namespace io { class Mouse; class Keyboard { friend class _MessageHandler<io::Keyboard, io::Mouse>; private: Keyboard(const Keyboard&) = delete; void operator=(const Keyboard&) = delete; Keyboard() = default; public: static Keyboard& Instance(); private: static void SomeServerFunc(); public: static void SomeClientFunc(); }; } }
70,537,324
70,537,388
Warnings vs optimization gcc
I wonder if the warnings reported by compiler such as variable unused or control reaches end of a non-void function can impact a program (i.e crash) when the optimization is enabled (O2 or O3) Could you please give me some examples ?
Warnings indicate likely mistakes in your code. However, whether or not the warning is there or whether or not optimizations are enabled doesn't affect whether the code is correct. Warnings such as unused variable simply indicate that you probably meant to use the variable somewhere but forgot to do so. Otherwise there wouldn't be a reason for the variable to be there. Warnings such as control reaches end of a non-void function are more severe. For example in this specific case, calling a function with non-void return type causes undefined behavior if its execution reaches the function body's closing } without returning via a return statement prior to that. In this case the warning is informing you that the compiler detected a path that the function could take for some input with this result. This is very likely unintended, because if you call that function taking that path, then your program would have undefined behavior. When the program has undefined behavior you cannot be sure what it will do, absent additional guarantees made by your compiler/platform. It may behave in one way with optimizations and in a different way without them. It might also have different behavior with different compiler versions or just between different compilation runs or even program executions. Higher optimization levels are however more likely to yield unexpected behavior in such a situation, because the compiler tries harder to transform the code into a more performant form and in doing so it will make assumptions on code constructs to not yield undefined behavior to expand the range of possible transformations.
70,537,383
70,537,600
Is there a way to extract outer loops of multiple similar functions?
Example: I want to extract the nested for loops from these operator functions that are the same except the one line. // Add two matrices Matrix& operator+=(const Matrix& other) { for (int i = 0; i < this->m_rows; i++) { for (int j = 0; j < this->m_cols; j++) { (*this)(i, j) = (*this)(i, j) + other(i, j); // Only difference } } return *this; } // Subtract two matrices Matrix& operator-=(const Matrix& other) { for (int i = 0; i < this->m_rows; i++) { for (int j = 0; j < this->m_cols; j++) { (*this)(i, j) = (*this)(i, j) - other(i, j); // Only different } } return *this; }
You can write a function template that accepts a binary function and applies it on all pairs of elements inside the loops template<typename Op> void loops(const Matrix& other, Op op) { for (int i = 0; i < this->m_rows; i++) { for (int j = 0; j < this->m_cols; j++) { (*this)(i, j) = op((*this)(i, j), other(i, j)); } } } and then use it like this // Add two matrices Matrix& operator+=(const Matrix& other) { loops(other, std::plus{}); return *this; } // Subtract two matrices Matrix& operator-=(const Matrix& other) { loops(other, std::minus{}); return *this; }
70,537,434
70,537,626
C++ question regarding how ifstream reads lines and columns
I was reading some old codes of mine and I realize that I don`t know exactly how ifstream works. The following code should just read a file, save its contents into an object and create another file with exactly same data, which is written as: #include <iostream> #include <fstream> using namespace std; class grade { public: float grade1; float grade2; float grade3; }; void read_file(grade data[]){ ifstream myfile("data.txt"); int i=0; while(myfile >> data[i].grade1){ myfile >> data[i].grade2 >> data[i].grade3; i=i+1; } myfile.close(); myfile.clear(); } void write_file(grade data[]){ ofstream myfile("data_out.txt"); for(int i=0; i<3; i++){ myfile << data[i].grade1 << "\t" << data[i].grade2 << "\t" << data[i].grade3 << endl; } myfile.close(); myfile.clear(); } int main() { grade data[3]; read_file(data); write_file(data); return 0; } With "data.txt" having: 23.5 10.1 11.6 14.3 8.2 9.3 6.5 6.7 5.3 The code works just fine, but I don't get how the ifstream "knows" which line or column it should be at a given moment, since the variable i is not used to control myfile. I am assuming that by default ifstream has two internal variables, one for line and the other for column, that each time a myfile >> xxx command is identified, the column variable is incremented and every time that a loop repeats the line variable is incremented. It is something like that? Not actually controlling what line or column the code is at a given moment is quite confusing to me. Lets say, for instance, that in this example I would like to read only the data on the second line and column. Could I access directly it using some explicit expression like 'myfile[1][1] >> xxx'? I guess that getlinecould be used, but since it is used for strings I really don't know.
In read_file() the reading occurs in this loop: int i=0; while(myfile >> data[i].grade1){ myfile >> data[i].grade2 >> data[i].grade3; i=i+1; } First, this assumes that data[] was already allocated with sufficient number of elements. It's strange since the file was not yet read, so how to know how many records are to be read in advance? Then, this reading algorithm assumes that the data is in an ordinary text file, in which data elements are space separated: The myfile >> data[i].grade1 reads the first grade of a new sequence. If it reaches the end of file, the result will be evaluated to false and the loop will end. Then for every first grade read, the loops reads the next grades of the record: myfile >> data[i].grade2 >> data[i].grade3; This logic reads in fact one number after the other. The only constraint is that there are one or several spaces between the numbers. The stream therefore doesn't care about columns: it's just the next item to be read. The following input file would work equally well: 23.5 10.1 11.6 14.3 8.2 9.3 6.5 6.7 5.3 This being said, no need to close and clear the stream at the end of the function: when the function will return, its local objets will be destroyed. This includes the stream object, and the destruction ensures that everything ends right. Remark: incomplete records are not handled well: if the first grade is present but one of the remaining is missing, the stream will be in an error state, and the grade2 or grade3 elements will be left uninitialized.
70,537,605
70,537,641
How do I stop a C++ program from calling a function body from the wrong source file, when it's defined in 2 places?
I've tried creating a static library with two copies of the same function, defined in two seperate header/source files. These 2 source files should be mutually exclusive and not includable within the same file as each other. I've recreated the issue with the example code below. This was written and tested on VS2019, I haven't tested this on any other compiler yet. The following is in a foobar static lib: foo.h #pragma once #ifdef BAR static_assert(-1, "Bar is already included, you shouldn't include both foo & bar"); #endif //BAR #define FOO void foobar(); foo.cpp #include "foo.h" #include <iostream> void foobar(){ std::cout << "this is foo!"; } bar.h #pragma once #ifdef FOO static_assert(-1, "Foo is already included, you shouldn't include both foo & bar"); #endif //FOO #define BAR void foobar(); bar.cpp #include "bar.h" #include <iostream> void foobar(){ std::cout << "this is bar!"; } I could then create an executable project with a single main.cpp I've created 3 diffirent versions of this file, but they all print the same line "this is foo!" Below are the 3 versions of the main file: #include "bar.h" int main() { foobar(); } #include "foo.h" int main() { foobar(); } #include "foo.h" #include "bar.h" int main() { foobar(); } So my questions are: Why does the executable always print "this is foo!", no matter what it includes? Why doesn't compilation fail when foo.h & bar.h are included in the same source file despite the static_assert in the header files? Is there a way to achieve 2 definitoins of the same function within the same library, but not allow them to be called at the same time? Edit: Thank you very much @selbie, you're answer is very useful. I've rewritten it so that it's slightly less hacky. foo.h #pragma once #ifdef BAR static_assert(false, "Bar is already included, you shouldn't include both foo & bar"); #endif //BAR #define FOO #include "foobar.h" bar.h #pragma once #ifdef FOO static_assert(false, "Foo is already included, you shouldn't include both foo & bar"); #endif //FOO #define BAR #include "foobar.h" foobar.h #pragma once void foobar_foo(); void foobar_bar(); inline void foobar() { #ifdef FOO foobar_foo(); #endif // FOO #ifdef BAR foobar_bar(); #endif // BAR } foobar.cpp #include "foobar.h" #include <iostream> void foobar_foo() { std::cout << "this is foo!"; } void foobar_bar() { std::cout << "this is bar!"; }
I'm surprised the linker didn't give you a warning about this. When it links together the final executable program, it's going to pick one of the foobar implementations and discard the other. Pre-processor hack. foobar is defined as a macro or inline function that invokes a unique function name. Define foo.h and foo.cpp like the following below: foo.h #pragma once #ifdef BAR static_assert(false, "Bar is already included, you shouldn't include both foo & bar"); #endif //BAR #define FOO void foobar_foo(); #ifndef FOOBAR_IMPL inline void foobar() {foobar_foo();} #endif // OR // #ifdef foobar // #undef foobar // #endif // #define foobar foobar_foo Then foo.cpp: #define FOOBAR_IMPL // avoids the ODR issue that user17732522 called out in comments #include "foo.h" #include <iostream> void foobar_foo(){ std::cout << "this is foo!"; } Repeat this pattern for bar.h and bar.cpp.
70,538,029
70,538,192
Boost 1.45 dataset workaround
I'm making an attempt at setting boost's unit test framework up for myself, but due to having to use C++98, I also have to use boost 1.45. Due to this, I find I can't make use of datasets the way I'd like (have test cases that have an arity of 2 and a dataset of pairs (input_val,expected_val)). It's looking like I'll be able to get an approximation going using a global fixture (The fixtures would have to be global if I want to not have it reset every test case. This issue is documented in another post), but I dislike the idea of throwing all that into global. Does anybody know a better, possibly more elegant solution?
@ provided the info I needed. If anybody else is looking for a good unit testing framework for C++98, Catch seems great so far!
70,538,129
70,538,219
C++ wininet fetching data in 513 byte chunks
I am trying to fetch my server html text data using wininet, but it seems to be reading it and breaking it into 513 byte size chunks. However I would prefer the data to be fetched as a whole. Is there a way I can go around this? Here is a full code for references: #include <windows.h> #include <wininet.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment (lib, "Wininet.lib") int main(int argc, char** argv) { HINTERNET hSession = InternetOpen(L"Mozilla/5.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); HINTERNET hConnect = InternetConnect(hSession, L"www.google.com", 0, L"", L"", INTERNET_SERVICE_HTTP, 0, 0); HINTERNET hHttpFile = HttpOpenRequest(hConnect, L"GET", L"/", NULL, NULL, NULL, 0, 0); while (!HttpSendRequest(hHttpFile, NULL, 0, 0, 0)) { printf("Server Down.. (%lu)\n", GetLastError()); InternetErrorDlg(GetDesktopWindow(), hHttpFile, ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); } DWORD dwFileSize; dwFileSize = BUFSIZ; char* buffer; buffer = new char[dwFileSize + 1]; while (true) { DWORD dwBytesRead; BOOL bRead; bRead = InternetReadFile(hHttpFile, buffer, dwFileSize + 1, &dwBytesRead); if (dwBytesRead == 0) break; if (!bRead) { printf("InternetReadFile error : <%lu>\n", GetLastError()); } else { buffer[dwBytesRead] = 0; std::string newbuff = buffer; std::wcout << "\n\nSize: " << newbuff.size() << std::endl; std::cout << newbuff; } } InternetCloseHandle(hHttpFile); InternetCloseHandle(hConnect); InternetCloseHandle(hSession); }
dwFileSize = BUFSIZ; If you look at your header files you will discover that BUFSIZ is #defined as 512. buffer = new char[dwFileSize + 1]; // ... Read = InternetReadFile(hHttpFile, buffer, dwFileSize + 1, &dwBytesRead); Your program then proceeds to allocate a buffer of 513 bytes, and then read the input, 513 bytes at a time. And that's exactly the result you're observing. This is the only thing that the shown code knows how to do. If you want to use a larger buffer size, you can easily change that (and there is no reason to new the buffer anyway, all that does is create an opportunity for memory leaks, just use std::vector, or a plain array for smaller buffers of this size). Unless you have advance knowledge of the size of the file to retrieve you have no alternative but to read the file, in pieces, like that. Even though it's being retrieved in pieces it looks like the file is getting retrieved in a single request, and it's just that the shown code retrieve it one chunk at a time, which is perfectly fine. Switching to a large buffer size might improve the performance, but not dramatically.
70,539,175
70,539,202
Couldn't free allocated memory using delete
I'm allocating memory in a member function like below: void Wrapper::PutData() { mpeople.append(new people("ALPHA","BEETA","GAMMA", this)); mpeople.append(new people("ALPHA","BEETA","GAMMA", this)); mpeople.append(new people("ALPHA","BEETA","GAMMA", this)); } where the mpeople object is declared as QList<QObject*> mpeople; Everything works fine until i try to remove items using the below member-function void Wrapper::RemoveClient(int index){ if(index >= 0){ delete[] mpeople[index]; mpeople.removeAt(index); } resetModel(); }
You're attempting to do scalar delete on an object that wasn't allocated with scalar new. That is delete, not delete []. Just do this: void Wrapper::RemoveClient(int index){ if(index >= 0){ delete mpeople[index]; mpeople.removeAt(index); } resetModel(); } A more modern way, is to use shared_ptr or unique_ptr or the equivalent qt smart pointer class. Declare like this: QList<std::shared_ptr<QObject>> mpeople; Insert like this: mpeople.append(std::make_shared<people>("ALPHA","BEETA","GAMMA", this)); Remove like this: mpeople.removeAt(index); // pointer will get deleted for you when the last reference goes away
70,539,361
70,539,396
Can I cast a memory area with a class type?
class RW { int a; public: int read() const { return this->a; } void write(int _a) { this->a = _a; } }; #define PHYSICAL_ADDRESS (0x60000000) #define SIZEOF_PHY_ADDR (sizeof(RW)) // assume physical memory area is already assigned for the sizeof(RW) void main() { int val; void *phy_ptr = PHYSICAL_ADDRESS; RW *rw_ptr = (RW *)phy_ptr; rw_ptr->write(1); val = rw_ptr->read(); } Please assume that the code above is pseudo code. I have a shared physical memory area which is read/writable. And I want to cast the pointer of that area to read and write. Can I do this and is it acceptable? I have checked it works fine but I am not sure if it's right cpp manner. I appreciate any response and discussion! Thanks in advance!
You don't need to cast: you may just create the object at that address with placement new operator. void main() { int val; void *phy_ptr = PHYSICAL_ADDRESS; //RW *rw_ptr = (RW *)phy_ptr; RW *rw_ptr = new(phy_ptr) RW; rw_ptr->write(1); val = rw_ptr->read(); rw_ptr->~RW(); }
70,541,155
70,541,310
How to assign char* variables dynamicly in C++?
I encounter a scenario to register arbitrary addresses as char* in a program.I need to pass each one as char* to the third party library for further action. The third_party_function is describe as such in its header file: virtual void RegisterFront(char *pszFrontAddress) = 0; First, the program have to read from a config file with a group of addresses like: tcp://18.19.20.22:7778; tcp://18.19.20.24:7778; tcp://18.19.20.25:7778; The procedure to analyze this string and break it to a vector of addresses is simple if I define it as a cstring and use a loop. But then each has to be registered in that function in order for the library to connect to another address if current failed. Currently the configuration has 3 addresses but an arbitrary number of them should be allowed. A static way to assign char* variables would be like this: ... #include third_party_lib; char* addr1 = "tcp://18.19.20.22:7778".c_str(); char* addr2 = "tcp://18.19.20.24:7778".c_str(); RegisterFront(addr1); RegisterFront(addr2); I omitted the loop to analyze the addresses out from the config, but the essence is clear: I cannot name addr[n]'s in the program since the number of addresses is uncertain - it depends on how many would be written in that config line. i.e. For the 3 addresses scenario I can assign addr1 addr2 addr3 in the code. But once it is compiled, what if the config line now contains only two addresses? What about changing to 5? How to improve the above to achieve dynamically assigning an arbitrary number of char* variables and pass each one of them to the third party function RegisterFront? - Of course you could replace it by some print function to try out, but the input type shall be the same. BTW: Replacement for RegisterFront function: void printFront(char *addr){ cout << addr <<endl; }
Let's say your config line is this: std::string s = "tcp://18.19.20.22:7778; tcp://18.19.20.24:7778; tcp://18.19.20.25:7778;" s can also be a char*, it doesn't matter. At some point in your code, you've got a string representation of that config line that you've read from file or wherever. Then to loop through that string for each URL and all your RegisterFront function is just this. #include <iostream> #include <vector> #include <string> #include <sstream> void trim(std::string& s) { size_t start = 0; size_t end = s.size(); while ((start < end) && isspace(s[start])) { start++; } while ((end > start) && isspace(s[end - 1])) { end--; } s = s.substr(start, end - start); } void RegisterAddresses(const std::string& config_line) { std::istringstream ss(config_line); std::string address; while (std::getline(ss, address, ';')) { trim(address); // address[0] returns a reference to the first char in the string // hence, &address[0] is the char* to the front of the string RegisterFront(&address[0]); } } Then when you have your config_line (either defined as a char* or std::string instance), you just invoke it either way: std::string s = "tcp://18.19.20.22:7778; tcp://18.19.20.24:7778; tcp://18.19.20.25:7778;"; RegisterAddresses(s); This also works (a temporary std::string is passed to RegisterAddresses - constructed from the char* passed in) const char* s = "tcp://18.19.20.22:7778; tcp://18.19.20.24:7778; tcp://18.19.20.25:7778;"; RegisterAddresses(s);
70,541,449
70,541,685
C++ Templates: expected constructor, destructor, or type conversion
I am trying to build a library with a templated class having a constraint on the value of the integer passed: library.h template<int N> requires (N == 1) class example { public: example(); }; library.cpp: #include "library.h" main.ccp: #include "library.h" int main() { return 0; } However, when trying to compile main.cpp, the compiler throws me the following error: error: expected constructor, destructor, or type conversion before '(' token I noticed that if I do not include library.h in main.ccp, the build compiles successfully, but I have nothing else in my main.ccp and I am not really sure what is happening. I appreciate any help solving the issue as I cannot continue working on this if I cannot compile.
As Charles Savoie already wrote in his comment, the requires keyword is new since C++ version 20. Older compilers do not know that keyword; for such compilers requires is just an identifier like example or helloWorld. You might try to replace requires by helloWorld to check if your compiler supports requires: template<int N> helloWorld (N == 1) class example { public: example(); }; Of course, this will cause some error message in any case. However, if you get exactly the same error message that you get now, it is very probable that your compiler does not support the requires keyword. You can try to get a newer compiler, of course. But in this case, it is probable that your library can only be used by the latest compilers so you will also require a very recent compiler when you write a program that uses your library. If you want your library to be compatible with less recent compilers, you must avoid the requires keyword.
70,541,494
70,541,798
Postfix to Infix conversion in C++. "Process returned -1073740940 (0xC0000374) execution time : 5.538 s". No clue why
The question is to convert a postfix expression to an infix expression using stacks and without stack library. Im getting a statement after i run it and enter my postfix expression saying : "Process returned -1073740940 (0xC0000374) execution time : 5.538 s" The second i enter my postfix expression, the computer freezes and takes up a few seconds and then gives the statement. It does not even return the infix expression. I have absolutely no clue why. It also somestimes can take 30-40s just for this error to pop up. Edit#1: Okay so as @churill said, the misplaced parenthesis was an issue. i corrected that. now im getting this error immediately: "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc" My code: (Edited once) #include <iostream> #include <ctype.h> const int MAX = 20; using namespace std; class Stack { private: int top = -1; string arr[MAX]; public: bool isEmpty(){ if (top == -1){ return true; } else{ return false; } } bool isFull(){ if(top == MAX-1){ return true; } else{ return false; } } void push(string c){ if(isFull()){ //Edited line cout<<"Stack Overflow"<<endl; } else{ top++; arr[top] = c; } } string pop(){ string val = arr[top]; arr[top] = '0'; top--; return val; } string topele(){ string topelement = arr[top]; return topelement; } string display(){ int i; for(i=top;i>=0;i--){ cout<<arr[i]<<endl; } } bool isOperand(char c){ if(c >= 'a' && c <= 'z'){ return true; } else{ return false; } } string posfixtoinfix(string postfix){ Stack s; int i; int len = postfix.size(); for(i=0;i<=len;i++){ if(s.isOperand(postfix[i])){ //Edited line string op(1, postfix[i]); s.push(op); } else{ string op1 = s.topele(); s.pop(); string op2 = s.topele(); s.pop(); string res = ("("+ (op2 + postfix[i] + op1) + ")"); s.push(res); } } return s.topele(); } }; int main(){ Stack s1; string postfix, infix; cout<<"Enter postfix expression: "<<endl; cin>>postfix; infix = s1.posfixtoinfix(postfix); cout<<"The infix expression is: "<<infix<<endl; return 0; }
For one, You have undefined behavior in your program. This is because you're going out of bounds when you wrote string op1 = s.topele(); at: else{ string op1 = s.topele(); //this will call topele //... } Now the member funciton topele is called and you have string topelement = arr[top]; //this will result in(when top = -1) undefined behavior and may crash the program But note since top holds the value -1 by default, in the above snippet, you're essentially writing string topelement = arr[-1]; which leads to undefined behavior and may result in a crash. Remember that for a std::string the valid range of indexes is 0 to myString.length() - 1 (inclusive). When you use -1 as index, you get the character before the string, which is out of bounds and leads to undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. 1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
70,541,587
70,541,934
Running until a certain value linked list
I want to sum the nodes until 0 is reached and update the original linked list with the new values. Note: it skips 0 until it reaches a number to calc sum or the end of the linked list. Definition of node: struct Node { int data; Node* next; }; void updateLinkedList(Node* head) { Node* currentNode = head; int temp = 0; int sum = 0; while (currentNode != NULL) { temp = currentNode->data; while(temp != 0) { sum = sum + currentNode->data; currentNode = currentNode->next; } } } I'm attempting to do the next thing: User input linked list: 1 2 0 5 3 0 4 Updated Linked List: 3 8 4
The function can be implemented for example the following way void updateLinkedList( Node * &head ) { for ( Node **current = &head; *current != nullptr; ) { if ( ( *current )->data == 0 ) { Node *tmp = *current; *current = ( *current )->next; delete tmp; } else { while ( ( *current )->next != NULL && ( *current )->next->data != 0 ) { ( *current )->data += ( *current )->next->data; Node *tmp = ( *current )->next; ( *current )->next = ( *current )->next->next; delete tmp; } current = &( *current )->next; } } } Here is a demonstration program. #include <iostream> struct Node { int data; Node *next; }; void clear( Node * &head ) { while (head != nullptr) { Node *tmp = head; head = head->next; delete tmp; } } void assign( Node * &head, const int a[], size_t n ) { clear( head ); for (Node **current = &head; n--; current = &( *current )->next) { *current = new Node{ *a++, nullptr }; } } std::ostream &display( const Node * const &head, std::ostream &os = std::cout ) { for (const Node *current = head; current != nullptr; current = current->next) { os << current->data << " -> "; } return os << "null"; } void updateLinkedList( Node * &head ) { for (Node **current = &head; *current != nullptr; ) { if (( *current )->data == 0) { Node *tmp = *current; *current = ( *current )->next; delete tmp; } else { while (( *current )->next != NULL && ( *current )->next->data != 0) { ( *current )->data += ( *current )->next->data; Node *tmp = ( *current )->next; ( *current )->next = ( *current )->next->next; delete tmp; } current = &( *current )->next; } } } int main() { Node *head = nullptr; const int a[] = { 0, 0, 1, 2, 0, 5, 3, 0, 4 }; const size_t N = sizeof( a ) / sizeof( *a ); assign( head, a, N ); display( head ) << '\n'; updateLinkedList( head ); display( head ) << '\n'; clear( head ); } The program output is 0 -> 0 -> 1 -> 2 -> 0 -> 5 -> 3 -> 0 -> 4 -> null 3 -> 8 -> 4 -> null
70,541,687
70,646,402
Linking local Openssl to Nodejs C++ addon
I am writing a C++ addon for Nodejs which uses OpenSSL 3 and I keep getting this error when trying to compile the code with the command node-gyp build: /Users/myuser/Library/Caches/node-gyp/17.0.1/include/node/openssl/macros.h:155:4: error: "OPENSSL_API_COMPAT expresses an impossible API compatibility level" I can see that the OpenSSL used here is included from the NodeJS folder, is there any way to link the OpenSSL library I installed with homebrew on my mac M1? My binding.gyp file looks like this: { "targets": [ { "target_name": "module", "include_dirs": [ "/opt/homebrew/opt/openssl@3/include" ], "sources": [ "./module.cpp" ], "libraries": [ "/opt/homebrew/opt/openssl@3/lib/libcrypto.3.dylib", "/opt/homebrew/opt/openssl@3/lib/libcrypto.a", "/opt/homebrew/opt/openssl@3/lib/libcrypto.dylib" ] } ] }
This is a problem in Node.js: https://github.com/nodejs/node/issues/40575 And here is a workaround: https://github.com/mmomtchev/node-gdal-async/commit/85816cbeff104b5484aae840fe43661c16cb6032 Add those two defines to your gyp: "OPENSSL_API_COMPAT=0x10100001L", "OPENSSL_CONFIGURED_API=0x30000000L" I am the author of both the issue and the workaround.
70,541,910
70,542,161
How to avoid a virtual function for a single derived class implementation?
I have a an Accessor class defining my interface to other classes and multiple base class objects within this Accessor class implementing stuff in various flavors. class Accessor { std::shared_ptr<Base> object1; std::shared_ptr<Base> object2; } The Accessor class implements of course more than just calls to the different objects, but there is one particular function, which indeed only redirects the function call to one of the objects. The problem is now that this particular function is supposed to be only implemented in one derived class and when calling the function using the Accessor class, it is known that the particular object is always the derived class implementing this method. Currently, I'm defining an 'empty' base class method and override it only in the mentioned derived class. However, I don't like this approach for two reasons: first, it looks ugly from the design perspective and second, I still have a virtual function call (and the discussed function here is in the hot path of a loop). In summary a minimal version of the code looks as follows: class Base { virtual void f() const { std::cout << "Dummy implementation!\n";} }; class Derived1 : Base { void f() const override { std::cout << "Implementing the actual thing!\n";} }; class Derived2 : Base { // Carrying the dummy implementation of the base class }; class Accessor { std::shared_ptr<Base> object1; std::shared_ptr<Base> object2; // When calling this function, we know that we actually // call object1 of type `Derived1`. Still, there might be // cases where object1 has a different type, but then we don't // call this function void f() const { object1->f();} } The whole description is probably somewhat a sign that the overall design is not the best choice. However, maybe there are other options to redesign the problem here so that the virtual function call vanishes and the code reflects the actual situation better.
If you are sure that object_1 always points to a Derived1, then make it a std::shared_ptr<Derived1> object1. And if the sole purpose of Base::f() is for Derived1, make it non-virtual and remove it from the classes that don't need it. But if one of those assumptions is not true, keep it as it is: Making an extra test to check if the class is Derived1 before calling a non-virtual function is not more efficient than calling directly a virtual function. If you don't trust me, make a benchmark. Moreover, if in the future you'd have a further specialization of Derived1, with a slightly different f(), you'd not have to worry. Assuming that it's always Derived1 and just statically down-casting is risky. As said, if you're so sure, just declare it as such (go to first paragraph), and make a (safe) downcasting when you initialize object_1. Remark: While it may seem weird at beginning to have a f() that is useless in most cases, it is in fact a common practice when using polymorphism with the tell, don't ask paradigm. A very typical example is when using the template method pattern.
70,541,941
70,541,967
How does my code get a value for my variable? C++
I'm following this book called C++ Primer Fifth Edition and it had this code: #include <iostream> int main() { int currVal = 0; int val = 0; if (std::cin >> val){ int cnt = 1; while (std::cin >> val){ if (val == currVal){ ++cnt; } else { std::cout << currVal << " occurs " << cnt << " times " << std::endl; currVal = val; cnt = 1; } } std::cout << currVal << " occurs " << cnt << " times " << std::endl; } return 0; } This code tells me how many times a number has occured in the users input. What I don't quite understand yet is how does the code know what the currVal is when I gave it a value of 0 and I haven't told it anything about the current value except in the last else statement. My question is does the code run the else code first and then runs the if statement code? But then the cnt wouldn't be able to count anything because it always gets reset to 1 at the end of the else statement. I know this is pretty basic but I just can't figure out the answer. I couldn't find an answer on google nor did it explain it in my book so I thought maybe I could ask it here.
No. The first time the if() statement is run, it checks against zero. currVal will only be updated when the else is executed.
70,542,093
70,542,324
using the current type in typedef in cpp
I need a data type which will hold either a string or a vector of the current data type. Here is a typedef I've written for that: typedef std::variant<std::vector<value>, std::string> value; Apparently this isn't valid, as value is an undeclared identifier when executing this line. So I tried first declaring value as another type and then using it in the same type: typedef int value; typedef std::variant<std::vector<value>, std::string> value; this didn't work either, because the types are different. So knowing this, what is the proper way of using the current type in a typedef?
I think this is what you're asking for: struct Type { using Value = std::variant<std::vector<Type>, std::string>; Value v; };
70,542,579
70,542,751
C++ atomic is it safe to replace a mutex with an atomic<int>?
#include <iostream> #include <thread> #include <mutex> #include <atomic> using namespace std; const int FLAG1 = 1, FLAG2 = 2, FLAG3 = 3; int res = 0; atomic<int> flagger; void func1() { for (int i=1; i<=1000000; i++) { while (flagger.load(std::memory_order_relaxed) != FLAG1) {} res++; // maybe a bunch of other code here that don't modify flagger // code here must not be moved outside the load/store (like mutex lock/unlock) flagger.store(FLAG2, std::memory_order_relaxed); } cout << "Func1 finished\n"; } void func2() { for (int i=1; i<=1000000; i++) { while (flagger.load(std::memory_order_relaxed) != FLAG2) {} res++; // same flagger.store(FLAG3, std::memory_order_relaxed); } cout << "Func2 finished\n"; } void func3() { for (int i=1; i<=1000000; i++) { while (flagger.load(std::memory_order_relaxed) != FLAG3) {} res++; // same flagger.store(FLAG1, std::memory_order_relaxed); } cout << "Func3 finished\n"; } int main() { flagger = FLAG1; std::thread first(func1); std::thread second(func2); std::thread third(func3); first.join(); second.join(); third.join(); cout << "res = " << res << "\n"; return 0; } My program has a segment that is similar to this example. Basically, there are 3 threads: inputer, processor, and outputer. I found that busy wait using atomic is faster than putting threads to sleep using condition variable, such as: std::mutex commonMtx; std::condition_variable waiter1, waiter2, waiter3; // then in func1() unique_lock<std::mutex> uniquer1(commonMtx); while (flagger != FLAG1) waiter1.wait(uniquer1); However, is the code in the example safe? When I run it gives correct results (-std=c++17 -O3 flag). However, I don't know whether the compiler can reorder my instructions to outside the atomic check/set block, especially with std::memory_order_relaxed. In case it's unsafe, then is there any way to make it safe while being faster than mutex? Edit: it's guaranteed that the number of thread is < number of CPU cores
std::memory_order_relaxed results in no guarantees on the ordering of memory operations except on the atomic itself. All your res++; operations therefore are data races and your program has undefined behavior. Example: #include<atomic> int x; std::atomic<int> a{0}; void f() { x = 1; a.store(1, std::memory_order_relaxed); x = 2; } Clang 13 on x86_64 with -O2 compiles this function to mov dword ptr [rip + a], 1 mov dword ptr [rip + x], 2 ret (https://godbolt.org/z/hxjYeG5dv) Even on a cache-coherent platform, between the first and second mov, another thread can observe a set to 1, but x not set to 1. You must use memory_order_release and memory_order_acquire (or sequential consistency) to replace a mutex. (I should add that I have not checked your code in detail, so I can't say that simply replacing the memory order is sufficient in your specific case.)
70,542,870
70,542,971
How to store unordered_set to a vector?
I want to use a vector to store several unordered_set. Here is my test codes: #include <unordered_set> #include <vector> using namespace std; int main(){ vector<unordered_set<int>> v1; unordered_set<int> s1 = {1,2}, s2 = {3,2}; v1[0] = s1; v1[1] = s2; for (auto &s : v1[0]) { cout << s << " "; } } And I get Segmentation fault (core dumped) . My question is: How should I modify my codes?
The problem with your code is that your vector does not have elements 0 and 1. Either initialize the vector with required number of elements, or insert the elements into an empty vector as below: int main(){ vector<unordered_set<int>> v1; unordered_set<int> s1 = {1,2}, s2 = {3,2}; v1.push_back(s1); v1.push_back(s2); for (auto &s : v1[0]) { cout << s << " "; } }
70,542,878
70,542,954
Is it permissible to specialize mathematical constants for custom numeric types?
Suppose I create my own floating point type MyFloatingPoint (e.g. to provide increased precision relative to the built-in types). Is it permissible to specialize the constants in the C++20 <numbers> header for this type, or is this undefined behavior?
According to C++20 draft it seems fine: 26.9.2 (...) 2. Pursuant to 16.5.4.2.1, a program may partially or explicitly specialize a mathematical constant variable template provided that the specialization depends on a program-defined type
70,542,909
70,542,996
SDL is sent me on a bad trip with FillRect
SDL_Rect r3; r3.h = 10; r3.w = 10; r3.x = 10; r3.y = 10; SDL_Rect r4; r3.h = 10; r3.w = 10; r3.x = 20; r3.y = 20; SDL_FillRect(surface, &r3, SDL_MapRGB(surface->format, 100, 0 ,100)); SDL_FillRect(surface, &r4, SDL_MapRGB(surface->format, 100, 100 ,0)); So the crazy thing, and it very weird. maybe I don't know something but R4 is R3. No I am not crazy, it will draw r3 and r4 in the same place. I commented out SDL_FillRect(surface, &r4, SDL_MapRGB(surface->format, 100, 100 ,0)); and it still draws the rectangle at r4 cords. This drives me crazy guys. SDL_Rect r3; r3.h = 10; r3.w = 10; r3.x = 10; r3.y = 10; SDL_Rect r4; r3.h = 10; r3.w = 10; r3.x = 200; r3.y = 200; //SDL_FillRect(surface, &r3, SDL_MapRGB(surface->format, 100, 0 ,100)); SDL_FillRect(surface, &r4, SDL_MapRGB(surface->format, 100, 100 ,0)); Now R4 is not drawn at all SDL_Rect r; r.w = n.left->width; r.h = n.left->height; r.x = n.left->position.x; r.y = n.left->position.y; SDL_Rect r2; r.w = (int)n.right->width; r.h = (int)n.right->height; r.x = (int)n.right->position.x; r.y = (int)n.right->position.y; SDL_Rect r3; r3.h = 10; r3.w = 10; r3.x = 10; r3.y = 10; SDL_Rect r4; r3.h = 10; r3.w = 10; r3.x = 200; r3.y = 200; //SDL_FillRect(surface, &r3, SDL_MapRGB(surface->format, 100, 0 ,100)); SDL_FillRect(surface, &r3, SDL_MapRGB(surface->format, 100, 100 ,0)); So basically r is drown where r2 should be drawn, r2 is not drawn, r3 is drawn where r4 should be and r4 is not drawn. wtf.
After declaring the SDL_rect r4, you set the coordinates for r3. SDL_Rect r4; r3.h = 10; r3.w = 10; r3.x = 200; r3.y = 200; This may result in uninitialized coordinate values for r4. This should work: SDL_Rect r3; r3.h = 10; r3.w = 10; r3.x = 10; r3.y = 10; //Set r4's coordinates instead of r3's SDL_Rect r4; r4.h = 10; r4.w = 10; r4.x = 200; r4.y = 200; SDL_FillRect(surface, &r3, SDL_MapRGB(surface->format, 100, 0 ,100)); SDL_FillRect(surface, &r4, SDL_MapRGB(surface->format, 100, 100 ,0))