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
69,070,872
69,071,854
Call Parameter as Reference to Array of Unknown Bound in C++
I am trying to understand whether references to array of unknown bound can be used as call parameter in functions in C++. Below is the example that i have: EXAMPLE 1 void func(int (&a)[]) { } int main() { cout << "Hello World" << endl; int k[] = {1,2,3}; // k[0] = 3; func(k); return 0; } To my surprise this example 1 above works when compiled with GCC 10.1.0 and C++11 but doesn't work with GCC version lower that 10.x. I don't think that we can have references to arrays of unknown size in C++. But then how does this code compile at the following link: successfully compiled My second question is that can we do this for a function template? For example, EXAMPLE 2 template<typename T1> void foo(int (&x0)[]) { } Is example 2 valid C++ code in any version like C++17 etc. I saw usage of example 2 in a book where they have int (&x0)[] as a function parameter of a template function.
I don't think that we can have references to arrays of unknown size in C++. That used to be the case, although it was considered to be a language defect. It has been allowed since C++17. Note that implicit conversion from array of known bound to array of unknown bound - which is what you do in main of example 1 - wasn't allowed until C++20. Is example 2 valid C++ code in any version like C++17 Yes; the template has no effect on whether you can have a reference to array of unknown bound.
69,071,095
69,071,179
How can anything possibly bind to this forward function?
I think I'm getting awfully close to understanding this. It seems that there are two overloads for the forward function, and I thought two overloads are needed to make it work, but as far as I can see one of them is completely useless, and it works with just one: template <typename T> T&& forward(T&& arg) {// Never gets called. // I can't see how since every argument from another function is always // an lvalue, nothing can bind to it return static_cast<T&&>(arg); } template <typename T> T&& forward(T& arg) {// Just this one seems to do the job return static_cast<T&&>(arg); } template <typename Type> void emplace(Type&& arg) { forward<Type>(arg); } int main() { int a = 0; int& intref = a; emplace(a); emplace(int()); } Both call the one forward function, the other one can go, right?
For illustration, you can change the code to this: #include <iostream> template <typename T> T&& forward(T&& arg) { // gets called when the parameter is a rvalue reference std::cout << "called\n"; return static_cast<T&&>(arg); } template <typename T> T&& forward(T& arg) { return static_cast<T&&>(arg); } template <typename Type> void emplace(Type&& arg) { forward<Type>(forward<Type>(arg)); } int main() { emplace(int()); } To get output: called In emplace the call forward<Type>(arg); does not call T&& forward(T&& arg) because arg in emplace is not a rvalue reference, sloppy speaking, because it has a name. You can call void emplace(Type&& arg) with an rvalue, but the argument arg isn't one. Actually thats the reason std::forward is needed in the first place.
69,071,462
69,075,486
how to handle excel files using C++?
I'm new to C++, And I want to enter values into an excel spreadsheet using C++, I know we can handle files using fstream but how to get a specific column or row using this method.
If you want to persist in using C++ (despite the comments above), this sample will give you an idea of the coding work needed to use C++ to automate the Excel application (as you might do in VBA or C#) rather than manipulate the file using a known file format (using a third-party library). The sample opens an existing worksheet in the background, adds 1 to the value in cell A1 on Sheet1, and then saves it. Whether this is a suitable or efficient solution for your case will depend on what exactly you are trying to do with the files. NB. Only works with the MS Visual Studio compiler. The hard-coded paths to the import libraries may be different on your computer, and may depend on your Excel version. //Import all the type libraries #import "C:\Program Files\Microsoft Office\Root\VFS\ProgramFilesCommonX86\Microsoft Shared\OFFICE16\MSO.dll" \ rename("RGB","RGB_mso") rename("DocumentProperties","DocumentProperties_mso") using namespace Office; #import "C:\Program Files\Microsoft Office\root\vfs\ProgramFilesCommonX86\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB" using namespace VBIDE; #import "C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE" \ rename( "DialogBox", "ExcelDialogBox" ) \ rename( "RGB", "ExcelRGB" ) \ rename( "CopyFile", "ExcelCopyFile" ) \ rename( "ReplaceText", "ExcelReplaceText" ) \ exclude( "IFont", "IPicture" ) #include <iostream> using namespace std; int main() { HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); Excel::_ApplicationPtr pXL; if (FAILED(pXL.CreateInstance("Excel.Application"))) { cout << "Could not create instance of Excel" << endl; return 1; } try { //Uncomment this to see what is going on during each step //pXL->Visible = true; Excel::_WorkbookPtr pWb = pXL->Workbooks->Open(L"c:\\temp\\testbook.xlsx"); //Gets number from cell A1 in Sheet1 and increments Excel::_WorksheetPtr pSheet = pWb->Worksheets->Item[L"Sheet1"]; Excel::RangePtr pRng = pSheet->Cells; _variant_t val = pRng->Item[1][1]; double dVal{ val }; pRng->Item[1][1] = ++dVal; pWb->Save(); pWb->Close(); } catch (_com_error ce) { cout << "Something went wrong" << endl; _bstr_t bstrDesc = ce.Description(); if( ! bstrDesc ) { cout << " Unknown Error" << endl; } else { cout << " Error text: " << bstrDesc << endl; } } pXL->Quit(); } EDIT: In answer to the unspoken question why is it Excel::_ApplicationPtr, Excel::_WorkbookPtr etc, but for a Range it is Excel::RangePtr (no _)? Absolutely no idea.
69,071,570
69,071,605
How do I make my code Repeat instead of ending in c++?
The code tells you if it's a prime or not, I've Tried Everything I could find, like a 'do while' loop and others It just won't work my code is if anyone could help. though it is probably me putting it in the wrong place so if anyone could put my code in the way to do it that would help alot. #include <iostream> using namespace std; int main() { { int n, i, m = 0, flag = 0; cout << "(press 'x' to exit) Enter the Number to check if It's a prime Number or not: "; cin >> n; m = n / 2; for (i = 2; i <= m; i++) { if (n % i == 0) { cout << "That's not a prime number." << endl; flag = 1; break; } } if (flag == 0) cout << "That's a prime number." << endl; } }
Put a while(true) around everything. I see you already got the {} for that: int main() { while (true) { int n, i, m = 0, flag = 0; If you do it this way it will endlessly continue asking. Ctrl+C will end the program. If you want to have the press x to exit working, something like this would work: int main() { while (true) { string s; int n, i, m = 0, flag = 0; cout << "(press 'x' to exit) Enter the Number to check if It's a prime Number or not: "; cin >> s; if (s == "x") break; n = atoi( s.c_str() ); m = n / 2;
69,071,943
69,072,141
what is the difference between using execution policy and thread pool?
I had this question, while learning C++. What is the difference between using an execution policy and VS doing the same job using a thread pool? Are there any benefits of using one over the other? std::atomic<int> sum{0}; std::for_each(std::execution::par_unseq, std::begin(v), std::end(v), [&](int i) { sum.fetch_add(i*i, std::memory_order_relaxed); }); std::for_each(std::begin(v), std::end(v), [&](int i) { thread_pool_->queue_work(callAddFn, i); }
Your thread pool version is queueing std::ranges::size(v) tiny pieces of work, whereas the execution policy version is given latitude to decide a reasonable chunk size. Because you are specifying one of the unsequenced policies, your program is ill formed if std::atomic<int>::is_lock_free() is false. On an appropriate platform, you'd get vectorised operations implementing it.
69,072,339
69,073,252
Compare UTF-8 characters
Here is a parsing function: double transform_units(double val, const char* s) { cout << s[0]; if (s[0] == 'm') return val * 1e-3; else if (s[0] == 'µ') return val * 1e-6; else if (s[0] == 'n') return val * 1e-9; else if (s[0] == 'p') return val * 1e-12; else return val; } In the line with 'µ' I'm getting the warning: warning: multi-character character constant [-Wmultichar] and the character 'µ' is not being catched. How to compare multibyte characters? Edit: a dirty workaround is to check if it is less than zero. As Giacomo mentioned, it's 0xCE 0xBC, both these bytes are greater than 127, so less than zero. It works for me.
How to compare multibyte characters? You can compare a unicode code point consisting of multiple bytes (more generally, multiple code units) by using multiple bytes. s[0] is only a single char which is the size of a byte and thus cannot by itself contain multiple bytes. This may work: std::strncmp(s, "µ", std::strlen("µ")) == 0.
69,072,385
69,072,879
conversion of integers into binary in c++
As we know, each value is stored in binary form inside memory. So, in C++, will these two values have different binary numbers when stored inside memory ? unsigned int a = 90; signed int b = 90;
So, in C++, will these two values have different binary numbers when stored inside memory ? The C++ language doesn't specify whether they do. Ultimately, the binary representation is dictated by the hardware, so the answer technically depends on that. That said, I haven't encountered hardware and C++ implementation where identically valued signed and unsigned variants of an integer didn't have identical binary representation. As such, I would find it surprising if the binary representations were different. Sidenote: Since "byte" is the smallest addressable unit of memory in C++, there isn't a way in the language to observe a directional order of individual bits in memory.
69,072,565
69,072,857
filesystem::operator/ different behaviour in boost and std
I am trying to port from boost::filesystem to std::filesystem. During the process I encountered some code in which boost and std seems to behave in a different way. The following code shows the behaviour: #include <iostream> #include <filesystem> #include <boost/filesystem.hpp> template<typename T> void TestOperatorSlash() { const std::string foo = "Foo"; const std::string bar = "Bar"; const T start = "\\"; std::string sep; sep += T::preferred_separator; const auto output = start / (foo + bar) / sep; std::cout << output << '\n'; } int main(int argc, char** argv) { TestOperatorSlash<std::filesystem::path>(); TestOperatorSlash<boost::filesystem::path>(); } The code gives in output: "\\" "\FooBar\" The expected behaviour for me is the one of boost, and I don't understand what happens with std::filesystem. Why do I get "\\"? Why is the behaviour of operator/ of path different in boost and std? Edit: After understanding the motivation of the behaviour of std::filesystem::operator/ and given the answer to this question, I decided to use the function path::relative_path() for the second argument of operator/ when I have an absolute path. In this way I can mimic the behaviour of boost::filesystem. So, for example: #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main(int argc, char** argv) { fs::path foo = "\\foo"; fs::path bar = "\\bar"; auto foobar0 = foo / bar; // Evaluates to \\bar auto foobar1 = foo / bar.relative_path(); // Evaluates to \\foo\\bar }
Boost will merge redundant separators. https://www.boost.org/doc/libs/1_68_0/libs/filesystem/doc/reference.html#path-appends Appends path::preferred_separator to pathname, converting format and encoding if required ([path.arg.convert]), unless: an added separator would be redundant, ... Whereas std::filesystem sees a leading separator in the second argument of / as an instruction to replace parts or all of the original path: https://en.cppreference.com/w/cpp/filesystem/path/append path("C:foo") / "/bar"; // yields "C:/bar" (removes relative path, then appends) Did you want: const auto output = start / (foo + bar) / ""; instead?
69,073,206
69,073,319
Why do we need stacks when we already have vectors which are even more powerful?
In C++ STL, Stacks are implemented using container adaptors which rewrite the interface of the Vector class. However, why is it necessary to do the interface rewriting and design a Stack class when there is already the Vector class available? Is it due to cost efficiency i.e. maintaining a stack uses less resources while it could do all necessary jobs?
Why do we need for loops and while loops when we already have goto which is even more powerful? You should adhere to the principle of parsimony - use the least powerful tool that is powerful enough to achieve the desired objective. If what you need is a stack, take a dependency on the standard library class that provides that functionality, not a more powerful one. It also communicates better to a person reading your code, what you are going to do.
69,073,375
69,073,480
what's wrong with this "maximum-minimum element in an array" Logic?
I am new to coding and I am unable to see what is wrong with this Logic. I am unable to get the desired output for this program. The Question is to find the minimum and maximum elements of an array. The idea is to create two functions for minimum and maximum respectively and have a linear search to identify the maximum as well as a minimum number. #include <iostream> #include<climits> using namespace std; void maxElement(int a[], int b) { // int temp; int maxNum = INT_MIN; for (int i = 0; i < b; i++) { if (a[i] > a[i + 1]) { maxNum = max(maxNum, a[i]); } else { maxNum = max(maxNum, a[i+1]); } // maxNum = max(maxNum, temp); } // return maxNum; cout<<maxNum<<endl; } void minElement(int c[], int d) { // int temp; int minNum = INT_MAX; for (int i = 0; i < d; i++) { if (c[i] > c[i + 1]) { minNum = min(minNum,c[i+1]); } else { minNum = min(minNum,c[i]); } // minNum = min(minNum, temp); } // return minNum; cout<<minNum<<endl; } int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } minElement(arr,n); maxElement(arr,n); return 0; }
You are already comparing each element to the current max / min. It is not clear why in addition you compare to adjacent elements. Trying to access a[i+1] in the last iteration goes out of bounds of the array and causes undefined behavior. Just remove that part: void maxElement(int a[], int b) { // int temp; int maxNum = INT_MIN; for (int i = 0; i < b; i++) { maxNum = max(maxNum, a[i]); } cout<<maxNum<<endl; } Similar for the other method. Note that int n; cin >> n; int arr[n]; is not standard C++. Variable length arrays are supported by some compilers as an extension, but you don't need them. You should be using std::vector, and if you want to use c-arrays for practice, dynamically allocate the array: int n; cin >> n; int* arr = new int[n]; Also consider to take a look at std::minmax_element, which is the standard algorithm to be used when you want to find the min and max element of a container. Last but not least you should seperate computation from output on the screen. Considering all this, your code could look like this: #include <iostream> #include <algorithm> std::pair<int,int> minmaxElement(const std::vector<int>& v) { auto iterators = std::minmax_element(v.begin(),v.end()); return {*iterators.first,*iterators.second}; } int main() { int n; std::cin >> n; std::vector<int> input(n); for (int i = 0; i < n; i++) { std::cin >> input[i]; } auto minmax = minmaxElement(input); std::cout << minmax.first << " " << minmax.second; } The method merely wraps the standard algorithm. It isnt really needed, but I tried to keep some of your codes structure. std::minmax_element returns a std::pair of iterators that need to be dereferenced to get the elements. The method assumes that input has at least one element, otherwise dereferencing the iterators is invalid.
69,073,378
69,073,411
Ignore white space characters in the sprintf* functions
I'd like to output some text using the sprintf_s function. Here is the code: sprintf_s(g_msgbuf, "\n\ Active Weapon PID: %d\n\ HitMode: %s\n\ Armor DT: %d\n\ Armor DR: %d\n", ActiveWeaponPID, HitModeStr.c_str(), cur_dmg_thresh, cur_dmg_resist ); As one can see for the readability reasons I've put all the parameters in separate lines. The problem is that I'm getting extra unwanted white space characters (tabs) generated in-between the format string parameter: Active Weapon PID: 8 HitMode: single Armor DT: 4 Armor DR: 30 Is there a way/parameter/option for the sprintf's functions (sprintf_s specifically) to ignore that redundant tabs?
You can use the fact that separate strings will be concatenated no matter what the whitespace/new lines are between - "one" "two" "three" is equivalent to "onetwothree" sprintf_s(g_msgbuf, "\n" "Active Weapon PID: %d\n" "HitMode: %s\n" "Armor DT: %d\n" "Armor DR: %d\n", ActiveWeaponPID, HitModeStr.c_str(), cur_dmg_thresh, cur_dmg_resist );
69,073,522
69,074,122
Would like to destroy the stack that I made
So, in class, we learnt about the implementation of an array abstract data structure, and using the array class we made, we implemented a stack abstract data structure as a class. #include <iostream> #ifndef ARRAYADT1_H #define ARRAYADT1_H using namespace std; class ArrayADT1 { public: ArrayADT1(); ArrayADT1(int); virtual ~ArrayADT1(); bool setElement(int, int); int getElement(int); int getCapacity(); protected: private: int capacity; int* elements; }; #endif // ARRAYADT1_H ArrayADT1::ArrayADT1(){ capacity=0; elements=NULL; } ArrayADT1::ArrayADT1(int arraySize){ capacity=arraySize; elements=new int[arraySize]; } bool ArrayADT1::setElement(int index, int value){ elements[index]=value; return(true); } int ArrayADT1::getElement(int index){ return(elements[index]); } int ArrayADT1::getCapacity(){ return(capacity); } ArrayADT1::~ArrayADT1(){ delete[] elements; } #ifndef STACKADT1_H #define STACKADT1_H using namespace std; class StackADT1 { public: StackADT1()=delete; //disable creation of stack without specifying capacity StackADT1(int); //create stack of capacity bool push(int); int pop(); bool isFull(); bool isEmpty(); int length(); virtual ~StackADT1(); protected: private: int ValueCount; ArrayADT1 members; }; #endif // STACKADT1_H #include <iostream> StackADT1::StackADT1(int stackCapacity): members(stackCapacity){ ValueCount=0; } int StackADT1::length(){ return(ValueCount); } bool StackADT1::isEmpty(){ if(ValueCount==0) return(true); return(false); } bool StackADT1::isFull(){ if(ValueCount==members.getCapacity()) return(true); return(false); } int StackADT1::pop(){ if(isEmpty()){ cout<<"The Stack is empty"<<"\n"; return(-1); } ValueCount--; return(members.getElement(ValueCount)); } bool StackADT1::push(int value){ if(isFull()){ cout<<"The stack is full"<<"\n"; return(false); } members.setElement(ValueCount, value); ValueCount++; return(true); } StackADT1::~StackADT1(){ //I would like to know what happens here //dtor } I was wondering about the destructor function in both cases. In the ArrayADT1 class, we explicitly used the delete method, but we do no such thing in the StackADT1 class. Does the stack also get destroyed after return 0; is called?
In the ArrayADT1 class, we explicitly used the delete method, but we do no such thing in the StackADT1 class You also explicitly used the new-expression in ArrayADT1 class, but you don't use a new-expression in the StackADT1. This is to be expected, since we only delete what we new. //I would like to know what happens here //dtor Nothing happens in the body of that destructor because the body is empty. The destructor will destroy the sub objects after the (empty) body. ArrayADT1 is copyable, but copying it results in undefined behaviour. This is bad. To fix it, follow the rule of five. I also recommend studying the RAII idiom. The example program appears to be a flawed attept at implementing RAII. Next, I recommend learning about std::unique_ptr which is a better way to manage memory.
69,073,602
69,074,256
What are the differences between member functions and member variables in terms of symbols?
I'm learning to use __attribute__ ((visibility("default"))) for symbol export // a.cpp class A { public: __attribute__ ((visibility("default"))) void func() {;}; __attribute__ ((visibility("default"))) int cnt; }; But I ran into the following problem # g++ -c a.cpp a.cpp:5:50: warning: ‘visibility’ attribute ignored [-Wattributes] __attribute__ ((visibility("default"))) int cnt; ^~~ What's the difference between a member function and a member variable? Why can one export a symbol and the other cannot?
Member functions are really just ordinary functions with special signature to accomodate the hidden this argument. So you can attach visibility attributes to them like to other global functions. On the contrary, member variables do not correspond to global entities - they are just symbolic names for offsets inside memory occupied by object of the class. So there is no point in attaching visibility to them.
69,073,827
69,092,631
What is the lifetime of a temporary object bound to a reference in a new-initializer?
From [class.temporary] of the Working Draft, Standard for Programming Language C++: (6.12) — A temporary bound to a reference in a new-initializer ([expr.new]) persists until the completion of the full-expression containing the new-initializer. [Note 7: This might introduce a dangling reference. — end note] [Example 5: struct S { int mi; const std::pair<int,int>& mp; }; S a { 1, {2,3} }; S* p = new S{ 1, {2,3} }; // creates dangling reference — end example] Does it mean that the temporary object {2,3} bound to the reference member mp of S persists until the evaluation of the expression new S { 1, {2,3} }, or until the evaluation of the expression S* p = new S{ 1, {2,3} }?
Full-expression is S* p = new S{ 1, {2,3} }.
69,074,172
69,074,502
C++ 2 Dimensional Dynamical Array with Pointer String
I see a lot of video and explanation about 2 dimensional array with double pointer which is possible when you are storing int, but what if I wanna store string in that 2 dimensional dynamical array? For example, I'm planning to input my files into my 2 dimensional dynamical array which depends on how many accounts or data I have in my files. Let's say I have 2 now, and in my program I add 1 more account, which is going to be 3, let say each of my arrays only has 3 elements inside, and then besides that, I do not want to set a constant array. How am I going to set a variable of two dimensional dynamical array that stores the string? like the very simple one. Edit : And can also someone explain me why do we have to delete after using the dynamical array? like what if I store something? does it mean my elements also get deleted? or when we close the console it will distract the actual memory? I do not really understand.
string** array = new string*[rows]; for (int i = 0; i < rows; i++)array[i] = new string[cols];} or vector<vector<string>> array;
69,074,886
69,076,236
Callback member function from API taking a free function with no arguments
I use an API which the declaration is: some_API.h typedef void (CALLBACK *EventCallback)(); class some_API{ public: // ... void EnableInterrupt(EventCallback func1, EventCallback func2); // ... }; and on the other side I have a class that use this API: My_class.h class My_class { some_API API; void CALLBACK my_func() { cout << "This is my_func!\n" } public: void using_api() { API.EnableInterrupt(my_func, nullptr); } }; main problem is type of my_func, error: Error (active) E0167 argument of type "void (__stdcall My_class::*)()" is incompatible with parameter of type "EventCallback" I found this answer, but the problem is, the API is close source, so I can't change the declaration of the void EnableInterrupt(EventCallback, EventCallback). Also I don't want to declare My_class::using_API and My_class::API as static member. I want something similar to this: API.EnableInterrupt((static_cast<void*>(my_func)), nullptr); // or API.EnableInterrupt((static_cast<EventCallback>(my_func)), nullptr); // invalid type conversion Is there any way to cast that member function to a non-member function to pass it to some_API::EnableInterrupt(...)?
Your problem is that the callback type typedef void (CALLBACK *EventCallback)(); does not have any user-provided data pointer. This is customary for the exact reason that users often need it. And just for completeness, Is there any way to cast that member function to a non-member function No, they're fundamentally different, because non-static member functions must be called with an implicit this pointer, and there's nowhere to store that in a regular function pointer. That's exactly what we'd use the user-provided pointer argument for if the API had one. Also I don't want to declare My_class::using_API and My_class::API as static member. How about if we generate another static for each distinct registration? We can automate it by using lambda type uniqueness: template <typename Lambda> class TrampolineWrapper { inline static std::optional<Lambda> dest_; // optional so we can defer initialization public: TrampolineWrapper(some_API *api, Lambda &&lambda) { // store your _stateful_ functor into a unique static dest_.emplace( std::move(lambda) ); // register a unique _stateless_ lambda (convertible to free function) api->EnableInterrupt( [](){ (*TrampolineWrapper<Lambda>::dest_)(); }, nullptr); } }; // handy type-deducing function template <typename Lambda> TrampolineWrapper<Lambda> wrap(some_API *api, Lambda &&lambda) { return {api, std::move(lambda)}; } and use it like class My_class { some_API API; void my_func() { cout << "This is my_func!\n" } public: void using_api() { auto wrapper = wrap(&API, [this](){ my_func(); }); // stateful lambda ^^^^ // not directly convertible to a free function } }; This depends on the uniqueness of lambda types to work - each lambda you use this with gets a unique static dest_ object of the same type (which may be stateful), and a unique stateless forwarding lambda (which is convertible to a free function for this horrible API). Note that this is unique only if you have multiple distinct callers registering distinct lambdas. Two calls to My_class::using_api will still collide (the second will overwrite the first's lambda). The only other nasty thing is that we're discarding the wrapper once the static is set up ... it'd be much nicer to keep it around so we could use it for unregistering the callback or something. You can do this if you want, but since you cannot know its type outside the scope of your lambda, it'll need to do something dynamic.
69,075,047
69,076,474
Is it safe to put '\0' to char[] one after the last element of the array?
I'm interested for some practical reasons. I know C++ adds '\0' after the last element, but is it safe to put it manually ? I heard about undefined behavior, however I'm interested if NULL character is actually the next symbol in the memory? UPD: I understood, my question is not clear enought without code snippets. So, I'm asking if this is actually save and won't lead to undefined behavior? const char* a = "Hello"; a[5] = '\0'; //this is wrong, will not compile on most compilers char* b = new char[5]; b[5] = '\0'; char c[5]; c[5] = '\0';
The snippet const char* a = "Hello"; a[5] = '\0'; does not even compile; not because the index 5 is out of bounds but because a is declared to point to constant memory. The meaning of "pointer to constant memory" is "I declare that I don't want to write to it", so the language and hence the compiler forbid it. Note that the main function of const is to declare the programmer's intent. Whether you can, in fact, write to it depends. In your example the attempt — after a const cast — would crash your program because modern compilers put character literals in read-only memory. But consider: #include <iostream> using namespace std; int main() { // Writable memory. Initialized with zeroes (interpreted as a string it is empty). char writable[2] = {}; // I_swear_I_wont_write_here points to writable memory // but I solemnly declare not to write through it. const char* I_swear_I_wont_write_here = writable; cout << "I_swear_I_wont_write_here: ->" << I_swear_I_wont_write_here << "<-\n"; // I_swear_I_wont_write_here[1] = 'A'; // <-- Does not compile. I'm bound by the oath I took. // Screw yesterday's oaths and give me an A. // This is well defined and works. (It works because the memory // is actually writable.) const_cast<char*>(I_swear_I_wont_write_here)[0] = 'A'; cout << "I_swear_I_wont_write_here: ->" << I_swear_I_wont_write_here << "<-\n"; } Declaring something const simply announces that you don't want to write through it; it does not mean that the memory concerned is indeed unwritable, and the programmer is free to ignore the declaration but must do so expressly with a cast. The opposite is true as well, but no cast is needed: You are welcome to declare and follow through with "no writing intended here" without doing any harm.
69,075,168
69,075,437
Finding the 4 corners of a rectangle which connects two moving objects
I am trying to make a line between two points, I am using sf::VertexArray shape(sf::Quads, 4); for this. This is my entire draw function: void Stick::draw(sf::RenderTarget& target, sf::RenderStates states) const { sf::VertexArray shape(sf::Quads, 4); sf::Vector2f p1Pos = this->p1->getPosition(); sf::Vector2f p2Pos = this->p2->getPosition(); shape[0].position = sf::Vector2f(p1Pos.x + 10.f, p1Pos.y + 10.f); shape[1].position = sf::Vector2f(p1Pos.x - 10.f, p1Pos.y - 10.f); shape[2].position = sf::Vector2f(p2Pos.x - 10.f, p2Pos.y - 10.f); shape[3].position = sf::Vector2f(p2Pos.x + 10.f, p2Pos.y + 10.f); shape[0].color = sf::Color::Green; shape[1].color = sf::Color::Green; shape[2].color = sf::Color::Green; shape[3].color = sf::Color::Green; target.draw(shape, states); } p1Pos and p2Pos are the center coordinates of the points. What this gets me is a line which obviously won't work with moving objects, since the corner points of the rectangles are fixed, here's some examples: (the red dot isn't moving while the white one is in this example) I would like to implement a solution so that the 'Stick' (rectangle) works regardless of the positions of the two points, and I will later on be adding some sort of onClick event for the sticks, so that I can delete them by clicking on them, so the solution would need to be compatible with that as well... Thanks!
You can find the normal of the line. This can be done by subtracting the positions p1Pos and p2Pos (and flipping either sign of x or y to get a 90° rotation) and dividing that by the length of the line. The length of the line can be found via Pythagoras theorem, since it can be thought of as the hypotenuse of a right triangle. auto diff = p1Pos - p2Pos; auto length = std::sqrt(diff.x * diff.x + diff.y * diff.y); auto normal = sf::Vector2f(p1Pos.y - p2Pos.y, p2Pos.x - p1Pos.x) / length; auto thickness = 15.0f; shape[0].position = sf::Vector2f(p1Pos.x + normal.x * thickness, p1Pos.y + normal.y * thickness); shape[1].position = sf::Vector2f(p1Pos.x - normal.x * thickness, p1Pos.y - normal.y * thickness); shape[2].position = sf::Vector2f(p2Pos.x - normal.x * thickness, p2Pos.y - normal.y * thickness); shape[3].position = sf::Vector2f(p2Pos.x + normal.x * thickness, p2Pos.y + normal.y * thickness); and here's the result:
69,075,254
69,200,322
Quaternion rotation works fine with y/z rotation but gets messed up when I add x rotation
So I've been learning about quaternions recently and decided to make my own implementation. I tried to make it simple but I still can't pinpoint my error. x/y/z axis rotation works fine on it's own and y/z rotation work as well, but the second I add x axis to any of the others I get a strange stretching output. I'll attach the important code for the rotations below:(Be warned I'm quite new to cpp). Here is how I describe a quaternion (as I understand since they are unit quaternions imaginary numbers aren't required): struct Quaternion { float w, x, y, z; }; The multiplication rules of quaternions: Quaternion operator* (Quaternion n, Quaternion p) { Quaternion o; // implements quaternion multiplication rules: o.w = n.w * p.w - n.x * p.x - n.y * p.y - n.z * p.z; o.x = n.w * p.x + n.x * p.w + n.y * p.z - n.z * p.y; o.y = n.w * p.y - n.x * p.z + n.y * p.w + n.z * p.x; o.z = n.w * p.z + n.x * p.y - n.y * p.x + n.z * p.w; return o; } Generating the rotation quaternion to multiply the total rotation by: Quaternion rotate(float w, float x, float y, float z) { Quaternion n; n.w = cosf(w/2); n.x = x * sinf(w/2); n.y = y * sinf(w/2); n.z = z * sinf(w/2); return n; } And finally, the matrix calculations which turn the quaternion into an x/y/z position: inline vector<float> quaternion_matrix(Quaternion total, vector<float> vec) { float x = vec[0], y = vec[1], z = vec[2]; // implementation of 3x3 quaternion rotation matrix: vec[0] = (1 - 2 * pow(total.y, 2) - 2 * pow(total.z, 2))*x + (2 * total.x * total.y - 2 * total.w * total.z)*y + (2 * total.x * total.z + 2 * total.w * total.y)*z; vec[1] = (2 * total.x * total.y + 2 * total.w * total.z)*x + (1 - 2 * pow(total.x, 2) - 2 * pow(total.z, 2))*y + (2 * total.y * total.z + 2 * total.w * total.x)*z; vec[2] = (2 * total.x * total.z - 2 * total.w * total.y)*x + (2 * total.y * total.z - 2 * total.w * total.x)*y + (1 - 2 * pow(total.x, 2) - 2 * pow(total.y, 2))*z; return vec; } That's pretty much it (I also have a normalize function to deal with floating point errors), I initialize all objects quaternion to: w = 1, x = 0, y = 0, z = 0. I rotate a quaternion using an expression like this: obj.rotation = rotate(angle, x-axis, y-axis, z-axis) * obj.rotation where obj.rotation is the objects total quaternion rotation value. I appreciate any help I can get on this issue, if anyone knows what's wrong or has also experienced this issue before. Thanks EDIT: multiplying total by these quaternions output the expected rotation: rotate(angle,1,0,0) rotate(angle,0,1,0) rotate(angle,0,0,1) rotate(angle,0,1,1) However, any rotations such as these make the model stretch oddly: rotate(angle,1,1,0) rotate(angle,1,0,1) EDIT2: here is the normalize function I use to normalize the quaternions: Quaternion normalize(Quaternion n, double tolerance) { // adds all squares of quaternion values, if normalized, total will be 1: double total = pow(n.w, 2) + pow(n.x, 2) + pow(n.y, 2) + pow(n.z, 2); if (total > 1 + tolerance || total < 1 - tolerance) { // normalizes value of quaternion if it exceeds a certain tolerance value: n.w /= (float) sqrt(total); n.x /= (float) sqrt(total); n.y /= (float) sqrt(total); n.z /= (float) sqrt(total); } return n; }
To implement two rotations in sequence you need the quaternion product of the two elementary rotations. Each elementary rotation is specified by an axis and an angle. But in your code you did not make sure you have a unit vector (direction vector) for the axis. Do the following modification Quaternion rotate(float w, float x, float y, float z) { Quaternion n; float f = 1/sqrtf(x*x+y*y+z*z) n.w = cosf(w/2); n.x = f * x * sinf(w/2); n.y = f * y * sinf(w/2); n.z = f * z * sinf(w/2); return n; } and then use it as follows Quaternion n = rotate(angle1,1,0,0) * rotate(angle2,0,1,0) for the combined rotation of angle1 about the x-axis, and angle2 about the y-axis.
69,075,453
69,076,419
Clang++ SCOPED_CAPABILITY produces "warning: releasing mutex 'locker' that was not held"
After attempting to implement the necessary annotations to an existing codebase, I was unable to remove a seemingly simple warning. I backed into the most simple example, and still no joy. I have cut-and-pasted the mutex.h header exactly as specified at Thread Safety Analysis. I cannot seem to do a scoped lock without producing a warning. Here is the code: #include "mutex.h" #include <iostream> // functions added just to complete the implementation void Mutex::Lock() { } void Mutex::GenericUnlock() { } // test a scoped lock void do_something(Mutex &m) { auto locker = MutexLocker(&m); std::cout << "Hello, world!\n"; } int main(int argc, char** argv) { Mutex my_mutex; do_something(my_mutex); } Compiling with clang++ -o thread_static_analysis thread_static_analysis.cpp -std=c++17 -Wthread-safety produces the following warning: thread_static_analysis.cpp:18:1: warning: releasing mutex 'locker' that was not held [-Wthread-safety-analysis] } ^ 1 warning generated. Either (1) I am missing something, or (2) this is a false-positive that must be ignored until a clang implementation issue is resolved. A search for such issues has as-yet given no useful results. clang version 10.0.0-4ubuntu1 Target: x86_64-pc-linux-gnu Thread model: posix
My understanding is that you are potentially creating a copy of temporary MutexLocker object in auto locker = MutexLocker(&m); (or thread safety analysis thinks you are creating it). The temporary is then destroyed and calls m.Unlock(). Then at the end of the function the locker object is destroyed and calls m.Unlock() again (thus causing a double release error).
69,075,569
69,076,271
Create a new log file every time a connection is made on my tool in C++
I need help with my log file. Every time I run the tool currently it gives logs on the same file, I need to add a code which can help me create a new file each time the connection is made. Help would be extremely appreciated. _mkdir(Path.c_str()); std::string FullFileName; FullFileName.append(Path); FullFileName.append(FileName); ::_sopen_s(&m_FileHandle, FullFileName.c_str(), _O_CREAT | _O_WRONLY | _O_BINARY, _SH_DENYWR, _S_IREAD | _S_IWRITE); return m_FileHandle != -1 ? ::_lseek(m_FileHandle, 0, SEEK_END) : -1;
Add auto end=std::chrono::system_clock::now(); std::time_t time = std::chrono::system_clock::to_time_t(end); FileName+=std::ctime(&time); before FullFileName.append(FileName); Will add the time to the filename so it will be unique. (If you want to start it multiple times a second you can add miliseconds) (also you have to #include <chrono>)
69,075,600
69,076,126
QT: QLabels not respecting borders
I'm creating a very basic QT Application and I'm running into the following problem: rasp4home::ui::MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { paletteSetup(); mTime.setText("00.22"); mTime2.setText("00.21232"); setLayout(new QBoxLayout(QBoxLayout::TopToBottom)); layout()->addWidget(&mTime); layout()->addWidget(&mTime2); } void rasp4home::ui::MainWindow::paletteSetup() { setAutoFillBackground(true); auto palette = QApplication::palette(); palette.setColor(QPalette::All, QPalette::Background, backgroundColor); palette.setColor(QPalette::All, QPalette::WindowText, textColor); setPalette(palette); } Now I would expect both labels to show up ordered top to bottom but I'm getting them on top of each other. What am I doing wrong?
You need to create a widget inside the main window and set it as the centralWidget, and set your layout in this widget. Note: this example was done on macOS, and so it doesn't have the same namespace. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { paletteSetup(); mTime.setText("00.22"); mTime2.setText("00.21232"); QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); layout->addWidget(&mTime); layout->addWidget(&mTime2); QWidget* mainWidget = new QWidget(); mainWidget->setLayout(layout); // QMainWindow will free mainWidget when appropriate setCentralWidget(mainWidget); }
69,075,666
69,075,819
How to find biggest out of four integers?
What is wrong in this code to find the greatest of four numbers using function? This is a question from Hackerrank C++ practice. Please give solution. This is the error i am getting: Solution.cpp: In function ‘int max(int, int, int, int)’: Solution.cpp:21:5: error: expected ‘}’ before ‘else’ else { cout << "b is greatest" << endl; } ^~~~ Solution.cpp:9:16: note: to match this ‘{’ if (a > b) { ^ Solution.cpp:22:5: error: no return statement in function returning non-void [-Werror=return-type] } ^ Solution.cpp: At global scope: Solution.cpp:23:1: error: expected declaration before ‘}’ token } ^ cc1plus: some warnings being treated as errors #include <iostream> #include <stdio.h> using namespace std; /* Add `int max_of_four(int a, int b, int c, int d)` here. */ int max(int a, int b, int c, int d) { if (a > b) { if (a > c) { if (a > d) { cout << "a is greatest" << endl; } else { cout << "d is greatest" << endl; } } else { cout << "c is greatest" << endl; } else { cout << "b is greatest" << endl; } } } int main() { int a, b, c, d; cin >> a >> b >> c >> d; int ans = max(a, b, c, d); cout << ans; return 0; }
The error is in line 22: you put else inside if bracket instead out of it, that's why you get compiler error: #include <iostream> #include <stdio.h> using namespace std; /* Add `int max_of_four(int a, int b, int c, int d)` here. */ int max(int a, int b, int c, int d) { if (a >= b && a >= c && a >= d) return a; if (b >= a && b >= c && b >= d) return b; if (c >= b && c >= a && c >= d) return c; return d; } int main() { int a, b, c, d; cin >> a >> b >> c >> d; int ans = max(a, b, c, d); cout << ans; return 0; } This function will return max out of 4 ints.
69,075,976
69,076,071
3 x 3 char vector in C++
I am starting learning C++ I try to declare a 3x3 vector and I did the following: std::vector<std::vector<char>> matrix(3, std::vector<int>(3)); Thats give me an error, althoug it works fine when the type is int: std::vector<std::vector<int>> matrix(3, std::vector<int>(3)); I would be very grateful if someone come explain what I am doing wrong and how to declare a 3x3 vector in C++. I know how to do that with a matrix. I have google but I have not been able to find the solution. I woul be very grateful If someone recommends a good book or an online course to learn C ++ for someone new to the subject. Thank you in advance and sorry for my english.
For me there is no any difference between 'char' matrix and between 'int' matrix. The thing is that you forgot a parenthesis at the end of line. It should be: std::vector<std::vector<int>> matrix(3, std::vector<int>(3)); or std::vector<std::vector<char>> matrix(3, std::vector<char>(3)); The point is that you should use a compilator to detect more easily this errors. For example in Visual Studio I get: error C2059: syntax error : ';'
69,076,028
69,076,171
Extending built-in classes in C++
I know extending built-in classes in C++ is deprecated, but still I want to do it for some reasons. I wanna add my custom methods to a class (str) that extends/inherits from the std::string class (this is for an example) But when I do so there's some problem I am facing with the methods that are already there in the std::string class (built-in methods), for example, #include <bits/stdc++.h> using namespace std; class str : public string { public: string s; str(string s1) { s = s1; //ig the problem is here } }; int main() { str s("hello world"); cout << s.size(); //prints out 0 not 11 => length of "hello world" } How do I get around this?
std::string doesn't know about your string s; member. It cannot possibly use it in its methods. If you want to use inheritance over composition, you need to use whatever is available under public interface of std::string - in this case, its constructors. class str : public string { public: str(string s1): string(s1) //initialize base class using its constructor { } }; // or class str : public string { public: using string::string; //bring all std::string constructors into your class }; As a footnote, there is nothing deprecated about inheriting from standard containers, but they are not meant for that and you can only do a very limited set of things safely. For example, this is Undefined Behaviour: std::string* s = new str("asdf"); delete s; // UB! More detailed explanation in this question. Also, you should strongly avoid <bits/stdc++.h> and using namespace std; and in particular you should not mix them. You will strip yourself of almost every name and it produces hard to find bugs.
69,076,462
69,076,703
LVN_GETDISPINFO receiver -- whether the list control's parent must be as it?
In the WinAPI, there is the ListView control. This control may be adjusted to work in so called virtual mode when it doesn't hold any data. Instead, it queries this data from its parent window. At least, accordingly to the documentation. I'm working currently on an old MFC-driven project. I am faced with a strange thing: the handler for the notification specified in the subject is placed in the CListCtrl successor class. That is, the list control sends the notifications to itself. And this works. Though, there is nothing surprising here at the technical point of view. Probably... But, on the other hand, why then is the parent window mentioned in the documentation as the notification receiver? My question: whether this is architecturally the right idea to place the LVN_GETDISPINFO's handler in the list control class, not in the parent window class as the documentation says? Is there some advantages in this solution over the documented one?
MFC has message reflection technique. (The same thing is available to ATL/WTL). The notification messages still arrive to the parent, but the parent reflects them to the controls, altering message code. When you use a control without overriding its behavior and not subclassing it, the parent window is responsible for its behavior, as you use a generic control. When you subclass controls to define more specific behavior, then it may be better to define message handing in the subclassed control, to prevent this spreading between control and its parent. VCL, the UI framework available in Delphi and C++Builder, does the same thing. It reflects notification messages from parent window to child control, transforming them into events in the child control classes. Events are fired by controls, controls are always subclassed by the framework, and notification messages are always handled as reflected internally.
69,076,466
69,077,550
Why We Couldn't Use Two Different enum Interchangeable?, e.g. As Function Parameter?
With this code: enum A { _1 }; enum B { _2 }; void f(A) {} int main() { f(_2); } A C++ compiler complains that couldn't convert B to A (try it on Wandbox), But with a C compiler we just get a warning (I know C++ is not C): main.c: In function ‘f’: main.c:11:6: warning: type of ‘A’ defaults to ‘int’ [-Wimplicit-int] 11 | void f(A) | ^ main.c:11:6: warning: unused parameter ‘A’ [-Wunused-parameter] Which it's make sense (for me) because as far as I know: An enum is just an int (whatever short int, int, ... depending on the value of the enumerations). So: Why the C++ compiler doesn't let me use B as A? And it's fine to use f(static_cast<A>(_2));? My environment: Compiler: GCC 11.1.0 Compiler Flags: -Wall -Wextra -Wpedantic OS: ArchLinux 5.13.13-arch1-1
In C++, the function void f(A) {} is interpreted to mean “a function named f that takes an argument of type A, and its parameter has no name.” However, the C language requires that all function parameters have names (this is different than C++), so C interprets this as “a function f that takes a parameter named A, and since A has no associated type the compiler thinks it’s looking at older C code in which parameters with no names have type int, so that’s a function named f taking an int named A.” The warning you get from gcc is trying to tell you that, but it’s hard to know what it means without that backstory. (The use of function parameters without types as implicitly being integers is something that hasn’t been legal C for decades, but for backwards compatibility some C compilers accept it anyway.) Independently - enumerated types have integral values but are not themselves integers. In both C and C++ you can implicitly convert an integer to an enumerated type. However, in C++ (and I believe C as well, but I’m not sure) enumerated values aren’t integers and can’t be treated as enumerated values of another type without a cast. So yes, you could call the function by explicitly casting one enumerated type to another, but you can’t call the function by passing an enumerated constant of the wrong type.
69,076,480
69,076,559
How to clear all elements in a vector except for the last one in a vector in c++
As the title says, I have a vector that has 11 integer elements ranging from 1 - 11. I am trying to use the .erase() function to clear all elements in my vector except for the last one. I am having trouble using iterators to do it as they clear out all elements except the first one. I tried a lot of solutions from the internet such as using .rbegin() and .rend() but they just gave me an error. Here is my code below:- #include <vector> #include <iostream> using namespace std; vector<int> epos = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; vector<int>::iterator it1, it2; int main() { it1 = epos.begin(); it2 = epos.end(); epos.erase(it1, it2); for (int i=0; i<=epos.size(); i++) { cout << epos[i] << ' '; } return 0; } I am still a beginner in c++ and would appreciate any help!
You were almost there, use this syntax : // make sure we end up with a vector with one element in it. // empty lists will stay empty if(epos.size()>1) { epos.erase(epos.begin(), epos.end() - 1); } And did you know that you can also iterate over containers like this? for (auto v : epos) { cout << v << ' '; } It's called a range based for loop, and prevents you from making mistakes with indices
69,076,536
69,076,616
Why aren't these strings equal
I'm learning C++ out of curiosity - my current task is to check if a string is a palindrome. What should be happening is the string is reversed, and I use the Equal To (==) operator to compare the original and reversed string. But for some reason, they're all returning as false, and I can't understand why. #include <iostream> using namespace std; string reverse_string(string text) { int string_size = text.size(); string reversed = ""; while (string_size >= 0) { reversed += text[string_size]; string_size--; }; return reversed; } bool is_palindrome(string text) { if (reverse_string(text) == text) { return true; }; return false; } int main() { cout << is_palindrome("madam") << "\n"; cout << is_palindrome("ada") << "\n"; cout << is_palindrome("lovelace") << "\n"; } For the record, I'm doing this via Codeacademy - It's returning false (0) for both the browser CMD prompt, as well as local. Something I'm noticing that if I try to log the comparison (reversed_string == text), I'm getting a single random integer. I'm not sure why that's happening; shouldn't it just be returning 0 or 1?
C++ indexing is zero-based. Thus string_size, while initially being the length of the string, is one past the end of the string. So in your loop’s first iteration you are indexing past the string, leading to the zero termination character ('\0') being returned. To fix this it’s enough to decrement the index just before performing the indexing operation.
69,076,734
69,077,010
How can I convert the given code to a mathematical function?
I am trying to convert a recursion into a mathematical formula. The code snippet (c++) below is a simplified variant. The values look like an exponential function, however I am trying to find a closed form. For example, rec(8, 6) is 1287. As an assumption, I first assumed 6 to be constant and tried to find an exponential function for rec(?, 6). However, these results were extremely inaccurate. Does anyone have an idea how I could achieve a closed function? Many thanks int rec(const int a, const int b, const int c = 0, const int d = 0) { int result = 0; if (d == a) ++result; else for (int i = 0; c + i < b; ++i) result += rec(a, b, c + i, d + 1); return result; }
There is no universal method of converting a recursive function to a mathematical, closed function. In your case the answer is the number of "b-1" combinations from an "a"-element set, that is, a!/((a-b+1)!(b-1)!). Proof: Your rec is equivalent to int rec(const int a, const int b) { if (0 == a) return 1; int result = 0; for (int i = 0; i < b; ++i) result += rec(a - 1, b - i); return result; } because all that matters is a-d and b-c. If a==0, rec returns 1 If a>0, it returns the sum of rec(a-1, i) where i is in (0, b). This is true and only true for the combinations. If you ask me to prove that, I will, but the plain text format is not good for mathematical proofs Edit: A general idea.: print all rec(i,j) as a table and try to spot the rule by looking at the table. I did: for (int i = 0; i != 10 ; ++i){ for (int j = 0; j != 10; ++j){ cout << rec(i, j) << "\t"; } cout << endl; } In this way I spotted that it is the Pascals_triangle
69,076,780
69,076,932
Re-using sqlite3 statement for new query
In order to commit an sqlite query in C++ we need to create an sqlite3_stmt, prepare it via sqlite3_prepare_v2, sqlite3_bind_ potential values to the statement and then sqlite3_step through it. Now, in a function that e.g. performs two separate sqlite queries, can I just re-use the same sqlite3_stmt by calling sqlite3_prepare_v2 on it again or do I need to explicitly sqlite3_reset the statement beforehand? E.g. void mySqliteFunction() { sqlite3_stmt* stmt; int rc; rc = sqlite3_prepare_v2(<connection>, <sql string>, ..., &stmt, ...); rc = sqlite3_step(stmt); if (rc == SQLITE_OK) { rc = sqlite3_prepare_v2(<connection>, <other sql string>, ..., &stmt, ...); // is this valid? rc = sqlite3_step(stmt); } rc = sqlite3_finalize(stmt); return; }
The stmt prepared statement variable in your code simply holds a handle for the prepared statement and its value is populated by the sqlite3_prepare_v2() call. The problem in your code currently is that you fail to finalize correctly. You are responsible for deleting the compiled SQL statement using sqlite3_finalize(). If you correctly finalized the initial prepared statement after use, then you could reuse the stmt variable, otherwise you are leaking resources. The sqlite3_reset() function is designed to reset a given prepared statement to allow it to be re-executed. It's not designed for the case where you will actually prepare a different SQL statement.
69,076,834
69,077,116
Getting Unexpected Output when using array in struct
I am new to the world of programming in c++. I am getting an unexpected thing when running following code: #include <iostream> using namespace std; typedef struct person { int age; char* name; float salary; bool gender; } prsn; enum Gender { male, female }; int main() { prsn p1; p1.name[0] = 'A'; p1.name[1] = 'd'; p1.name[2] = 'i'; p1.name[3] = 't'; p1.name[4] = 'y'; p1.name[5] = 'a'; p1.age = 17; p1.salary = 100000; p1.gender = male; // enum used cout << "Person p1's info:\nName: " << p1.name << "\nAge: " << p1.age << "\nSalary: " << p1.salary << "\nGender: " << p1.gender; return 0; } When running above code at printing p1.name always getting 4 random characters different everytime. My g++ version: g++.exe (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0, using Visual Studio Code(IDE). Thanks!
So you can learn on your mistake lets first see what is wrong with your code. typedef struct person { int age; char* name; float salary; bool gender; } prsn; char * is pointer to some address. So if you do not use new it will point to random address that was previously written to the memory. Your alternatives are to use constructor and allocate some memory: struct person () : name (new name(10)) { } or to use std::string. typedef struct person { int age; std::string name; float salary; bool gender; } prsn; One more note that points me to the thing that you are learning C++ from wrong place is typedef struct person { } prsn; In C this is done to avoid initializing your struct with: int main () { struct person p1; ... } In C++ you can easily do it this way: int main () { person p1; ... } remember struct is a class with public members by default in C++. #include <iostream> using namespace std; struct person { int age; char* name; float salary; bool gender; person () : age (0), char (new char[20]()), salary (0.0), gender (true) { } }; enum Gender { male, female }; int main() { person p1; p1.name[0] = 'A'; p1.name[1] = 'd'; p1.name[2] = 'i'; p1.name[3] = 't'; p1.name[4] = 'y'; p1.name[5] = 'a'; p1.age = 17; p1.salary = 100000; p1.gender = male; // enum used cout << "Person p1's info:\nName: " << p1.name << "\nAge: " << p1.age << "\nSalary: " << p1.salary << "\nGender: " << p1.gender; return 0; } There are some more errors in your code, so my suggestion is pls switch your book, website whatever you are learning C++ from. As suggested, you should avoid using raw pointers in C++. Instead uses std::shared_ptr() and std::unique_ptr().
69,076,861
69,077,059
unordered_map not being updated properly
Trying to update an unordered map using the following code snippet to have only lowercase letters, but it seems to stop after erasing one key-value pair { [33 '!']: 3 } and exits the loop leaving the rest of the map unvisited and prints the partly updated map. for (auto &i : m) if (!(i.first >= 'a' && i.first <= 'z')) m.erase(i.first); Following debugging images revealed the above The complete code is herewith: #include <iostream> #include <unordered_map> #include <algorithm> using namespace std; int main() { string line = "Try! Try! Try! until you succeed"; //getline(cin, line); unordered_map<char, int> m; for (int i = 0; line[i]; i++) { char lower = (char)tolower(line[i]); if (m.find(lower) == m.end()) m.insert(make_pair(lower, 1)); else m[lower]++; } for (auto &i : m) //only updates until ! if (!(i.first >= 'a' && i.first <= 'z')) m.erase(i.first); cout<<"The freq. map so formed is : \n"; for (auto &i : m) cout<<i.first<<"\t"<<i.second<<endl; return 0; } /* OUTPUT : The freq. map so formed is : d 1 t 4 r 3 e 2 y 4 l 1 o 1 5 n 1 u 3 i 1 s 1 c 2 */ Can't seem to understand why it won't loop through the complete unordered map. Also, not sure if this helps towards a clear picture but, when the standard map is used instead of unordered map it gives an Address Boundary Error at the same instance where the next character of the map needs to be updated like so:
You cannot erase the element of a map while iterating this way. When you erase the iterator, it becomes invalidated, so you need to explicitly increment it before you delete the element. Try this code instead: for (auto it = m.begin(); it != m.end();) if (!((*it).first >= 'a' && (*it).first <= 'z')) it = m.erase(it); else ++it;
69,077,002
69,077,093
Compiler warning (or static analysis) for subtraction of unsigned integers?
Consider the following program: #include <iostream> int main() { unsigned int a = 3; unsigned int b = 7; std::cout << (a - b) << std::endl; // underflow here! return 0; } In the line starting with std::cout an underflow is happening because a is lesser than b so a-b is less than 0, but since a and b are unsigend so is a-b. Is there a compiler flag (for G++) that gives me a warning when I try to calculate the difference of two unsigend integers? Now, one could argue that an overflow/underflow can happen in any calculation using any operator. But I think it is more dangerous to apply operator - to unsigend ints because with unsigned integers this error may happen with quite low (to me: "more common") numbers. A (static analysis) tool that finds such things would also be great but I much prefer a compiler flag and warning.
GCC does not (afaict) support it, but Clang's UBSanitizer has the following option [emphasis mine]: -fsanitize=unsigned-integer-overflow: Unsigned integer overflow, where the result of an unsigned integer computation cannot be represented in its type. Unlike signed integer overflow, this is not undefined behavior, but it is often unintentional. This sanitizer does not check for lossy implicit conversions performed before such a computation
69,077,134
69,078,255
Transposition table makes algorithm slower (am I doing it wrong?)
I store every position with a Zobrist key (64-bit). I store theses in a std::vector. At the beginning I std::vector::reserve(1,000,000). When a position is searched, it takes a long time to check if the key is in the vector, and if it is, a long time to locate it. This happens at later depths when the vector of transpositions becomes so long it's faster just to re-compute the position instead of looking for a transposition. What I've tried: -inserting the keys into the vector sorted from least to greatest and using a binary search to locate them later. -pushing the key to the vector, and every time I want to check for a key, looping through the vector to check for a matching key. Also in case it helps hashing a key efficiently is not a problem, I have already implemented it so that it updates every time a move is made.
You can use a vector whose size is a power of 2, and mask off the corresponding part of the Zobrist hash to get an index into the vector. For example: std::vector<whatever> x(0x100000) std::int64_t hash = get_hash_from_somewhere(); whatever& value = x[hash & 0xFFFFF]; You might want to use a more sophisticated mask if that one leads to too many collisions.
69,077,322
69,077,397
Remove Title Bar in ImGui
I would like to know that how do I remove the title bar from an ImGui Window. I am using C++ with GLFW for this.
You can use the ImGuiWindowFlags_NoTitleBar flag when creating the window: ImGui::Begin("Window Name", &is_open, ImGuiWindowFlags_NoTitleBar); // ... render window contents ... ImGui::End(); An example of this and other flags you can use on an ImGui Window is located in imgui_demo.cpp.
69,077,553
69,102,765
QT5 Cannot get different custom context menus to work for different tables
I am trying to get multiple (3) custom context menus to work, each for a different table view. My code works fine in debug but in release I am not getting the different context menus - the best I have managed to get is either the first menu working (and the others disabled) or displaced menus (i.e. the menu is offset relative to the top left corner of the screen not at the cursor). The code: void DisplayWidget::Init() { // ParameterData Table pLabel_Param = new QLabel(tr("PARAMETER DATABASE")); pTableW_Param = new QTableWidget(this); // EmuNameIn Table pLabel_EmuNameIn = new QLabel(tr("EMULATOR NAME IN")); pTableW_EmuNameIn = new QTableWidget(this); // EmuNameOut Table pLabel_EmuNameOut = new QLabel(tr("EMULATOR NAME OUT")); pTableW_EmuNameOut = new QTableWidget(this); // Setup context menus pTableW_Param->setContextMenuPolicy(Qt::CustomContextMenu); connect(pTableW_Param, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customMenuRequested_Param(QPoint))); pTableW_EmuNameIn->setContextMenuPolicy(Qt::CustomContextMenu); connect(pTableW_EmuNameIn, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customMenuRequested_EmuNameIn(QPoint))); pTableW_EmuNameOut->setContextMenuPolicy(Qt::CustomContextMenu); connect(pTableW_EmuNameOut, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customMenuRequested_EmuNameOut(QPoint))); } void DisplayWidget::customMenuRequested_Param(QPoint pos) { if(!pTableW_Param || (sizeOfTable_Param == 0)) return; QModelIndex index = pTableW_Param->indexAt(pos); QMenu *menuParam = new QMenu(this); if(IsEmuValid()) menuParam->addAction(pAct_AddParam); menuParam->addAction(pAct_SearchTable_Param); menuParam->popup(pTableW_Param->viewport()->mapToGlobal(pos)); } void DisplayWidget::customMenuRequested_EmuNameIn(QPoint pos) { if(!pTableW_EmuNameIn || !IsEmuValid() || (sizeOfTable_EmuNameIn == 0)) return; QModelIndex index = pTableW_EmuNameIn->indexAt(pos); QMenu *menuNameIn = new QMenu(this); menuNameIn->addAction(pAct_DeleteFromNameIn); menuNameIn->addAction(pAct_Toggle_InToOut); menuNameIn->addAction(pAct_SearchTable_EmuNameIn); menuNameIn->addAction(pAct_SortTable_EmuNameIn); menuNameIn->popup(pTableW_EmuNameIn->viewport()->mapToGlobal(pos)); } void DisplayWidget::customMenuRequested_EmuNameOut(QPoint pos) { if(!pTableW_EmuNameOut || !IsEmuValid() || (sizeOfTable_EmuNameOut == 0)) return; QModelIndex index = pTableW_EmuNameOut->indexAt(pos); QMenu *menuNameOut = new QMenu(this); menuNameOut->addAction(pAct_DeleteFromNameOut); menuNameOut->addAction(pAct_Toggle_OutToIn); menuNameOut->addAction(pAct_SearchTable_EmuNameOut); menuNameOut->addAction(pAct_SortTable_EmuNameOut); menuNameOut->popup(pTableW_EmuNameOut->viewport()->mapToGlobal(pos)); } I have tried looking / searching for the same problem, but failed to resolve the issue.
I have found a way to make it work although I still do not understand why my code failed. The way to make it work was to swap out the following: menuNameOut->popup(pTableW_EmuNameOut->viewport()->mapToGlobal(pos)); menuNameIn->popup(pTableW_EmuNameIn->viewport()->mapToGlobal(pos)); menuParam->popup(pTableW_Param->viewport()->mapToGlobal(pos)); for: menuNameOut->exec(QCursor::pos()); menuNameIn->exec(QCursor::pos()); menuParam->exec(QCursor::pos());
69,077,753
69,096,710
Why does std::get only have two function overloads for ranges::subrange?
There are four pair-like types in the standard, namely std::array, std::pair, std::tuple, and ranges::subrange, where the overload of std::get for ranges::subrange is defined in [range.subrange#access-10]: template<size_t N, class I, class S, subrange_kind K> requires (N < 2) constexpr auto get(const subrange<I, S, K>& r); template<size_t N, class I, class S, subrange_kind K> requires (N < 2) constexpr auto get(subrange<I, S, K>&& r); Effects: Equivalent to: if constexpr (N == 0) return r.begin(); else return r.end(); And ranges::subrange::begin() has two overloads: constexpr I begin() const requires copyable<I>; [[nodiscard]] constexpr I begin() requires (!copyable<I>); I noticed that this std::get only has two overloads, and there is no corresponding overload for non-const lvalue reference, which makes it impossible for us to apply std::get to lvalue input_range with non-copyable iterator (godbolt): #include <ranges> #include <sstream> int main() { auto ints = std::istringstream{"42"}; auto is = std::ranges::istream_view<int>(ints); std::ranges::input_range auto r = std::ranges::subrange(is); auto b = r.begin(); // OK auto b2 = std::get<0>(r); // Error, passing 'const subrange' as 'this' argument discards qualifiers } So why does std::get only have two function overloads for ranges::subrange? Does it miss the overloads for ranges::subrange& and const ranges::subrange&&? Is this a standard defect or is it intentional?
As a general rule, a fully-formed subrange in well-defined code represents a valid range, and if it stores a size, then the size is equal to the size of the range. This is reflected in the precondition of every non-default constructor (the default constructed state can still be partially-formed). This got slightly muddled by the introduction of move-only iterators (since the non-const begin needs to move the iterator out) but remains the design intent. In other words, subrange is quite unlike pair, tuple, or array. Those three are aggregates of values with no semantics, and their get overloads reflect that by transparently propagating cv-qualification and value category. subrange, on the other hand, does have semantics - it's not merely a pair of iterator and sentinel. Its get is only for reading, never for writing. That's why get on a subrange returns by value. It doesn't make much sense to provide a non-const lvalue get overload; returning by mutable reference is out of the question; returning by reference to const is unlike everything else (and also surprising). Returning by value means that in the only case it makes a difference, get on an lvalue subrange is a destructive operation, which would be quite unexpected.
69,078,153
69,078,342
Trying to figure out Error when attempting to add a text box in a MS Visual Studio C++ Dialog
For Microsoft Visual Studio C++ Community 2019, I'm trying to add a textbox into a Dialog box I made. I'm having trouble adding a textbox into it by right clicking on the new dialog box and using "Add variable". Keeps saying - "Did not find a dialog class with the specified ID 'IDD_DIALOG1'. I tried adding the class name in the Dialog properties under the "Class Name" field. But that did not work. Thanks in advance for your help.
Try using the "Edit control" in the toolbox. the youtube video: VC++ / C++ MFC tutorial 1: Creating a Dialog box for user input will be able to assist you further. Cheers.
69,078,570
69,198,219
How do I change/set DNS with c++?
I'm trying to change/set DNS with c++. I've been unable to find any resources on this currently. public static NetworkInterface GetActiveEthernetOrWifiNetworkInterface() { var Nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault( a => a.OperationalStatus == OperationalStatus.Up && (a.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || a.NetworkInterfaceType == NetworkInterfaceType.Ethernet) && a.GetIPProperties().GatewayAddresses.Any(g => g.Address.AddressFamily.ToString() == "InterNetwork")); return Nic; } public static void SetDNS(string DnsString) { string[] Dns = { DnsString }; var CurrentInterface = GetActiveEthernetOrWifiNetworkInterface(); if (CurrentInterface == null) return; ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { if (objMO["Description"].ToString().Equals(CurrentInterface.Description)) { ManagementBaseObject objdns = objMO.GetMethodParameters("SetDNSServerSearchOrder"); if (objdns != null) { objdns["DNSServerSearchOrder"] = Dns; objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null); } } } } } This c# code I found from Change DNS in windows using c# works great. I'm trying to do the same in c++.. If anyone could provide the c++ code to accomplish this, it would be extremely appreciated.
I ended up researching more and found something that worked for me. I was trying to have requests to domain go through CloudFlare's DNS 1.1.1.1 since many ISPs blocked my domain. This is the solution I'm using: std::ofstream myfile; myfile.open("C:\\Windows\\System32\\drivers\\etc\\hosts"); myfile << "1.1.1.1 example.com"; myfile.close();
69,079,259
69,080,243
How can I run many C++ source files in one CLion project?
I am using CLion as an IDE. When I create a project a main.cpp is automatically added. I would like to add 30-40 cpp files in a project and keep them as one project. Basically, I just wanna create many .cpp files in one folder and make CLion run them. I can do this in Pycharm by simply creating a project and add as many .py files as I want. But when I want to do this on CLion I got an error. Is it possible to add many .cpp files in a project in CLion, if yes, how can I do that? An error could be seen in the below. I added a second.cpp to the project and run and this error message appears. ====================[ Build | trial | Debug ]=================================== /Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake --build /Users/mertsaner/CLionProjects/trial/cmake-build-debug --target trial -- -j 6 Scanning dependencies of target trial [ 66%] Building CXX object CMakeFiles/trial.dir/main.cpp.o [ 66%] Building CXX object CMakeFiles/trial.dir/second.cpp.o [100%] Linking CXX executable trial duplicate symbol '_main' in: CMakeFiles/trial.dir/main.cpp.o CMakeFiles/trial.dir/second.cpp.o ld: 1 duplicate symbol for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make[3]: *** [trial] Error 1 make[2]: *** [CMakeFiles/trial.dir/all] Error 2 make[1]: *** [CMakeFiles/trial.dir/rule] Error 2 make: *** [trial] Error 2
Clion uses Cmake. If you want to create multiple executable files for eg with names (ex1.cpp, ex2.cpp. ex3.cpp) in one directory, you will do something like this in the CMake file of your directory. cmake_minimum_required(VERSION 3.18) project(some_project) set(CMAKE_CXX_STANDARD 20) add_executable(executable1 ex1.cpp) add_executable(executable2 ex2.cpp) add_executable(executable3 ex3.cpp) and so on..
69,079,419
69,079,569
How I can read more than 16384 bytes using OpenSSL TLS?
I'm trying to read a big chunk of data using OpenSSL TLS sockets, and I'm always stuck at 16384 being read. How I can read more? SSL_CTX* ctx; int server; SSL* ssl; int bytes; std::string result; std::vector<char> buffer(999999999); ctx = InitCTX(); server = OpenConnection(); ssl = SSL_new(ctx); SSL_set_fd(ssl, server); if (SSL_connect(ssl) != -1) { std::string msg = 0; //request here SSL_write(ssl, msg.c_str(), msg.size()); bytes = SSL_read(ssl, &buffer[0], buffer.size()); } result.append(buffer.cbegin(), buffer.cend());
The TLS protocol encapsulates data in records that are individually encrypted and authenticated. Records have a maximum payload of 16 kB (minus a few bytes), and SSL_read() will only process one record at a time. I suggest you change the size of buffer to 16384 bytes to match. Note that allocating ~1 GB as you did is way too much anyway, as that amount of memory would then potentially not be available to other processes. Then, as rustyx mentioned in the comments, just read more in a loop. If the other side can respond with multiple records, it would be good if it would somehow send the size of the response in the first record, so you would know how much to read.
69,079,644
69,079,740
Question std::cout in C++ how exactly does the stream work?
Say we have: std::cout << "Something"; How exactly is this working? I just want to make sure I understand this well and, from what I've been reading, is it okay to say that basically the insertion operator inserts the string literal "Something" into the standard output stream? But what happens after that? Where does the standard output stream lead? Can anyone explain this? That's basically the only part I don't get: I have the string literal "Something" in the standard output stream, but where does the stream lead?
The technical details vary between the different Operating Systems, but the basics are the same: Every program has usually 3 standard streams: out (cout), in (cin), and err (cerr) (same as out, but used for errors). Those streams are nothing on their own; they exist to be used by a third party. That third party may be, for example, the terminal. When you execute a program form the terminal, it attaches to the program streams and show their output/request their input in the terminal. If you wanted to do the same, you could execute a command yourself from your program, and take the out/in/err streams to read or write from/to them. You have an example of that here: How do I execute a command and get the output of the command within C++ using POSIX? Edit: When talking about C++, remember that cout << "anything" is just syntactic sugar for the function cout.operator<<("anything"). And that function "simply" writes to the stream
69,080,400
69,080,440
C++ Tilde Operator on bool
I've done the LinkedIn C++ Assessment and got the following question: What is the result from executing this code snippet? bool x=true, x=false; if(~x || y) { /*part A*/ } else { /*part B*/ } I don't know anymore what the answers were, but I thought "B" should be displayed, right? I thought by "~", x is inverted ("bitwise NOT") and is therefore no longer "true" But when I run the code, I get "A": Code: #include <iostream> int main() { bool x = true, y = false; std::cout << "x: " << x << std::endl; std::cout << "~x: " << ~x << std::endl; if (~x || y) { std::cout << "A" << std::endl; } else { std::cout << "B" << std::endl; } return 0; } Output: x: 1 ~x: -2 A Can someone explain this to me?
In this expression ~x there is applied the integral promotions to the operand x of the type bool. The result of the promotion is an object of the type int that has the value equal to 1 like (in binary) 00000000 00000000 00000000 00000001 The operator ~ inverses bits and you will get 11111111 11111111 11111111 11111110 From the C++ 14 Standard (5.3.1 Unary operators) 10 The operand of ~ shall have integral or unscoped enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. The type of the result is the type of the promoted operand. and (4.5 Integral promotions) 6 A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one. 7 These conversions are called integral promotions. As this value is not equal to 0 then used as an operand of the logical OR operator it is implicitly converted to the boolean value true. From the C Standard (5.15 Logical OR operator) 1 The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true. and (4.12 Boolean conversions) 1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
69,080,686
69,080,707
Why doesn't braced initialization throw a narrowing error when converting from double to float?
Two things every C++ tutorial mentions early on: Braced initialization is generally superior when possible, because it will throw an error during a narrowing conversion such as int narrow{1.7}; // error: narrowing conversion of '1.7e+0' from 'double' to 'int' You must explicitly declare floats as float literals, otherwise they will default to double literals float some_float{1.7f}; However, when working with the g++ compiler on Windows, I've discovered something odd - float narrow{1.7}; // still a float despite no f postfix double not_narrow{1.7}; // actually a double This code compiles without any errors, and sizeof(narrow) returns 4, where sizeof(not_narrow) returns 8, as expected. Hovering over 1.7, VSCode identifies it as a double literal ~=1.699999999999999956, but float has then narrowed it to ~=1.700000048. I thought it might be simply that 1.7 is both valid as a float and a double, so I tried float narrow{1.699999999999999956}; but this produces an identical result. Why doesn't braced initialization throw an error (warning, diagnostic message, anything) here for narrowing a double literal to a float? Is this g++ specific, or a quirk of C++ in general? I'd love to understand better.
A conversion from a floating-point type to a shorter floating-point type is not a narrowing conversion if "the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly)" (C++20 [dcl.init.list]/7.2). If you think about it, double{1.7} and float{1.7} are most likely both inexact. But if you write the latter, it's reasonable to assume that you mean it, and there's not much to be gained from prohibiting this.
69,081,332
69,081,351
How do I declare a template parameter of type Range?
I am not sure if it is a correct code, but at least as an example, I was able to declare a template parameter of type rage as follows: template <std::ranges::range Range> inline auto TransformIt(Range r) { return r | std::views::transform([](int n) { return n * n; }); } int main() { std::vector<int> v; auto r = TransformIt(v); return 0; } but I was unable to improve my code like this: template <std::ranges::range<int> Range> inline auto TransformIt(Range r) { return r | std::views::transform([](int n) { return n * n; }); } what is the right syntax for that?
std::ranges::range<int> doesn't do what you think it does. This is the concept range applied over int, i.e. you check weather int is a range ... which it isn't. One way of achieving what you need is: template <std::ranges::range Range> requires std::same_as<std::ranges::range_value_t<Range>, int> auto TransformIt(Range r) { return r | std::views::transform([](int n) { return n * n; }); } If you want you can create a new concept: template <class R, class Value> concept range_over = std::ranges::range<R> && std::same_as<std::ranges::range_value_t<R>, Value>; template <range_over<int> Range> auto TransformIt(Range r) { return r | std::views::transform([](int n) { return n * n; }); } Depending on your needs you might want to change same_as with convertible_to. Side note: as TransformIt is a template function inline keyword is redundant and idiomatically not used.
69,082,348
69,082,458
Creating a struct without a variable name, how is it useful?
I just came across this syntax and I am not sure where can I really make use of it. std::hash<std::string>{}(str); I see that no variable name was used here for reference to the record created and I would like to know why anyone would be using this syntax to create structs/record except for calling functions/overloaded operators?
Essentially, yeah, you do that if you want to call a constructor or a member function, but you don't care about the object itself. From my experience, this is most common with RAII types where the lifetime of the object is tied to the resource. You create an object, thereby acquiring a resource (like a file or sth), and then do something with that resource. Now say you don't need it afterwards. If you don't give it a name, it will call the destructor directly after you're done with it since the 'variable' (which doesn't even really exist) goes out of scope immediately, thereby freeing the resource.
69,082,581
69,085,447
dpc++ error Command group submitted without a kernel or a explicit memory operation. -59 (CL_INVALID_OPERATION)
I was trying out sycl/dpc++. I have written the below code. I am creating an array deviceArr on device side to which values of hostArr are copied using memcpy and then values of the devicearray are incremented by 1 using a parallel_for kernel and values are copied back with memcpy. queue q; std::array<int, 10> hostArr; for (auto &val : hostArr) val = 1; int *deviceArr = malloc_device<int>(10, q); q.submit([&](handler &h) { memcpy(deviceArr, &hostArr[0], 10 * sizeof(int)); }); q.submit([&](handler &h) { h.parallel_for(10, [=](auto &idx) { deviceArr[idx]++; }); }); q.submit([&](handler &h) { memcpy(&hostArr[0], deviceArr, 10 * sizeof(int)); }); This code compiles fine but while running this I get the below error during run time. **Command group submitted without a kernel or a explicit memory operation. -59 (CL_INVALID_OPERATION)** However I can see all my queues submitted have either a kernel(parallel_for) or a memory operation(memcpy). Can anybody explain why this error occurs?
Only the code and functions called from a kernel are seen by the device compiler. This means that your memcpy is the regular std::memcpy. SYCL and the device compiler have no way of knowing that you put that here. To submit your memcpy, you should write instead h.memcpy(...)! Or use the shorthand q.memcpy(). And just to finish, given that you're using USM, you have to take care of the synchronisation. There's no guarantee that the three kernels will be executed in the same order, unless you have a in order queue. You can either wait() after each submission or use h.depends_on(...)
69,082,701
69,082,778
Preventing multiple definition in C++
I am getting error: /usr/bin/ld: /tmp/ccCbt8ru.o: in function `some_function()': Thing.cpp:(.text+0x0): multiple definition of `some_function()'; /tmp/ccc0uW5u.o:main.cpp:(.text+0x0): first defined here collect2: error: ld returned 1 exit status when building a program like this: main.cpp #include "common.hpp" #include "Thing.hpp" int main() { some_function(); } common.hpp #pragma once #include <iostream> void some_function() { std::cout << "something" << std::endl; } Thing.hpp #pragma once class Thing { public: void do_something(); }; Thing.cpp #include "Thing.hpp" #include "common.hpp" void Thing::do_something() { some_function(); } I'm compiling with: g++ main.cpp Thing.cpp -o main.out I've also tried using include guards instead of #pragma once, but it didn't seem to work either. Is there something I am forgetting here?
#pragma once and include guards can only prevent multiple definitions in a single translation unit (a .cpp file). The individual units know nothing about each other, and so cannot possibly remove the multiple definition. This is why when the linker links the object files, it sees the multiple definitions still. To solve this issue, change common.hpp to: #pragma once void some_function(); This tells the compiler that there is some code for some_function. Then, add a file common.cpp that contains the code for the common.hpp header: #include "common.hpp" #include <iostream> void some_function() { std::cout << "something" << std::endl; } Finally, change the g++ command to: g++ main.cpp common.cpp Thing.cpp -o main
69,083,237
69,105,384
GetProcessId doesn't find any process
I'm using the following code to try to get the PID of notepad.exe, but it doesn't find the process. I'm currently running on Windows 10 and compiling using VS Studio 19 as Release x64. Also tried to find other processes, like chrome.exe, calculator.exe, etc, but couldn't find anything. DWORD GetProcessId(LPCTSTR ProcessName) { PROCESSENTRY32 pt; HANDLE hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); std::wcout << "Error: " << GetLastError() << std::endl; // Error: 0 pt.dwSize = sizeof(PROCESSENTRY32); std::wcout << "Error: " << GetLastError() << std::endl; // Error: 0 if (Process32First(hsnap, &pt)) { // must call this first do { if (!lstrcmpi(pt.szExeFile, ProcessName)) { CloseHandle(hsnap); return pt.th32ProcessID; } } while (Process32Next(hsnap, &pt)); } std::wcout << "Error: " << GetLastError() << std::endl; // Error: 24 CloseHandle(hsnap); // close handle on failure return 0; } int _tmain(int argc, _TCHAR* argv[]) { DWORD processId; processId = GetProcessId(TEXT("notepad.exe")); std::wcout << "processId: " << processId << std::endl; return 0; } While debugging, I see the code is skipping the do while and jumping directly to CloseHandle(hsnap) GetLastError() returns 24 at this line.
The image you posted of your debug output window shows pt.dwSize is set to 2168. This looks wrong. pt.dwSize is important, it used by Windows for version control. On my computer sizeof(PROCESSENTRY32) is 556 (it depends on Windows version, I am using Windows 10). If project is not Unicode, the size should about half that. In VS, you can right click on PROCESSENTRY32 and it takes you to this definition: typedef struct tagPROCESSENTRY32W { DWORD dwSize; DWORD cntUsage; DWORD th32ProcessID; // this process ULONG_PTR th32DefaultHeapID; DWORD th32ModuleID; // associated exe DWORD cntThreads; DWORD th32ParentProcessID; // this process's parent process LONG pcPriClassBase; // Base priority of process's threads DWORD dwFlags; WCHAR szExeFile[MAX_PATH]; // Path } PROCESSENTRY32W; MAX_PATH should be 260. My guess is that you have redefined MAX_PATH or you have put the wrong #pragma statement somewhere. Or there is something weird happening. Try restarting Windows (use Restart instead of shutdown/start) Also, zero the memory with PROCESSENTRY32 pt = {0} PROCESSENTRY32 pt = { 0 }; pt.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hsnap, &pt)) { DWORD err = GetLastError(); std::cout << "Process32First failed\n"; std::cout << pt.dwSize << " GetLastError : " << err << "\n"; CloseHandle(hsnap); return DWORD(-1); } The only expected GetLastError is ERROR_NO_MORE_FILES as shown in Windows documentation. If the error is something else, it means the function has totally failed. If your project is Unicode, as it should be, consider avoiding those T macros. Just use GetProcessId(L"notepad.exe"); and LPCWSTR etc. Ps, I ran your code and it was fine in my computer. The only difference was sizeof(PROCESSENTRY32)
69,084,770
69,085,441
How to test a program using SDL without a graphical interface?
I made a C++ program that uses SDL for display and sound. I am implementing gtest to test the graphical functions, for example to draw a pixel : void Interface::draw_pixel(unsigned short x, unsigned short y, bool on) { if (on) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); } else { SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); } SDL_Rect rect = {normalize_x(x), normalize_y(y), SIZE_MULTIPLIER_, SIZE_MULTIPLIER_}; SDL_RenderFillRect(renderer, &rect); } And to check if this pixel is indeed drawn : bool Interface::is_pixel_on(int x, int y) { p_ = (uint8_t *) SDL_GetWindowSurface(window)->pixels + normalize_y(y) * SDL_GetWindowSurface(window)->pitch + normalize_x(x) * bpp_; SDL_GetRGB(*(uint32_t *) p_, SDL_GetWindowSurface(window)->format, &rgb_.r, &rgb_.g, &rgb_.b); return rgb_.r != 0; } I would like to draw a pixel and check if it is drawn in C.I. tests. I have tried to create the SDL window with the SDL_WINDOW_HIDDEN flag but it doesn't draw and my test fail. Do you have any idea or hints how it should be done?
Generally, unit tests don't test gui but logics. Have a layer of abstraction between library and your logic. Eg: namespace mygui { RenderFillRect(MyRenderer renderer, MyRect* rect); }; void Interface::draw_pixel(unsigned short x, unsigned short y, bool on) { if (on) { MySetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); } else { MySetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); } MyRect rect = {normalize_x(x), normalize_y(y), SIZE_MULTIPLIER_, SIZE_MULTIPLIER_}; MyRenderFillRect(renderer, &rect); } Mock mygui::RenderFillRect and check if it's called with correct arguments after calling Interface::draw_pixel. After your elaborated in comment about testing for CHIP8 interpreter, my suggestion is still relevant. I'll suggest you to mock SDL function calls by using the instruction here. Another way is mocking Interface::draw_pixel() to make sure one instruction is writing to the correct position. I'm not sure when do you need to test SDL library. The only scenario I came up with is that it might breaks when you upgrade the library version. However most of time it doesn't get upgraded frequently.
69,084,852
69,084,896
Implementation of constructor for size in stack using array in c++
#include <iostream> using namespace std; class Stack { private: int size; public: Stack(int n) { size = n; } int stack_arr[size], top = -1; void push(int a) { if (top >= 4) cout << "Stack is full" << endl; else { top++; stack_arr[top] = a; } } void pop() { if (top <= -1) cout << "There is no element remaining in stack" << endl; else { cout << "The popped element is " << stack_arr[top] << endl; top--; } } void peek() { if (top < 0) { cout << "Stack is Empty"; } else { int x = stack_arr[top]; cout << "The last element in the Stack is: "; cout << x << endl; } } int isempty() { if (top == -1) cout << "Stack is Empty: "; else return false; } void display() { if (top >= 0) { cout << "Stack elements are:"; for (int i = top; i >= 0; i--) cout << stack_arr[i] << " "; cout << endl; } else cout << "Stack is empty"; } }; int main() { Stack s(5); s.push(10); s.push(12); s.push(14); s.push(10); s.push(12); s.push(14); s.peek(); s.display(); s.pop(); s.display(); } I'm facing the issue while compilation 13:9: error: invalid use of non-static data member 'Stack::size' 14:15: error: from this location In member function 'void Stack::push(int)': 21:7: error: 'stack_arr' was not declared in this scope In member function 'void Stack::pop()': 28:40: error: 'stack_arr' was not declared in this scope In member function 'void Stack::peek()': 38:17: error: 'stack_arr' was not declared in this scope In member function 'void Stack::display()': 53:13: error: 'stack_arr' was not declared in this scope can anyone help me for giving idea how i can get stack size from constructor,if im doing wrong approach
I made your code compile, you had to do two simple modifications: private: int size; int* stack_arr; int top = 0; public: Stack(int n) { size = n; stack_arr = new int[size]; } You forgot to define top, also to achieve what you tried with a dynamic array you can use new. I also fixed some issues that lead to random dygits while printing, you basically were going out of array scope: void push(int a) { if (top == size - 1) // in your code it was top<=4, //suppose it was only for your specific test case // your forgot that it has to be generic cout << "Stack is full" << endl; else { top++; stack_arr[top] = a; } } void pop() { if (top == -1) cout << "There is no element remaining in stack" << endl; else { cout << "The popped element is " << stack_arr[top] << endl; top--; } } void peek() { if (top == -1) { cout << "Stack is Empty"; } else { int x = stack_arr[top]; cout << "The last element in the Stack is: "; cout << x << endl; } } int isempty() { if (top == -1) cout << "Stack is Empty: "; else return false; } void display() { if (top > -1) { cout << "Stack elements are:"; for (int i = top; i >= 0; i--) cout << stack_arr[i] << " "; cout << endl; } else cout << "Stack is empty"; } In modern c++ there is a rule: If you have anything in your class using new, you should make a destructor. And if you create a destructor, you should create copy constructor, and copy assignment operator (Its called rule of 3). For bonus, in this case, at least in my opinion, I also created move constructor and move assignment operator ( likely you wont use then in your case, that's why I say its bonus. It's known as rule of 5). //Destructor ~Stack() { delete [] stack_arr; } //copy Constructor Stack(const Stack& s) : size(s.size), stack_arr(new int[size]), top(s.top) { for (int i = 0; i <= top; i++) stack_arr[i] = static_cast<int>(s.stack_arr[i]); } //copy assignment operator Stack& operator=(const Stack& s) { if (stack_arr != nullptr) delete[] stack_arr; size = s.size; top = s.top; stack_arr = new int[size]; for (int i = 0; i <= top; i++) stack_arr[i] = static_cast<int>(s.stack_arr[i]); return *this; } //move constructor Stack(Stack&& s) noexcept : top(std::move(s.top)), size(std::move(s.size)), stack_arr(std::move(s.stack_arr)) { s.stack_arr = nullptr; } //move assignment operator Stack& operator=(Stack&& s)noexcept { if (this != &s) { if (stack_arr != nullptr) delete[] stack_arr; size = std::move(s.size); top = std::move(s.top); stack_arr = std::move(s.stack_arr); } return *this; }
69,084,887
69,085,701
How can I prevent template type expansion in C++?
I wrote the following classes which uses member pointer functions: #include <stdlib.h> #include <vector> template<class Type> class PrimitiveAccessor { public : PrimitiveAccessor( JNIEnv* env, const char name[], const char ctorSig[], Type (JNIEnv::*callTypeMethodFunction) (jobject, jmethodID) ) { this->env = env; this->type = (jclass)env->NewGlobalRef(env->FindClass(name)); this->callTypeMethodFunction = callTypeMethodFunction; } ~PrimitiveAccessor(){ env->DeleteGlobalRef(this->type); } private: JNIEnv* env; jclass type; jmethodID constructorId; jmethodID callTypeMethodId; Type (JNIEnv::*callTypeMethodFunction) (jobject, jmethodID); }; class Environment { public: Environment(JNIEnv* env) { this->env = env; this->init(); } ~Environment(){ this->env = 0; delete(this->jintAccessor); this->jintAccessor = 0; } private: JNIEnv* env; PrimitiveAccessor<jint>* jintAccessor; void init() { jintAccessor = new PrimitiveAccessor<jint>( env, "java/lang/Integer", "(I)V", &JNIEnv::CallIntMethod ); } }; But on compiling I obtain the following compilation error: F:\Shared\Workspaces\Projects\DriverFunctionSupplierNative.cpp: In member function 'void Environment::init()': F:\Shared\Workspaces\Projects\JNIDriverFunctionSupplierNative.cpp:75:4: error: no matching function for call to 'PrimitiveAccessor<long int>::PrimitiveAccessor(JNIEnv*&, const char [18], const char [5], jint (JNIEnv_::*)(jobject, jmethodID, ...))' ); ^ F:\Shared\Workspaces\Projects\JNIDriverFunctionSupplierNative.cpp:36:3: note: candidate: 'PrimitiveAccessor<Type>::PrimitiveAccessor(JNIEnv*, const char*, const char*, Type (JNIEnv_::*)(jobject, jmethodID)) [with Type = long int; JNIEnv = JNIEnv_; jobject = _jobject*; jmethodID = _jmethodID*]' PrimitiveAccessor( ^~~~~~~~~~~~~~~~~ F:\Shared\Workspaces\Projects\JNIDriverFunctionSupplierNative.cpp:36:3: note: no known conversion for argument 4 from 'jint (JNIEnv_::*)(jobject, jmethodID, ...)' {aka 'long int (JNIEnv_::*)(_jobject*, _jmethodID*, ...)'} to 'long int (JNIEnv_::*)(jobject, jmethodID)' {aka 'long int (JNIEnv_::*)(_jobject*, _jmethodID*)'} F:\Shared\Workspaces\Projects\JNIDriverFunctionSupplierNative.cpp:34:7: note: candidate: 'constexpr PrimitiveAccessor<long int>::PrimitiveAccessor(const PrimitiveAccessor<long int>&)' class PrimitiveAccessor { ^~~~~~~~~~~~~~~~~ I temporarily fixed it by casting the member function pointer: void init() { jintAccessor = new PrimitiveAccessor<jint>( env, "java/lang/Integer", "(I)V", (long (JNIEnv::*) (jobject, jmethodID))&JNIEnv::CallIntMethod ); } I noticed that the type passed to the template is expanded: is there a way to avoid this cast?
You need to specify a matching type, not a type that is similar. I have also cleaned up lots of your unidiomatic C++. Don't use new; it isn't required. You don't need a user-defined destructor if your data members clean themselves up. You should initialise your data members in the member initialiser list, not in the body of the constructor. Use std::string for strings. #include <stdlib.h> #include <vector> #include <memory> #include <string> struct GlobalRefDeleter { JNIEnv* env; void operator()(jobject type) { env->DeleteGlobalRef(type); } }; using JClass = std::unique_ptr<_jclass, GlobalRefDeleter>; JClass getClass(JNIEnv* env, const std::string & name) { return { static_cast<jclass>(env->NewGlobalRef(env->FindClass(name.c_str()))), env }; } template<class Type> class PrimitiveAccessor { using CallMethod = Type (JNIEnv::*) (jobject, jmethodID, ...); public : PrimitiveAccessor( JNIEnv* env, const std::string & name, const std::string & ctorSig, CallMethod callMethod) ) : env(env), type(getClass(env, name)), callMethod(callMethod) { } private: JNIEnv* env; JClass type; jmethodID constructorId; jmethodID callTypeMethodId; CallMethod callMethod; }; class Environment { public: Environment(JNIEnv* env) : env(env), jintAccessor(env, "java/lang/Integer", "(I)V", &JNIEnv::CallIntMethod) { } private: JNIEnv* env; PrimitiveAccessor<jint> jintAccessor; };
69,084,926
69,103,857
Link PahoMqttCpp as a static library in CMake using Conan
I am working on a C++ web framework, oatpp to create REST APIs. Using the oatpp-starter project where the CMakeLists.txt looks like: cmake_minimum_required(VERSION 3.1) set(project_name my-project) ## rename your project here project(${project_name}) set(CMAKE_CXX_STANDARD 11) add_library(${project_name}-lib src/AppComponent.hpp src/controller/MyController.cpp src/controller/MyController.hpp src/dto/DTOs.hpp ) ## link libs find_package(oatpp 1.2.5 REQUIRED) target_link_libraries(${project_name}-lib PUBLIC oatpp::oatpp PUBLIC oatpp::oatpp-test ) target_include_directories(${project_name}-lib PUBLIC src) ## add executables add_executable(${project_name}-exe src/App.cpp test/app/MyApiTestClient.hpp) target_link_libraries(${project_name}-exe ${project_name}-lib) add_dependencies(${project_name}-exe ${project_name}-lib) add_executable(${project_name}-test test/tests.cpp test/app/TestComponent.hpp test/app/MyApiTestClient.hpp test/MyControllerTest.cpp test/MyControllerTest.hpp ) target_link_libraries(${project_name}-test ${project_name}-lib) add_dependencies(${project_name}-test ${project_name}-lib) set_target_properties(${project_name}-lib ${project_name}-exe ${project_name}-test PROPERTIES CXX_STANDARD 11 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON ) enable_testing() add_test(project-tests ${project_name}-test) The executable I get after compiling this code runs successfully inside a container with same architecture. But when I add paho-mqtt library to the project, the executable does't run on the container because the shared library libpaho-mqttcpp3.so.1 not found: No such file or directory error. I am adding the library using this configuration: Updated CMakeLists.txt : cmake_minimum_required(VERSION 3.1) set(project_name my-project) ## rename your project here project(${project_name}) set(CMAKE_CXX_STANDARD 11) add_library(${project_name}-lib src/AppComponent.hpp src/controller/MyController.cpp src/controller/MyController.hpp src/dto/DTOs.hpp ) ## link libs find_package(oatpp 1.2.5 REQUIRED) target_link_libraries(${project_name}-lib PUBLIC oatpp::oatpp PUBLIC oatpp::oatpp-test ) ## conan include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup(TARGETS) target_include_directories(${project_name}-lib PUBLIC src) ## add executables add_executable(${project_name}-exe src/App.cpp test/app/MyApiTestClient.hpp) target_link_libraries(${project_name}-exe ${project_name}-lib ${CONAN_LIBS}) add_dependencies(${project_name}-exe ${project_name}-lib) add_executable(${project_name}-test test/tests.cpp test/app/TestComponent.hpp test/app/MyApiTestClient.hpp test/MyControllerTest.cpp test/MyControllerTest.hpp ) target_link_libraries(${project_name}-test ${project_name}-lib ${CONAN_LIBS}) add_dependencies(${project_name}-test ${project_name}-lib) set_target_properties(${project_name}-lib ${project_name}-exe ${project_name}-test PROPERTIES CXX_STANDARD 11 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON ) enable_testing() add_test(project-tests ${project_name}-test) Here's the conanfile.txt [requires] paho-mqtt-cpp/1.2.0 # MQTT Client [generators] cmake How to configure CMake to use Conan's downloaded PahoMqttCpp library to build a standalone project executable (using static library)
Here's what was happening: I configured CMakeLists.txt incorrectly to integrate with conan. Since I had paho-mqtt-cpp installed beforehand, the program was linking to installed libraries instead of those provided by conan. This CMakeLists.txt works for me: cmake_minimum_required(VERSION 3.1) set(PROJECT_NAME my-awesome-project) project(${PROJECT_NAME}) set(CMAKE_CXX_STANDARD 14) ############################### CONAN SETUP BEGIN ########################################## if(NOT EXISTS "${CMAKE_BINARY_DIR}/conan.cmake") message(STATUS "Downloading conan.cmake from https://github.com/conan-io/cmake-conan") file(DOWNLOAD "https://raw.githubusercontent.com/conan-io/cmake-conan/v0.9/conan.cmake" "${CMAKE_BINARY_DIR}/conan.cmake") endif() include(${CMAKE_BINARY_DIR}/conan.cmake) conan_cmake_run(CONANFILE conanfile.txt BASIC_SETUP) ############################### CONAN SETUP END ############################################ add_library(${PROJECT_NAME}-lib # controllers src/controller/StaticController.hpp # db src/db/DemoDb.hpp # mqtt src/mqtt/MqttCoroutine.hpp src/mqtt/MqttClient.hpp # dto src/dto/PageDto.hpp src/dto/StatusDto.hpp src/dto/DemoDto.hpp # services src/service/DemoService.cpp src/service/DemoService.hpp # base src/AppComponent.hpp src/DatabaseComponent.hpp src/ErrorHandler.cpp src/ErrorHandler.hpp) ## include directories target_include_directories(${PROJECT_NAME}-lib PUBLIC src) add_definitions( ## SQLite database file -DDATABASE_FILE="${CMAKE_CURRENT_SOURCE_DIR}/sql/db.sqlite" ## SQLite database test file -DTESTDATABASE_FILE="${CMAKE_CURRENT_SOURCE_DIR}/sql/test-db.sqlite" ## Path to database migration scripts -DDATABASE_MIGRATIONS="${CMAKE_CURRENT_SOURCE_DIR}/sql" ## my-awesome-project Service -DHOST="0.0.0.0" -DPORT=8080 ## MQTT Broker -DMQTT_BROKER_URL="tcp://127.0.0.1:1883" ) if(CMAKE_SYSTEM_NAME MATCHES Linux) find_package(Threads REQUIRED) target_link_libraries(${PROJECT_NAME}-lib INTERFACE Threads::Threads ${CMAKE_DL_LIBS}) endif() ## add executables add_executable(${PROJECT_NAME}-exe src/App.cpp) target_link_libraries(${PROJECT_NAME}-exe ${PROJECT_NAME}-lib ${CONAN_LIBS}) add_executable(${PROJECT_NAME}-test test/tests.cpp test/app/TestClient.hpp test/app/TestDatabaseComponent.hpp test/app/TestComponent.hpp test/DeviceControllerTest.hpp test/DeviceControllerTest.cpp) target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME}-lib ${CONAN_LIBS}) enable_testing() add_test(e2e-tests ${PROJECT_NAME}-test) Along with this conanfile.txt [requires] oatpp/1.2.5 # REST library oatpp-sqlite/1.2.5 # SQLite3 plugin paho-mqtt-cpp/1.2.0 # MQTT Client [generators] cmake Just use regular cmake command to generate Makefile. Then run make to get the executable.
69,085,912
69,088,161
Get decimal separator on Mac
Can someone explain to me, why I always get "." as a decimal separator on my Mac with this simple program, regardless of the system settings? #include <iostream> int main(int argc, const char * argv[]) { std::locale::global(std::locale()); std::cout << "decimal separator: " << std::use_facet< std::numpunct<char> >(std::cout.getloc()).decimal_point() << "\n"; return 0; } In the system settings I set the decimal separator to ",": Note: When I execute this program on Windows, it returns the correct decimal separator, depending on the system settings.
The locale you pass in your call to std::locale::global uses the default constructor to make a std::locale object. That default constructor, in your case, makes a copy of std::locale::classic. From cppreference (bolding mine): (1) Default constructor. Constructs a copy of the global C++ locale, which is the locale most recently used as the argument to std::locale::global or a copy of std::locale::classic if no call to std::locale::global has been made. That locale, as its name implies, uses the 'classic' C++ semantics, which means using a dot as the decimal separator. I'm not sure why your Windows version behaves differently – when I run your code on my Windows 10 PC, with the system set to use a comma for the decimal separator, I still get a dot reported. In order to report the actual current decimal separator, you can use the locale constructor with an empty string argument in the call to global, then default construct a std::locale object and use that to report the current separator: int main(int argc, const char* argv[]) { std::locale::global(std::locale{ "" }); // First call sets the environment locale std::locale loc; // Default constructor - uses the new locale set in above call std::cout << "decimal separator: " << std::use_facet< std::numpunct<char> >(loc).decimal_point() << "\n"; return 0; } Alternatively, if you don't actually need to change the global locale, just construct the loc object using the empty string argument: #include <iostream> #include <clocale> int main(int argc, const char* argv[]) { std::locale loc{ "" }; std::cout << "decimal separator: " << std::use_facet< std::numpunct<char> >(loc).decimal_point() << "\n"; return 0; } And, finally, if you want to set and use the locale in the std::cout stream, you need to imbue() that stream with the specific locale: #include <iostream> #include <clocale> int main(int argc, const char* argv[]) { std::cout << 1.234 << std::endl; // Uses default (C) separator (dot): 1.234 std::cout.imbue(std::locale{ "" }); std::cout << "decimal separator: " << std::use_facet< std::numpunct<char> >(std::cout.getloc()).decimal_point() << "\n"; std::cout << 1.234 << std::endl; // Uses the system separator (comma): 1,234 return 0; }
69,086,319
69,086,800
Was the C++14 standard defective/underspecified w.r.t. deduction of an array type function parameter from an initializer list?
It comes as no surprise that the following program // #1 template<typename T, std::size_t N> void f(T (&&)[N]) {} int main() { f({1,2,3}); } is seemingly well-formed in C++14 (well, at least all compilers that I've tried seems to accepts it). However, it seems as if this is not supported by the C++14 standard, particularly that T and N can be deduced from an initializer list argument? [temp.deduct.type]/3.4 A given type P can be composed from a number of other types, templates, and non-type values: [...] /3.4 An array type includes the array element type and the value of the array bound. explains why deduction succeeds for the following example: template<typename T, std::size_t N> void f(T (&)[N]) {} int main() { int arr[] = {1, 2, 3}; // #2 f(arr); } where particularly [dcl.init.aggr]/4 governs that #2 declares and array of size 3 (even though omitted from the type in the declaration). However, in the context of a function call, as per [temp.deduct.type]/5.6 A function parameter for which the associated argument is an initializer list ([dcl.init.list]) but the parameter does not have std::initializer_list or reference to possibly cv-qualified std::initializer_list type. ... this is a non-deduced context. From the C++17 standard and onwards [temp.deduct.call]/1 has been updated to express that an array type argument can be deduced from a (non-empty) initializer list, but this was not present in the C++14 standard, and [temp.deduct.type]/5.6, regarding non-deduced contexts, explicitly refers to [temp.deduct.call]/1 for exceptions to the rule. Was this a defect/underspecification of the C++14 standard? If so, is there an associated defect report(1)? If not, what passages of the C++14 standard covers that #1 above is well-formed? (1) I've tried to find one myself without any success.
This is DR 1591. It would seem reasonable ... to allow an array bound to be deduced from the number of elements in the initializer list, e.g., template<int N> void g(int const (&)[N]); void f() { g( { 1, 2, 3, 4 } ); } Being a DR, it applies retroactively to C++14. NB: It seems Language Lawyer beat me to it, but I found it independently through git blame of templates.tex:)
69,086,379
69,101,316
golang os.Setenv does not work in cgo C.dlopen?
For some reason, I can not set $LD_LIBRARY_PATH to global env. I try to set it up in golang code use os.Setenv. os.Setenv("LD_LIBRARY_PATH", my_library_paths) lib := C.dlopen(C.CString(libpath), C.RTLD_LAZY) I use another C++ function to get $LD_LIBRARY_PATH, it shows corretly. But lib returns '<nil>', and C.dlerror() shows >> %!(EXTRA string=libhasp_linux_x86_64_demo.so: cannot open shared object file: No such file or directory) Means $LD_LIBRARY_PATH does not work in dlopen, cgo can not find depend libraries. I don't know why.Hope some one can help me.Thanks!
It looks like you're trying to call os.Setenv("LD_LIBRARY_PATH", ...) and then C.dlopen() from within the same process. From the man page dlopen(3): Otherwise, the dynamic linker searches for the object as follows ... If, at the time that the program was started, the environment variable LD_LIBRARY_PATH was defined to contain a colon-separated list of directories, then these are searched. The key phrase being, at the time the program is started. We can see in the implementation for dlopen in the glibc source elf/dl-load.c that it looks at a global variable __rtld_env_path_list.dirs that has already been set when searching for libraries to load; it does not look at the current value of $LD_LIBRARY_PATH. If you want to use LD_LIBRARY_PATH to find things in C.dlopen, then you'll need to set it before your process starts (by running e.g. LD_LIBRARY_PATH=/my/path go run my-app.go).
69,087,986
69,107,834
How to unit test gRPC asynchronous C++ client functions with google test
I'm trying to write unit tests for my C++ gRPC client, using google test. I'm using both synchronous and asynchronous rpc's, and I can't figure out how to use mock'ed version of asynchronous ones. In my .proto file I have: rpc foo(EmptyMessage) returns (FooReply) {} From this protoc has generated mock stub with both synchronous and asynchronous calls: MOCK_METHOD3(foo, ::grpc::Status(::grpc::ClientContext* context, const ::EmptyMessage& request, ::FooReply* response)); MOCK_METHOD3(AsyncfooRaw, ::grpc::ClientAsyncResponseReaderInterface< ::FooReply>*(::grpc::ClientContext* context, const ::EmptyMessage& request, ::grpc::CompletionQueue* cq)); I can succesfully mock synchronous calls with: EXPECT_CALL(mockStub, foo).Times (1).WillOnce ([] (grpc::ClientContext *, const ::EmptyMessage &, ::FooReply *repl) { // I can set desired values to 'repl' here return grpc::Status::OK; }); Question: how can I use the mock'ed asynchronous foo() rpc? I have tried for example: EXPECT_CALL(mockStub, AsyncfooRaw).Times (1).WillOnce ([] (::grpc::ClientContext* context, const ::EmptyMessage& request, ::grpc::CompletionQueue* cq) -> grpc_impl::ClientAsyncResponseReaderInterface<::FooReply>* { ... which compiles, but I get: GMOCK WARNING: Uninteresting mock function call - returning default value. Function call: AsyncfooRaw which to my understanding means gmock does not find the handler for AsyncfooRaw I'm trying to provide.
Unfortunately, gRPC doesn't offer a way to create mocks for the async API. There were some historical constraints that made this infeasible when the async API was first developed, and as a result, the API wasn't really designed to support this. We might want to look at supporting this for the new callback-based API, which is intended to replace the async API. Feel free to file a feature request for this. However, it will require some investigation, and I'm not sure how quickly we'll be able to get to it. In the interim, the best work-around is to create a server implementation and add your mocks there, rather than mocking the client API directly.
69,088,439
69,088,584
How can I make a superclass of a template class abstract?
I have declared the following classes in a header file (Environment.h) and I would like to make the superclass FieldAccessor abstract: #include <jni.h> class FieldAccessor { public: FieldAccessor( JNIEnv* env ) { this->jNIEnv = env; } virtual jobject getValue(jobject, jobject) = 0; protected: JNIEnv* jNIEnv; }; template<typename Type> class PrimitiveFieldAccessor : public FieldAccessor { public : PrimitiveFieldAccessor ( JNIEnv* env, const char name[], const char ctorSig[], Type (JNIEnv::*getFieldValueFunction) (jobject, jfieldID) ); jobject getValue(jobject, jobject); private: jclass type; jmethodID constructorId; Type (JNIEnv::*getFieldValueFunction) (jobject, jfieldID); }; But I obtain the following compilation error: F:/Shared/Workspaces/Projects/JNI/src/DriverFunctionSupplierNative.cpp: In instantiation of '_jobject* PrimitiveFieldAccessor<Type>::getValue(jobject, jobject) [with Type = long int; jobject = _jobject*]': F:/Shared/Workspaces/Projects/JNI/src/Environment.h:73:11: required from here F:/Shared/Workspaces/Projects/JNI/src/DriverFunctionSupplierNative.cpp:80:2: error: must use '.*' or '->*' to call pointer-to-member function in '((PrimitiveFieldAccessor<long int>*)this)->PrimitiveFieldAccessor<long int>::getFieldValueFunction (...)', e.g. '(... ->* ((PrimitiveFieldAccessor<long int>*)this)->PrimitiveFieldAccessor<long int>::getFieldValueFunction) (...)' This is a piece of the implementation file (DriverFunctionSupplierNative.cpp): template<typename Type> PrimitiveFieldAccessor<Type>::PrimitiveFieldAccessor ( JNIEnv* env, const char name[], const char ctorSig[], Type (JNIEnv::*getFieldValueFunction) (jobject, jfieldID) ) : FieldAccessor(env) { this->jNIEnv = env; this->type = (jclass)jNIEnv->NewGlobalRef(env->FindClass(name)); this->constructorId = jNIEnv->GetMethodID(this->type, "<init>", ctorSig); this->getFieldValueFunction = getFieldValueFunction; } template<typename Type> jobject PrimitiveFieldAccessor<Type>::getValue(jobject target, jobject field) { jfieldID fieldId = jNIEnv->FromReflectedField(field); return jNIEnv->NewObject( this->type, this->constructorId, this->getFieldValueFunction(target, fieldId) ); }
The compilation error is quite descriptive of the problem. Take the time to read them and learn what they mean: error: must use '.*' or '->*' to call pointer-to-member function in '...', e.g. ... Now look at how you try to call the function: this->callTypeMethodFunction( ... ) The syntax would be something like this: (jNIEnv->*callTypeMethodFunction)(value, this->callTypeMethodId); The same thing applies for the other pointer to the member function calls: return jNIEnv->NewObject( this->type, this->constructorId, (jNIEnv->*getFieldValueFunction)(target, fieldId) ); Now why does the compilation error only happen when you have the virtual method? This is because of how template instantiation works. You didn't post how the class will be instantiated, but looking at the symptoms is that the virtual function get instantiated early to build the vtable, but other methods (non-virtual) will only be instantiated on usage.
69,088,562
69,093,166
Hiding symbols of the derived class in shared library
I will be writing a shared library and I've found this note on the Internet about setting the visibility of the symbols. The general guidance is to hide everything that is not needed by the client of the library, which leads to reduce the size and the load time of the library. And it's clear for me unless it comes to use class hierarchies. However, let's start from the beginning. Assumptions: The GCC toolchain is used on Linux OS The library and the client application are built with the same toolchain The library will be used on Linux distribution built with the same toolchain -fvisibility=hidden and -fvisibility-inlines-hidden compile option are used to build library I've prepared cases to check what is the impact of the compiler switches to the library. Case 1 Client code: #include "Foo.hpp" int main() { auto s = make(); delete s; } Library header: struct Foo{}; Foo* make() __attribute__((visibility("default"))); Library source: #include "Foo.hpp" Foo *make() { return new Foo; } In this case, everything compiles and links without errors, even only the make function is exported. This is clear to me. Case 2 I add the Foo destructor definition. Client code same as in Case 2. Library header: struct Foo { ~Foo(); }; Foo* make() __attribute__((visibility("default"))); Library source: #include "Foo.hpp" Foo::~Foo() = default; Foo *make() { return new Foo; } In this case, during linking the client application with the library, the linker complains about the undefined reference to Foo::~Foo(), which is also clear for me. The destructor symbol was not exported and the client application needs it. Case 3 The client application and library source are the same as in case 2. However, in the library header I export Foo class: struct __attribute__((visibility("default"))) Foo { ~Foo(); }; Foo* make() __attribute__((visibility("default"))); No surprises here. Code compiles, links and runs without errors since the library exports all the symbols needed by the client application. However (case 4) When I was writing this library on the first attempt, instead of export the class I've made the destructor virtual: struct Foo { virtual ~Foo(); }; Foo* make() __attribute__((visibility("default"))); And surprisingly… the code compiled, linked and runs without any errors. Go further (case 5) Originally my library defines a class hierarchy, where Foo is the base class for the rest and defines pure virtual interface: struct __attribute__((visibility("default"))) Foo { virtual ~Foo(); virtual void foo() = 0; }; Foo* make() __attribute__((visibility("default"))); The make function produces instances of the derived classes, returning a pointer to the base class: #include "Foo.hpp" #include <cstdio> Foo::~Foo() = default; struct Bar: public Foo { void foo() override { puts("Bar::foo"); } }; Foo* make() { return new Bar; } And application uses the interface: #include "Foo.hpp" int main() { auto s = make(); s->foo(); delete s; } Everything compiles, links, runs without errors. Application prints Bar::foo, which shows that the Bar::foo override was called, even the Bar class was not exported at all. Questions (Case 4) Why did the linker not complain about the missing symbol to the destructor? Is it kind of the undefined behaviour? I'm not going to do it like that, only want to understand. (Case 5) Is it ok to export symbols only for the base class and the factory function, where the factory returns instances of the derived classes for which the symbols are hidden?
Why did the linker not complain about the missing symbol to the destructor? That's because client code loads address of destructor from vtable stored in object created in make function. Linker does not need to know the explicit address of ~Foo when linking the client code. Is it ok to export symbols only for the base class and the factory function, where the factory returns instances of the derived classes for which the symbols are hidden? It is ok as long as your client code only calls overloaded virtual methods in these derived classes. The reasons are same as for virtual ~Foo - addresses will be obtained from the object's vtable.
69,088,830
69,089,014
Can I glDeleteBuffer a VBO and IBO after binding to a VAO?
I've read that a VBO (Vertex Buffer Object) essentially keeps a reference count, so that if the VBO's name is given to glDeleteBuffers(), it isn't truly dismissed if a living VAO (Vertex Array Object) still references it. This behavior is similar to "Smart Pointers" newer languages are increasingly adopting. But to what extent this is true and can be designed around, and if it applies to IBO (Index Buffer Object) as well, I haven't been able to find any information on. If a VBO is kept alive by a VAO that references it and I don't intend to update it or use it beyond the VAO's death, I think the best play is to destroy my reference to it. Is it proper to do so? And can I do the same with an IBO?
Objects can be attached to other objects. So long as an object is attached to another object, the attached object will not actually be destroyed by calling glDelete*. It will be destroyed only after it is either unattached or the object it is attached to is destroyed as well. This isn't really something to worry about all that much. If you glDelete* an object, you should not directly use that name again.
69,089,144
69,089,915
Reading a buffer from a json using boost
I have the following json string: {"message": {"type":"Buffer", "data":[0,0,0,193,0,41,10,190,1,34,128,0,0,1,38,0,0,1,232,41,40,202,35,104,81,66,0,162,194,173,0,254,67,116,38,60,235,70,250,195,139,141,184,47,167,240,210,207,118,184,140,225,82,52,30,35,111,80,23,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,115,33,2,155,92,51,188,68,15,123,37,47,245,59,120,114,102,60,233,15,212,39,112,165,190,210,14,188,25,156,234,124,154,181,101,118,71,48,69,2,33,0,242,181,45,125,208,73,206,26,86,183,220,28,159,36,149,124,208,72,187,118,116,44,224,252,192,173,242,248,112,181,63,49,2,32,84,83,33,39,113,80,183,50,225,212,133,84,226,26,173,185,65,216,237,234,90,20,215,136,184,246,229,230,13,227,69,42]}, "validator_key":"n9MZdq6qPssK3jw63sjR8VRR4NjyCmaV11LnqTiCFQjRCDFreUVc\n"} I need to read the field message.data, which is a buffer coming from a node.js process via gRPC. I tried something like this: std::stringstream ss; boost::property_tree::ptree pt; ss << gossip.message(); boost::property_tree::read_json(ss, pt); auto message_received = pt.get<std::string>("message.data"); std::cout << "Message received pure: " << gossip.message() << std::endl; std::cout << "Message received, json: " << message_received << std::endl; gossip.message() is my json string as it is received via gRPC. The result is the following: Message received pure: {"message":{"type":"Buffer","data":[0,0,0,193,0,41,10,190,1,34,128,0,0,1,38,0,0,1,232,41,40,202,35,104,81,66,0,162,194,173,0,254,67,116,38,60,235,70,250,195,139,141,184,47,167,240,210,207,118,184,140,225,82,52,30,35,111,80,23,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,115,33,2,155,92,51,188,68,15,123,37,47,245,59,120,114,102,60,233,15,212,39,112,165,190,210,14,188,25,156,234,124,154,181,101,118,71,48,69,2,33,0,242,181,45,125,208,73,206,26,86,183,220,28,159,36,149,124,208,72,187,118,116,44,224,252,192,173,242,248,112,181,63,49,2,32,84,83,33,39,113,80,183,50,225,212,133,84,226,26,173,185,65,216,237,234,90,20,215,136,184,246,229,230,13,227,69,42]},"validator_key":"n9MZdq6qPssK3jw63sjR8VRR4NjyCmaV11LnqTiCFQjRCDFreUVc\n"} Message received, json: How can I read this field and put it inside a std::string or a asio buffer?
Two problems: message.data is not a string. It's an array of integers. Boost Property Tree is not a JSON library. Assuming you expect the "string" to be composed of bytes that are represented as their unsigned integral values in the array. One fix, one workaround: The Fix Use a JSON library, like Boost JSON: Live On Compiler Explorer #include <boost/json.hpp> #include <boost/json/src.hpp> #include <iostream> struct Gossip { std::string message(); } gossip; int main() { namespace json = boost::json; auto doc = json::parse(gossip.message()).as_object(); auto& arr = doc["message"].as_object()["data"]; auto bytes = json::value_to<std::vector<uint8_t>>(arr); std::string text(bytes.begin(), bytes.end()); //std::cout << "message(): " << gossip.message() << "\n"; std::cout << "doc: " << doc << "\n"; std::cout << "arr: " << arr << "\n"; std::cout << "bytes: "; for (int val : bytes) std::cout << " " << val; std::cout << "\ntext: " << std::quoted(text) << "\n"; } std::string Gossip::message() { return R"({ "message": { "type": "Buffer", "data": [0, 0, 0, 193, 0, 41, 10, 190, 1, 34, 128, 0, 0, 1, 38, 0, 0, 1, 232, 41, 40, 202, 35, 104, 81, 66, 0, 162, 194, 173, 0, 254, 67, 116, 38, 60, 235, 70, 250, 195, 139, 141, 184, 47, 167, 240, 210, 207, 118, 184, 140, 225, 82, 52, 30, 35, 111, 80, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115, 33, 2, 155, 92, 51, 188, 68, 15, 123, 37, 47, 245, 59, 120, 114, 102, 60, 233, 15, 212, 39, 112, 165, 190, 210, 14, 188, 25, 156, 234, 124, 154, 181, 101, 118, 71, 48, 69, 2, 33, 0, 242, 181, 45, 125, 208, 73, 206, 26, 86, 183, 220, 28, 159, 36, 149, 124, 208, 72, 187, 118, 116, 44, 224, 252, 192, 173, 242, 248, 112, 181, 63, 49, 2, 32, 84, 83, 33, 39, 113, 80, 183, 50, 225, 212, 133, 84, 226, 26, 173, 185, 65, 216, 237, 234, 90, 20, 215, 136, 184, 246, 229, 230, 13, 227, 69, 42] }, "validator_key": "n9MZdq6qPssK3jw63sjR8VRR4NjyCmaV11LnqTiCFQjRCDFreUVc\n" })"; } Workaround With Boost Property Tree std::string message_received; for (auto& [k, v] : pt.get_child("message.data")) { message_received += static_cast<char>(v.get_value<unsigned short>()); } The resulting data doesn't resemble any (known to me) text encoding, but that's probably not concerning. Live On Compiler Explorer #include <boost/property_tree/json_parser.hpp> #include <iostream> struct Gossip { std::string message(); } gossip; int main() { boost::property_tree::ptree pt; { std::stringstream ss(gossip.message()); boost::property_tree::read_json(ss, pt); } std::string message_received; for (auto& [k, v] : pt.get_child("message.data")) { message_received += static_cast<char>(v.get_value<unsigned short>()); } std::cout << "Message received pure: " << gossip.message() << std::endl; std::cout << "Message received, json: " << message_received << std::endl; } std::string Gossip::message() { return R"({ "message": { "type": "Buffer", "data": [0, 0, 0, 193, 0, 41, 10, 190, 1, 34, 128, 0, 0, 1, 38, 0, 0, 1, 232, 41, 40, 202, 35, 104, 81, 66, 0, 162, 194, 173, 0, 254, 67, 116, 38, 60, 235, 70, 250, 195, 139, 141, 184, 47, 167, 240, 210, 207, 118, 184, 140, 225, 82, 52, 30, 35, 111, 80, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115, 33, 2, 155, 92, 51, 188, 68, 15, 123, 37, 47, 245, 59, 120, 114, 102, 60, 233, 15, 212, 39, 112, 165, 190, 210, 14, 188, 25, 156, 234, 124, 154, 181, 101, 118, 71, 48, 69, 2, 33, 0, 242, 181, 45, 125, 208, 73, 206, 26, 86, 183, 220, 28, 159, 36, 149, 124, 208, 72, 187, 118, 116, 44, 224, 252, 192, 173, 242, 248, 112, 181, 63, 49, 2, 32, 84, 83, 33, 39, 113, 80, 183, 50, 225, 212, 133, 84, 226, 26, 173, 185, 65, 216, 237, 234, 90, 20, 215, 136, 184, 246, 229, 230, 13, 227, 69, 42] }, "validator_key": "n9MZdq6qPssK3jw63sjR8VRR4NjyCmaV11LnqTiCFQjRCDFreUVc\n" })"; }
69,089,153
69,089,325
Something better than many nested `for` loops?
I wish to evaluate several different potential rules/scoring systems for a game. The game involves rolling three dice up to three times. In order to consider the results of each eventuality, I'm iterating over all the possible values of each of the nine possible rolls of the dice. My question is whether the following brute force style coding is the best approach. // get the result for each possible game void Evaluate( const ScoringSystem& sys ) { for( int d1=0; d1<6; ++d1 ) { for( int d2=0; d2<6; ++d2 ) { for( int d3=0; d3<6; ++d3 ) { for( int d4=0; d4<6; ++d4 ) { for( int d5=0; d5<6; ++d5 ) { for( int d6=0; d6<6; ++d6 ) { for( int d7=0; d7<6; ++d7 ) { for( int d8=0; d8<6; ++d8 ) { for( int d9=0; d9<6; ++d9 ) { int rolls[] = { d1, d2, d3, d4, d5, d6, d7, d8, d9 }; // get the result for this particular game sys.GetGameResult( rolls ); } } } } } } } } } } The code functions but is ugly and not extensible to a game with more dice. I've got an environment that supports C++17, so I'm open to newer ideas — as long as they don't make the code look too terrible. (Tangent: 6^9 is over 10 million. I might be better off using pseudo-random numbers and just 'rolling' nine dice a million times. But I still want to know if there's a clever way to work through the permutations.)
If you ever find that you're nesting loops that look pretty much the same you should consider using recursion. void generateDiceRolls(const ScoringSystem& sys, std::vector<int>& rolls, size_t index) { if (index == rolls.size()) { // Reached the end - all the dice have been rolled sys.GetGameResult(rolls); } else { // For each value of a die at this index, generate dice rolls for the rest of them for (int i = 0; i < 6; i++) { rolls[index] = i; generateDiceRolls(sys, rolls, index + 1); } } } void Evaluate(const ScoringSystem& sys) { std::vector<int> rolls(9); // Change 9 to however many dice you want to use generateDiceRolls(sys, rolls, 0); }
69,089,184
69,089,323
Using push_back(std::move()) in unique_ptr vector
Hello I've been studying c++ and came across about unique_ptr. I want to put in a integers in this vector. I used vector because I wanted to practice the iterators too... auto integerArray = std::vector<std::unique_ptr<int[]>>(10); std::cout << "Created:" << sizeof(integerArray)/sizeof(int) << std::endl; for (int i = 0; i<10;i++) { int num = i * 10; integerArray.push_back((std::vector<std::unique_ptr<int>>)std::move(num)); //compile error here } std::cout << "Output : "; for (auto const& i : integerArray) { std::cout << i << std::endl; } This is the error: error C2664: 'void std::vector<std::unique_ptr<int [],std::default_delete<int []>>,std::allocator<std::unique_ptr<int [],std::default_delete<int []>>>>::push_back(const _Ty &)': cannot convert argument 1 from 'std::vector<std::unique_ptr<int,std::default_delete<int>>,std::allocator<std::unique_ptr<int,std::default_delete<int>>>>' to 'const _Ty &' with [ _Ty=std::unique_ptr<int [],std::default_delete<int []>> ] note: Reason: cannot convert from 'std::vector<std::unique_ptr<int,std::default_delete<int>>,std::allocator<std::unique_ptr<int,std::default_delete<int>>>>' to 'const _Ty' with [ _Ty=std::unique_ptr<int [],std::default_delete<int []>> ] note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called vector(633): note: see declaration of 'std::vector<std::unique_ptr<int [],std::default_delete<int []>>,std::allocator<std::unique_ptr<int [],std::default_delete<int []>>>>::push_back' and why the first cout output says 4 instead of 10? I expected 10 cause I made a vector container with 10 blocks that can contain integer.
You are misunderstanding how std::vector works. It manages its contents already, and std::unique_ptr is not appropriate in this circumstance. You are also declaring pointers to int being the type in the unique_ptr as well. If all you want is a container of integers, this is all that's necessary: auto integerVector = std::vector<int>(10); // filled with 10 default-init values, 0 for int std::cout << "Created:" << integerVector.size() << std::endl; for (int i = 0; i<10;i++) { int num = i * 10; integerVector.push_back(num); // Adds it to the end, not just first "unfilled" } std::cout << "Output : "; for (auto const& i : integerVector) { // Will print 20 times, as original 10 "0", and the // 10 you added to the end std::cout << i << std::endl; } Be very careful with the names "array" and "vector" as they are not the same thing in c++. They are similar, but not identical at all.
69,089,267
69,091,497
Parent function terminates whenever I try to call QTextCharFormat on QTextCursor selection
I recently ran into a weird issue where my QPlainTextEdit::selectionChanged handler function terminates prematurely whenever QTextCursor::mergeCharFormat/setCharFormat/setBlockCharFormat is called. Additionally, after terminating it gets called again and runs into the same issue, leading to an infinite loop. I'm trying to replicate a feature present in many text editors (such as Notepad++) where upon selecting a word, all similar words in the entire document are highlighted. My TextEditor class is overloaded from QPlainTextEdit. The minimal reproducible example is as follows: main.cpp: #include "mainWindow.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); mainWindow w; w.show(); return a.exec(); } MainWindow.h: #pragma once #include <QtWidgets/QMainWindow> #include "ui_mainWindow.h" #include "TextEditor.h" class mainWindow : public QMainWindow { Q_OBJECT public: mainWindow(QWidget *parent = Q_NULLPTR) : QMainWindow(parent) { ui.setupUi(this); auto textEdit = new TextEditor(this); textEdit->setPlainText("test lorem ipsum test\n dolor sit test"); ui.tabWidget->addTab(textEdit, "Editor"); //Or any other way of adding the widget to the window } private: Ui::mainWindowClass ui; }; TextEditor.h: The regex highlighter part is based on this SO answer. #pragma once #include <QPlainTextEdit> class TextEditor : public QPlainTextEdit { Q_OBJECT public: TextEditor(QWidget* parent) : QPlainTextEdit(parent) { connect(this, &QPlainTextEdit::selectionChanged, this, &TextEditor::selectChangeHandler); } private: void selectChangeHandler() { //Ignore empty selections if (textCursor().selectionStart() >= textCursor().selectionEnd()) return; //We only care about fully selected words (nonalphanumerical characters on either side of selection) auto plaintext = toPlainText(); auto prevChar = plaintext.mid(textCursor().selectionStart() - 1, 1).toStdString()[0]; auto nextChar = plaintext.mid(textCursor().selectionEnd(), 1).toStdString()[0]; if (isalnum(prevChar) || isalnum(nextChar)) return; auto qselection = textCursor().selectedText(); auto selection = qselection.toStdString(); //We also only care about selections that do not themselves contain nonalphanumerical characters if (std::find_if(selection.begin(), selection.end(), [](char c) { return !isalnum(c); }) != selection.end()) return; //Prepare text format QTextCharFormat format; format.setBackground(Qt::green); //Find all words in our document that match the selected word and apply the background format to them size_t pos = 0; auto reg = QRegExp(qselection); auto cur = textCursor(); auto index = reg.indexIn(plaintext, pos); while (index >= 0) { //Select matched text and apply format cur.setPosition(index); cur.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor, 1); cur.mergeCharFormat(format); //This causes the selectChangeHandler function to terminate and then execute again, causing an infinite loop leading to a stack overflow //Move to next match pos = index + (size_t)reg.matchedLength(); index = reg.indexIn(plaintext, pos); } } }; I suspect the format fails to apply for some reason, possibly causing an exception that gets caught inside Qt and terminates the parent function. I tried adding my own try-catch handler around the problematic area, but it did nothing (as expected). I'm not sure whether this is my fault or a bug inside Qt. Does anybody know what I'm doing wrong or how to work around this issue?
An infinite loop is being generated because it seems that getting the text changes also changes the selection. One possible solution is to block the signals using QSignalBlocker: void selectChangeHandler() { const QSignalBlocker blocker(this); // <--- this line //Ignore empty selections if (textCursor().selectionStart() >= textCursor().selectionEnd()) return; // ...
69,089,347
69,089,432
Why do ref-qualifier together with cv-qualifier on operator overloading allow rvalue assignment?
Adding a ref-qualifier to an operator will remove the possibility to do rvalue assignment for example, compiling the following with g++ -std=c++14 bar.cpp && ./a.out #include <cstdio> struct foo { void operator+=(int x) & { printf("%d\n", x+2); } }; int main() { foo() += 10; } will give you $ g++ -std=c++14 bar.cpp && ./a.out bar.cpp: In function ‘int main()’: bar.cpp:14:14: error: passing ‘foo’ as ‘this’ argument discards qualifiers [-fpermissive] 14 | foo() += 10; | ^~ bar.cpp:6:10: note: in call to ‘void foo::operator+=(int) &’ 6 | void operator+=(int x) & { printf("%d\n", x+2); } | ^~~~~~~~ you can of course "fix" this by adding an explicit && #include <cstdio> struct foo { void operator+=(int x) & { printf("%d\n", x+2); } void operator+=(int x) && { printf("%d\n", x+3); } }; int main() { foo() += 10; } output $ g++ -std=c++14 bar.cpp && ./a.out 13 But adding a const & will also let you call += on the struct instance. #include <cstdio> struct foo { void operator+=(int x) & { printf("%d\n", x+2); } void operator+=(int x) const & { printf("%d\n", x+4); } }; int main() { foo() += 10; } output $ g++ -std=c++14 bar.cpp && ./a.out 14 To "fix" this, the const && must be explicitly deleted #include <cstdio> struct foo { void operator+=(int x) & { printf("%d\n", x+2); } void operator+=(int x) const & { printf("%d\n", x+4); } void operator+=(int x) const && = delete; }; int main() { foo() += 10; } output $ g++ -std=c++14 bar.cpp && ./a.out bar.cpp: In function ‘int main()’: bar.cpp:14:14: error: use of deleted function ‘void foo::operator+=(int) const &&’ 14 | foo() += 10; | ^~ bar.cpp:9:10: note: declared here 9 | void operator+=(int x) const && = delete; | ^~~~~~~~ Why is this? Why do adding the ref-qualifier implicitly remove the rvalue assignment? But adding a cv-qualifier together with ref-qualifier seem to implicitly add the rvalue assignment? I'm sure I'm missing something obvious here. But Google-Wan Kenobi doesn't seem to be able to help me understand.
Because rvalues could be bound to lvalue-reference to const. Just same as the following code: foo& r1 = foo(); // invalid; rvalues can't be bound to lvalue-reference to non-const const foo& r2 = foo(); // fine; rvalues can be bound to lvalue-reference to const BTW: The overload qualified with rvalue-reference wins in overload resolution when calling on rvalues. That's why you mark it as delete explicitly works as expected.
69,089,425
69,090,146
How to wsprintf const char*
I'm trying to print the value of translatedMessage but its printing ????? static std::map<int, const char*> wmTranslation = { {0, "WM_NULL" }, {1, "WM_CREATE" }, {2, "WM_DESTROY" }, //.... }; void Msg(int Msg) { const char* translatedMessage = wmTranslation[Msg]; WCHAR wsText[255] = L""; wsprintf(wsText, L"Msg: %s", translatedMessage); OutputDebugString(wsText); } What would be the correct way to print it?
Solution for if you need to convert between string and wstring. It seems conversion between those strings is a "hard" problem. The C++ standard library had support for it, but it will be removed. So I fall back to a windows API call here. #include <array> #include <map> #include <string> #include <stdexcept> #include <iostream> #include <sstream> #include <Windows.h> // just use std::string when you mean text. Not const char* // to avoid conversion between character sets you could use std::wstring here too static std::map<int, const std::string > wmTranslation = { {0, "WM_NULL" }, {1, "WM_CREATE" }, {2, "WM_DESTROY" }, }; std::wstring convert(const std::string& s) { std::array<wchar_t, 256> buffer; auto result = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.c_str(), -1, buffer.data(), static_cast<int>(buffer.size() * sizeof(wchar_t))); if (result < 0) throw std::runtime_error("input string could not be converted"); return std::wstring{ buffer.begin(), buffer.end() }; } void Msg(int Msg) { std::wstringstream s; const auto& translatedMessage = wmTranslation[Msg]; auto wide_string = convert(translatedMessage); //wsprintf(wsText, L"Msg: %s", wide_string); s << L"Msg: " << wide_string; std::wcout << s.str() << std::endl; ::OutputDebugString(s.str().c_str()); } int main() { Msg(WM_CREATE); return 0; }
69,089,551
69,091,501
C++ V-shape casting: vector<Base1*> to vector<Base2*>
I'm having real trouble to figure out this casting problem. Starting with 3 classes: #include <vector> // Pure virtual class class Base1{ public: virtual ~Base1(); virtual void do_sth()=0; } class Base2{ public: int prop=3; ~Base2(); } class Derived: public Base1, Base2{ ~Derived(); void do_sth(){print("Hi");}; } How can I perform the following conversion? std::vector<Base1*> vec1 vec1.reserve(10); for( int i = 0; i < 10; ++i ) vec1.push_back(new Derived()); // To this type...? std::vector<Base2*> vec2 = ?????; Some remarks: I'd use dynamic_cast to perform safe casting from Base1 to Derived. Ideally, no object copies are made in the process!. My best bet so far is to call vec2.data() to obtain a Base1* pointer, then dynamic_cast to Derived, then static cast to Base2, but I don't know how to transfer memory ownership nor how to pass vector size.
The comments to the question have gotten rather muddled, so I'll post this partial answer here, rather than trying to straighten out the comments. Base1 has a virtual function. Good start. Derived is derived from Base1. Derived is also derived from Base2. If you have an object of type Derived you can create a pointer to Base1 that points at the derived object: Derived d; Base1* b1 = &d; Now that you have a pointer to a polymorphic base class, you can use dynamic_cast to perform a cross-cast: Base2* b2 = dynamic_cast<Base2*>(b1); The compiler knows how to do that, and the result should be the same pointer value as you'd have gotten if you did it directly: Base2* b2x = &d; assert(b2x == b2); Note, too, that since the code traffics in vectors of pointers, it seems that the Derived objects are being created with new Derived. If that's the case, and eventually the code deletes the Derived object through a pointer to one of the base types, then the base type must have a virtual destructor.
69,089,588
69,089,927
How to determine if std::filesystem::remove_all failed?
I am trying to use the non-throwing version of std::filesystem::remove_all, I have something like: bool foo() { std::error_code ec; std::filesystem::remove_all(myfolder, ec); if (ec.value()) { // failed to remove, return return false; } } Is this the correct way to use error_code? My reasoning: I read this: The overload taking a std::error_code& parameter sets it to the OS API error code if an OS API call fails, and executes ec.clear() Now here: clear - sets the error_code to value 0 in system_category Now I used this to imply error_code == 0 => No error. error_code != 0 => error. I really can't any much examples of uses of error_code. I just want to determine if all the files have been removed or not.
There is a difference between ec.value() and ec != std::error_code{}; in the case where the error code in ec is a different error category than system error and has a value of 0, the first will return false, while the second will return true. Error codes are a tuple of categories and value. Looking only at the value is a tiny bit of "code smell". In this case, I don't think it is possible for the error code to have anything except the system category. And it would be bad form for a non-system error category to use the value 0 for an actual error. If there was no error (value 0) with a non-system error code, treating it like an error is probably a bad idea. So maybe you shouldn't be checking the category. Finally, if (ec.value()) is a verbose way of saying if (ec). I'd use the explicit operator bool() const instead of calling .value(). Another option is: if (-1 == std::filesystem::remove_all(myfolder, ec)) { // failed to remove, return return false; }
69,089,690
69,090,654
Sorting a Vector of Vector in Cpp
Say I have this vector of vector [[5,10],[2,5],[4,7],[3,9]] and I want to sort it using the sort() method of cpp, such that it becomes this [[5,10],[3,9],[4,7],[2,5]] after sorting. That is I want to sort based on the second index. Now I have written this code to sort this vector of vector, but it is not working correctly. static bool compareInterval( vector<vector<int>> &v1, vector<vector<int>> &v2) { return (v1[0][1]>v2[0][1]); } sort(boxTypes.begin(), boxTypes.end(), compareInterval); Can anyone tell me where I am going wrong and hwo can I correct it. Thanks in advance.
When your code is sorting vector of vectors then to the boolean function it passes two vectors (not vector of vectors), and compares them to determine if they need to be interchanged, or are they in correct positions relative to each other. Hence, here you only need to compare 2 vectors (you have tried to compare vector of vectors). The change you need to make in compareInterval is: static bool compareInterval( vector<int> &v1, vector<int> &v2) { return (v1[1]>v2[1]); } Find my testing code below: #include <bits/stdc++.h> using namespace std; static bool compareInterval( vector<int> &v1, vector<int> &v2) { return (v1[1]>v2[1]); } int main() { vector<vector<int>> boxTypes = {{5,10},{2,5},{4,7},{3,9}}; sort(boxTypes.begin(), boxTypes.end(), compareInterval); for(int i=0;i<4;i++) cout<<boxTypes[i][0]<<" "<<boxTypes[i][1]<<"\n"; }
69,090,657
69,090,959
Missing small primes in C++ atomic prime sieve
I try to develop a concurrent prime sieve implementation using C++ atomics. However, when core_count is increased, more and more small primes are missing from the output. My guess is that the producer threads overwrite each others' results, before being read by the consumer. Even though the construction should protect against it by using the magic number 0 to indicate it's ready to accept the next prime. It seems the compare_exchange_weak is not really atomic in this case. Things I've tried: Replacing compare_exchange_weak with compare_exchange_strong Changing the memory_order to anything else. Swapping around the 'crossing-out' and the write. I have tested it with Microsoft Visual Studio 2019, Clang 12.0.1 and GCC 11.1.0, but to no avail. Any ideas on this are welcome, including some best practices I might have missed. #include <algorithm> #include <atomic> #include <future> #include <iostream> #include <iterator> #include <thread> #include <vector> int main() { using namespace std; constexpr memory_order order = memory_order_relaxed; atomic<int> output{0}; vector<atomic_bool> sieve(10000); for (auto& each : sieve) atomic_init(&each, false); atomic<unsigned> finished_worker_count{0}; auto const worker = [&output, &sieve, &finished_worker_count]() { for (auto current = next(sieve.begin(), 2); current != sieve.end();) { current = find_if(current, sieve.end(), [](atomic_bool& value) { bool untrue = false; return value.compare_exchange_strong(untrue, true, order); }); if (current == sieve.end()) break; int const claimed = static_cast<int>(distance(sieve.begin(), current)); int zero = 0; while (!output.compare_exchange_weak(zero, claimed, order)) ; for (auto product = 2 * claimed; product < static_cast<int>(sieve.size()); product += claimed) sieve[product].store(true, order); } finished_worker_count.fetch_add(1, order); }; const auto core_count = thread::hardware_concurrency(); vector<future<void>> futures; futures.reserve(core_count); generate_n(back_inserter(futures), core_count, [&worker]() { return async(worker); }); vector<int> result; while (finished_worker_count < core_count) { auto current = output.exchange(0, order); if (current > 0) result.push_back(current); } sort(result.begin(), result.end()); for (auto each : result) cout << each << " "; cout << '\n'; return 0; }
compare_exchange_weak will update (change) the "expected" value (the local variable zero) if the update cannot be made. This will allow overwriting one prime number with another if the main thread doesn't quickly handle the first prime. You'll want to reset zero back to zero before rechecking: while (!output.compare_exchange_weak(zero, claimed, order)) zero = 0;
69,091,069
69,091,142
Unexpected results with array and array as argument
Forgive me for this possibly dumb question. Consider this: int foo(int* arr) { std::cout << arr << "(" << sizeof(arr) << ")"; } int main() { int x[] = {0, 1, 2, 3, 4}; foo(x); std::cout << " " << x << "(" << sizeof(x) << ")"; } Output: 0x7c43ee9b1450(8) 0x7c43ee9b1450(20) - Same address, different size. My understanding is that the function argument is an address specific to the first element of the array, so the size is 8 bytes, and the same should be true for the variable in main too; So how come the size of the variable outside of the function represent the whole array (4 bytes int times 5 elements = 20)? How could I possibly determine from inside the function how large an array actually is?
This is because the types are not the same inside and out side the function. If you make sure the type is the same inside and outside the function you should get the same result. int foo(int (&arr)[5]) { std::cout << arr << "(" << sizeof(arr) << ")"; return 0; } The problem is that arrays decay into pointers at the drop of a hat. So if you pass an array to a function it will easily be converted into a pointer. That is what is happening here. int foo(int* arr) // ^^^^ Notice this is not an array. // It is simply a pointer to an integer // The array has decayed into a pointer to the // first element in the array. { std::cout << arr << "(" << sizeof(arr) << ")"; return 0; } How could I possibly determine from inside the function how large an array actually is? This is actually a real problem with C. In C they solved this by getting you to pass the size of the array as a second parameter: int foo(int* arr, std::size_t size); Then call it from main as: foo(arr, sizeof(arr)/sizeof(arr[0])); // This always works as it done // at compile time and not runtime In C++ we don't usually use C-arrays but prefer std::vector or std::array as the size is easily retrievable. Generally we use a container type C as they are duck types of Container: template<typename C> int foo(C& container) { std::cout << "(" <<container.size() << ")"; return container.size(); }
69,091,389
69,091,517
Overloading the function template
How can I overload the cb function template so that the code will compile? Now the exception is: error C2535: void notify_property <T> :: cb (const F &): member function already defined or declared But the templates are different. template <typename T> class notify_property { public: virtual ~notify_property() {} //1 template <typename F, typename = std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>>>>> void cb(const F& task) { set_cb([task] { try { task(); } catch (...) {} }); } //2 template <typename F, typename = std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>, std::decay_t<T>>>>> void cb(const F& task) { set_cb([this, task] { try { task(_value); } catch (...) {} }); } //3 template <typename F, typename... A, typename = std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>, std::decay_t<T>, std::decay_t<A>...>>>> void cb(const F& task, const A &...args) { set_cb([this, task, args...] { try { task(_value, args...); } catch (...) {} }); } virtual T& operator= (const T& f) { if (f != _value) { _value = f; if (_cb != nullptr) _cb(); } return _value; } virtual const T& operator() () const { return _value; } virtual explicit operator const T& () const { return _value; } virtual T* operator->() { return &_value; } protected: template <typename F> void set_cb(const F& cb) { _cb = std::function<void()>(cb); } std::function<void()> _cb = nullptr; T _value; }; Аnswer: //1 template <typename F, std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>>>>* = nullptr> void cb(const F& task) {...} //2 template <typename F, std::enable_if_t<std::is_void_v<std::invoke_result_t<std::decay_t<F>, std::decay_t<T>>>>* = nullptr> void cb(const F& task) {...}
typename = std::enable_if_t is problematic if duplicated because - as your error mentions - you're defining the same function multiple times, merely with a different default parameter. Change every type template parameter // Type parameter, with a defaulted type typename = std::enable_if_t< ... > // ^^^^^^^^^^^ remove! to a non-type template parameter that is part of the function's signature: // Value (pointer) parameter, with a defaulted value std::enable_if_t< ... >* = nullptr // ^^^^^^^^^^^ add (Or, as cppreference does it) // Value (bool) parameter, with a defaulted value std::enable_if_t< ..., bool> = true // ^^^^^^^^^^^^^^ add
69,091,542
69,091,803
C++ GDI: I am seeking explanation for color matrix such that I can create any color manipulation mask
I am trying to implement an application that can manipulate the background screen color attributes through a transparent window. Basically trying to recreate Color Oracle. I am progressing here through C++:GDI+ resources. This GDI has a Color Matrix concept. I am able to create filters for greyscale(as shown in the example in the last hyperlink), brightness tweaking, saturation tweaking; However, as advanced use cases such as color blindness filter, blue light filter, contrast tweaks - I am using the hit-n-trial approach, It will be much efficient if anyone can take me in the right direction to learn fundamentals of this color matrix. Example Matrix is shown below which boosts saturation by a small factor while restricting brightness component. MAGCOLOREFFECT magEffectSaturationBoost = { { // MagEffectBright { 1.02f, 0.0f, 0.0f, 0.0f, 1.0f }, { 0.0f, 1.02f, 0.0f, 0.0f, 1.0f }, { 0.0f, 0.0f, 1.02f, 0.0f, 1.0f }, { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }, { -0.1f, -0.1f, -0.1f, 0.0f, 0.0f } } } // Using the Matrix ret = MagSetColorEffect(hwndMag, &magEffectSaturationBoost);
It will be much efficient if anyone can take me in the right direction to learn fundamentals of this color matrix. Each color vector is multipled by 5x5 matrix, to make it possible color vector is 5 elements long - the fifth element is a dummy one, this allows to perform additional operations on colors (rotation, scaling, ...). In your example each color component is multiplied by 1.02f making color brighter, after multiplication - from each color component 0.1 value is subtracted. You can find full explanation here: https://learn.microsoft.com/en-us/windows/win32/gdiplus/-gdiplus-using-a-color-matrix-to-transform-a-single-color-use and: https://learn.microsoft.com/en-us/windows/win32/gdiplus/-gdiplus-coordinate-systems-and-transformations-about Few more links: https://docs.rainmeter.net/tips/colormatrix-guide/ https://www.integral-domain.org/lwilliams/math150/labs/matrixcolorfilter.php
69,091,716
69,091,886
Error when compiling c++ program with SFML
I am learning SFML with c++, when I am compiling with mingw32-make it is giving error because I am using class file this is the error: main.o:main.cpp:(.text+0x16): undefined reference to `Game::Game()' main.o:main.cpp:(.text+0x21): undefined reference to `Game::running() const' main.o:main.cpp:(.text+0x30): undefined reference to `Game::pollEvent()' main.o:main.cpp:(.text+0x3b): undefined reference to `Game::update()' main.o:main.cpp:(.text+0x46): undefined reference to `Game::render()' main.o:main.cpp:(.text+0x58): undefined reference to `Game::~Game()' main.o:main.cpp:(.text+0x69): undefined reference to `Game::~Game()' collect2.exe: error: ld returned 1 exit status Makefile:6: recipe for target 'link' failed mingw32-make: *** [link] Error 1 this is the code main.cpp: #include "Game.h" #include <iostream> using namespace std; using namespace sf; int main() { Game mygame; while (mygame.running()){ //poll event mygame.pollEvent(); //update mygame.update(); //render mygame.render(); } //End of the game return 0; } Game.h: #ifndef GAME_H #define GAME_H #pragma once #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <SFML/Network.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> using namespace sf; class Game{ private: //variable RenderWindow *window; Event ev; VideoMode videoMode; //private function void initVar(); void initWindow(); public: //constructor / Destructor Game(); virtual ~Game(); //Accessors const bool running() const; //functions void pollEvent(); void update(); void render(); }; #endif Game.cpp: #include "Game.h" #include <iostream> void Game::initVar(){ this->window = nullptr; } void Game::initWindow(){ this->videoMode.height = 600; this->videoMode.width = 800; this->window = new RenderWindow(this->videoMode, "Game 1", Style::Titlebar | Style::Close | Style::Resize); } //constructure Game::Game(){ this->initVar(); this->initWindow(); } //Destructure Game::~Game(){ delete this->window; } //Accsessors const bool Game::running() const{ return this->window->isOpen(); } //Functions void Game::pollEvent(){ while(this->window->pollEvent(this->ev)){ switch(this->ev.type){ case Event::Closed: this->window->close(); break; case Event::KeyPressed: if(this->ev.key.code == Keyboard::Escape){ this->window->close(); break; } } } } void Game::update(){ this->pollEvent(); } void Game::render(){ this->window->clear(Color(255, 0, 0, 255)); //Draw game objects this->window->display(); } Makefile: all: compile link compile: g++ -I src/include -c main.cpp link: g++ main.o -o main -L src/lib -l sfml-graphics -l sfml-window -l sfml-system
You're not compiling game.cpp, so the linker is looking for the implementation of these functions and is unable to find them. You can update your makefile as follows compile: g++ -I src/include -c main.cpp -c Game.cpp link: g++ main.o Game.o -o main -L src/lib -l sfml-graphics -l sfml-window -l sfml-system and it should work
69,091,745
69,094,750
Fibonacci memoization - pass by lvalue vs rvalue reference
I'm learning about memoization and decided to apply this technique to a recursive function calculating the n-th Fibonacci number. I am not sure whether I should pass my memo map by lvalue reference or rvalue reference. Is there any difference (regarding performance and generally how the program behaves) in the two snippets presented below? Which one would be preferred? Also, is there a way to provide a default argument to the first function (map& memo = map{} doesn't work because an lvalue reference doesn't bind with an rvalue...)? Version #1 using map = std::unordered_map<int, unsigned long long>; unsigned long long fib(int n, map& memo){ if(memo.find(n) != memo.cend()) return memo[n]; if(n <= 2) return 1; memo[n] = fib(n - 1, memo) + fib(n - 2, memo); return memo[n]; } Version #2 using map = std::unordered_map<int, unsigned long long>; unsigned long long fib(int n, map&& memo = map{}){ if(memo.find(n) != memo.cend()) return memo[n]; if( n <= 2) return 1; memo[n] = fib(n - 1, std::move(memo)) + fib(n - 2, std::move(memo)); return memo[n]; }
In C++, moving an object corresponds to the following contract: I am never planning on using this object again. Person I am moving the object to: you are free to do whatever you'd like with this object's resources. I promise not to use the object again without first assigning it a new value, so I will never see the effects of anything you did. So please, do Cruel and Unusual things to my object if it makes you happy. Now, consider this line of code: memo[n] = fib(n - 1, std::move(memo)) + fib(n - 2, std::move(memo)); Here, you are calling std::move(memo), which signals "I promise never to use memo again." However, in the same line of code, you are then assigning to memo[n], which means that you are indeed planning on using memo later. That breaks the contract that you're making with whomever you std::move the object to. Imagine this as a dialog between you and the calls to Fibonacci: You: Hey, Mr. Fibonacci! I got you a memoization table. It's 100% yours and I am never going to use it again. Fibonacci: Great! Thanks! You: Okay, now that I just gave you the memoization table, I'd like to paint it blue and put flowers on it. Fibonacci: Wait, hold on! It's not your table any more! You: Well, I'm going to do it anyway. Fibonacci: Why, you little! (Violence ensues) So, yeah. That's not going to work. Ignoring the assignment to memo[n], there's another issue here. You are trying to move the same object twice to two different people. Think about what that means from the perspective of a conversation between you, the first call to Fibonacci, and the second call to Fibonacci. You: Hey, Mr. First Call to Fibonacci! Here's memo. It's yours. Do whatever you'd like with it. No one else is going to see it. Mr. First Call to Fibonacci: Woohoo! That's awesome! You: Hey, Mr. Second Call to Fibonacci! Here's memo. It's yours. Do whatever you'd like with it. No one else is going to see it. Mr. Second Call to Fibonacci: Woohoo! That's awesome! Mr. First Call to Fibonacci: Wait, hold on! They gave me that object! They can't give it to you! Mr. Second Call to Fibonacci: Weren't you listening? They just gave me that object! It's mine! Mr. First Call to Fibonacci: Why, you little! (Violence ensues) So yeah, that isn't going to end well. :-) Fundamentally, only use std::move when you or anyone else is planning on using that object again. In the case of memoization, when a bunch of function calls all need to coordinate to share the same memoization table across the calls, that requirement isn't held, so you shouldn't use rvalue semantics here.
69,091,769
69,199,056
Fast communication between C++ and python using shared memory
In a cross platform (Linux and windows) real-time application, I need the fastest way to share data between a C++ process and a python application that I both manage. I currently use sockets but it's too slow when using high-bandwith data (4K images at 30 fps). I would ultimately want to use the multiprocessing shared memory but my first tries suggest it does not work. I create the shared memory in C++ using Boost.Interprocess and try to read it in python like this: #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> int main(int argc, char* argv[]) { using namespace boost::interprocess; //Remove shared memory on construction and destruction struct shm_remove { shm_remove() { shared_memory_object::remove("myshm"); } ~shm_remove() { shared_memory_object::remove("myshm"); } } remover; //Create a shared memory object. shared_memory_object shm(create_only, "myshm", read_write); //Set size shm.truncate(1000); //Map the whole shared memory in this process mapped_region region(shm, read_write); //Write all the memory to 1 std::memset(region.get_address(), 1, region.get_size()); std::system("pause"); } And my python code: from multiprocessing import shared_memory if __name__ == "__main__": shm_a = shared_memory.SharedMemory(name="myshm", create=False) buffer = shm_a.buf print(buffer[0]) I get a system error FileNotFoundError: [WinError 2] : File not found. So I guess it only works internally in Python multiprocessing, right ? Python seems not to find the shared memory created on C++ side. Another possibility would be to use mmap but I'm afraid that's not as fast as "pure" shared memory (without using the filesystem). As stated by the Boost.interprocess documentation: However, as the operating system has to synchronize the file contents with the memory contents, memory-mapped files are not as fast as shared memory I don't know to what extent it is slower however. I just would prefer the fastest solution as this is the bottleneck of my application for now.
So I spent the last days implementing shared memory using mmap, and the results are quite good in my opinion. Here are the benchmarks results comparing my two implementations: pure TCP and mix of TCP and shared memory. Protocol: Benchmark consists of moving data from C++ to Python world (using python's numpy.nparray), then data sent back to C++ process. No further processing is involved, only serialization, deserialization and inter-process communication (IPC). Case A: One C++ process implementing TCP communication using Boost.Asio One Python3 process using standard python TCP sockets Communication is done with TCP {header + data}. Case B: One C++ process implementing TCP communication using Boost.Asio and shared memory (mmap) using Boost.Interprocess One Python3 process using standard TCP sockets and mmap Communication is hybrid : synchronization is done through sockets (only header is passed) and data is moved through shared memory. I think this design is great because I have suffered in the past from problem of synchronization using condition variable in shared memory, and TCP is easy to use in both C++ and Python environments. Results: Small data at high frequency 200 MBytes/s total: 10 MByte sample at 20 samples per second Case Global CPU consumption C++ part python part A 17.5 % 10% 7.5% B 6% 1% 5% Big data at low frequency 200 MBytes/s total: 0.2 MByte sample at 1000 samples per second Case Global CPU consumption C++ part python part A 13.5 % 6.7% 6.8% B 11% 5.5% 5.5% Max bandwidth A : 250 MBytes / second B : 600 MBytes / second Conclusion: In my application, using mmap has a huge impact on big data at average frequency (almost 300 % performance gain). When using very high frequencies and small data, the benefit of shared memory is still there but not that impressive (only 20% improvement). Maximum throughput is more than 2 times bigger. Using mmap is a good upgrade for me. I just wanted to share my results here.
69,091,914
69,103,664
Problem with conan package manager while inspect and build
Below conan cmd failed with invalid syntax, but that file is not created by me. Not sure why below error is appearing. $ conan inspect poco/1.9.4 poco/1.9.4: Not found in local cache, looking in remotes... poco/1.9.4: Trying with 'conancenter'... Downloading conanmanifest.txt completed [0.74k] Downloading conanfile.py completed [14.36k] Downloading conan_export.tgz completed [0.30k] Decompressing conan_export.tgz completed [0.00k] poco/1.9.4: Downloaded recipe revision 0 ERROR: Error loading conanfile at '/home/snandi/.conan/data/poco/1.9.4/_/_/export/conanfile.py': Unable to load conanfile in /home/snandi/.conan/data/poco/1.9.4/_/_/export/conanfile.py File "/home/snandi/.conan/data/poco/1.9.4/_/_/export/conanfile.py", line 97 tools.get(**self.conan_data["sources"][self.version], ^ SyntaxError: invalid syntax
Your error occurs because Python 2 can not parse **self.conan_data due unpack feature improvement introduced on Python 3.5 (PEP 448), you have to use Python 3 only. You can validate it simply running: $ python2 Python 2.7.18 (default, Mar 24 2021, 14:28:23) [GCC 10.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> dict(**{'x': 1}, y=2, **{'z': 3}) File "<stdin>", line 1 dict(**{'x': 1}, y=2, **{'z': 3}) ^ SyntaxError: invalid syntax $ python3 Python 3.9.6 (default, Jun 30 2021, 10:22:16) [GCC 11.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> dict(**{'x': 1}, y=2, **{'z': 3}) {'x': 1, 'y': 2, 'z': 3} Thus, to solve your problem: First, uninstall Conan from python2: python2 -m pip uninstall conan Then, keep only the python 3 version installed: python3 -m pip install -U conan If you have some difficult managing your Python environment in your host, I would suggest using pyenv, which manage the global version installed.
69,092,014
69,092,165
C++: will an std::runtime_error object leak in a longjmp?
Suppose I have some C++ code which has a try-catch block in which the catch part will trigger a long jump: #include <stdexcept> #include <stdio.h> #include <setjmp.h> void my_fun() { jmp_buf jump_buffer; if (setjmp(jump_buffer)) return; try { std::string message; message.resize(100); snprintf(&message[0], 100, "error code %d\n", 3); throw std::runtime_error(message); } catch (std::runtime_error &e) { longjmp(jump_buffer, 1); } } Since the std::runtime_error object was allocated dynamically somewhere, will it leak the memory that was allocated for it or for the string?
This is kind of complicated. About longjmp's validity, the standard says: A setjmp/longjmp call pair has undefined behavior if replacing the setjmp and longjmp by catch and throw would invoke any non-trivial destructors for any objects with automatic storage duration. runtime_error has a non-trivial destructor, so the question is whether the exception object has "automatic storage duration". It does not. This suggests that longjmp should be fine. In addition, exception object destruction can happen in one of two places: The points of potential destruction for the exception object are: when an active handler for the exception exits by any means other than rethrowing, immediately after the destruction of the object (if any) declared in the exception-declaration in the handler; when an object of type std​::​exception_­ptr that refers to the exception object is destroyed, before the destructor of std​::​exception_­ptr returns. longjmp is not "rethrowing". So in theory, this should be fine thanks to bullet point 1. That being said, never rely on this. I highly doubt that implementations of longjmp handle this correctly, and even if some do, it's probably not something you can expect.
69,092,160
69,092,196
Best practice when setting a string to (possibly) its own value?
Community, I have a scenario where I want to append a prefix '*' to a tab in a QTabWidget in case it is not saved. The relevant code is working fine and something along these lines: auto index = m_tabWidget->indexOf(tab); auto tabName = (canBeSaved) ? "*" + tab->getName() : tab->getName(); if (m_tabWidget->tabText(index) != tabName) m_tabWidget->setTabText(index, tabName); The alternative is to always call the setter without condition m_tabWidget->setTabText(index, tabName); My Question is: Does checking the tabName for changes make up the expense of the (potentially) skipped setText? Is there a general rule of thumb, whether to check for equality before setting a variable or not? Thank you all in advance.
It doesn't matter in these cases. Pick what looks clearest to you and your team. Don't sweat over it. There's no general rule of thumb either. There are specific cases where checking before setting is a must because of some side effects in the setter and there are specific cases where settings regardless is a must because of performance criticality / checking is expensive / multithreading, this case is neither.
69,092,611
69,093,288
Unable to make an Producer-Consumer instance with list in c++
guys. I am learning about the Producer-Consumer Problem. My professor gave us an example code using a classical int array to share resources between the two threads. It works as expected, however, I wanted to try it using std:list class from C++ and it doesn't work as expected. The consumer seems not to respect sem_wait(&full); so it tries to consume many times when there is nothing in the shared list. Original code with array buffer #include <pthread.h> #include <semaphore.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #define N 2 #define TRUE 1 int buffer[N], in = 0, out = 0; sem_t empty, full, mutexC, mutexP; void *producer(void *arg) { while(TRUE) { sleep(rand()%5); sem_wait(&empty); sem_wait(&mutexP); buffer[in] = rand() % 100; printf("Producing buffer[%d] = %d\n", in, buffer[in]); in= (in+1) % N; sem_post(&mutexP); sem_post(&full); } } void *consumer(void *arg) { while(TRUE) { sleep(rand()%5); sem_wait(&full); sem_wait(&mutexC); printf("Consuming buffer[%d] = %d\n", out, buffer[out]); out = (out+1) % N; sem_post(&mutexC); sem_post(&empty); } } int main(int argc, char *argv[ ]) { pthread_t cons, prod; sem_init(&mutexC, 0, 1); sem_init(&mutexP, 0, 1); sem_init(&empty, 0, N); sem_init(&full, 0, 0); pthread_create(&prod, NULL, producer, NULL); pthread_create(&cons, NULL, consumer, NULL); pthread_exit(0); } My implementation with list: #include <pthread.h> #include <semaphore.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <list> #define TRUE 1 #define N 2 using namespace std; list<int> sharedList; sem_t empty, full, mutexC, mutexP; void *producer(void *arg) { while(TRUE) { sleep(rand()%5); sem_wait(&empty); sem_wait(&mutexP); int prod = rand() % 100; cout << "producing: " << prod << endl; sharedList.push_back(prod); sem_post(&mutexP); sem_post(&full); } } void *consumer(void *arg) { while(TRUE) { sleep(rand()%5); sem_wait(&full); sem_wait(&mutexC); if (!sharedList.empty()) { cout << "consuming: "; cout << sharedList.front() << endl; sharedList.pop_front(); } else { cout << "not possible to consume" << endl; } sem_post(&mutexC); sem_post(&empty); } } int main(int argc, char *argv[ ]) { pthread_t cons, prod; sem_init(&mutexC, 0, 1); sem_init(&mutexP, 0, 1); sem_init(&empty, 0, N); sem_init(&full, 0, 0); pthread_create(&prod, NULL, producer, NULL); pthread_create(&cons, NULL, consumer, NULL); pthread_exit(0); } The - unexpected - logs from my implementation: producing: 73 consuming: 73 not possible to consume producing: 44 consuming: 44 producing: 9 producing: 65 consuming: 9 producing: 87 consuming: 65 consuming: producing: 29 87 not possible to consume consuming: 29 producing: 9 producing: 60 consuming: 9 producing: 78 Can somebody explain to me what is happening? Thanks in advance!
In the first place, note that in both programs: with only one producer ever contending for semaphore mutexP, that semaphore serves no useful purpose. Likewise, with only one consumer ever contending for semaphore mutexC, that serves no useful purpose either. Now, consider what purpose is served in your first program by initializing semaphore empty with value 2 instead of value 1: I presume that you will agree that doing so allows the producer to run concurrently with the consumer, one position ahead. This is ok because accesses to different array elements do not conflict. But when your storage is a std::list instead of an array, it is not ok for two threads to manipulate it concurrently if one of them modifies it. There are several complementary ways to look at it, among them: a std::list is a single object, access to which must be synchronized, whereas an array is merely an aggregate of its elements, not a distinct object of its own as far as synchronization requirements are concerned. a std::list has members -- maintaining the current list size, for example -- that are used by all manipulations, access to which must be synchronized. However you choose to look at it, you must ensure that the std::list cannot be accessed concurrently by two threads if one of those threads modifies it.
69,092,639
69,106,833
Can a parameter pack in function template be followed by another parameter which depends on the return type?
I have a function where a template type parameter follows a parameter pack. It looks like this: template<typename...Args, typename T> T* default_factory_func() { return new T; } Visual C++ compiler rejects it with an error C3547: template parameter 'T' cannot be used because it follows a template parameter pack and cannot be deduced from the function parameters of 'default_factory_func'. However, I tried various versions of GCC (starting with 4.4.7) and clang (starting with 3.1) available on Compiler Explorer, and all of them compile such code just fine. // this code is just a minimal example condensed // from a much more complex codebase template<typename T> T* construct(T* (*factory_func)()) { return factory_func(); } template<typename...Args, typename T> T* default_factory_func() // C3547 on this line { return new T(Args()...); } struct some_class { some_class(int, int, int) {} }; int main() { construct<some_class>( default_factory_func<int,int,int> ); } Is this some quirk of MSVC or is it not allowed by the standard?
I think the standard is confused here (probably needs an issue if one doesn't already exist). The definition of default_factory_func is ill-formed per [temp.param] A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced from the parameter-type-list ([dcl.fct]) of the function template or has a default argument At the same time, the types of default_factory_func can be (arguably) deduced per [temp.deduct.funcaddr] because you are attempting to match a target type of some_class*(*)(void) when you pass &default_factory_func<int,int,int> Template arguments can be deduced from the type specified when taking the address of an overload set. If there is a target, the function template's function type and the target type are used as the types of P and A, and the deduction is done as described in [temp.deduct.type]. Otherwise, deduction is performed with empty sets of types P and A (Thanks to n.m. for pointing this second one out in their now-deleted-answer) I think the safest bet would be to avoid running afoul of the first rule by reordering your template arguments: template<class T, typename...Args> T* default_factory_func() { return new T(Args()...); } And then explicitly casting your function pointer to resolve the overload: auto foo = construct( static_cast<some_class*(*)()>(default_factory_func<some_class, int, int, int>) ); Live Code (Compiles on gcc/clang/and msvc latest)
69,092,743
69,094,472
SQL numeric/decimal to boost multiprecision
I'm looking for some (non-string) type in C++ that we can use to store a SQL numeric(18, 4) (or decimal(18, 4)) value. I went through the documentation of boost's cpp_dec_float, but am still quite confused about how to use it: When the doc says "decimal digits" (e.g. in "The typedefs cpp_dec_float_50 and cpp_dec_float_100 provide arithmetic types at 50 and 100 decimal digits precision respectively"), is it referring to the number of digits to the right of the decimal point or all the significant digits? std::numeric_limits<number<cpp_dec_float<50>>>::digits10 is 50 but std::numeric_limits<number<cpp_dec_float<4>>>::digits10 is 9. Why is that? If the Digits10 template parameter is the number of all significant digits, does it mean there is no way to specify a fixed precision and a scale (as in SQL numeric(18, 4)) for boost multiprecision types?
When the doc says "decimal digits" (e.g. in "The typedefs cpp_dec_float_50 and cpp_dec_float_100 provide arithmetic types at 50 and 100 decimal digits precision respectively"), is it referring to the number of digits to the right of the decimal point or all the significant digits? All the significant digits. std::numeric_limits<number<cpp_dec_float<50>>>::digits10 is 50 but std::numeric_limits<number<cpp_dec_float<4>>>::digits10 is 9. Why is that? It's an implementation detail. Basically, the library provides the minimum it requires to deliver you the promised 4 digits If the Digits10 template parameter is the number of all significant digits, does it mean there is no way to specify a fixed precision and a scale (as in SQL numeric(18, 4)) for boost multiprecision types? Indeed. In short, the multi-precision library does not provide any fixed-point types (though you can obviously make your own with something like cpp_int)
69,092,846
69,092,936
Finding a struct in a vector
I want to find a struct whose all member data match certain values. I made a following short program: #include <iostream> #include <vector> using namespace std; struct vlan { int vlanId; bool status; }; vector<vlan> vlanTable; int main(){ vlan tmp; tmp.status = true; tmp.vlanId = 1; vector <vlan>::iterator flag = find(vlanTable.begin(), vlanTable.end(), tmp); if ( flag != vlanTable.end()){ cout<<"found"<<endl; } else cout<<"not found"<<endl; return 0; } It returns error as: template argument deduction/substitution failed right at the find function. Could someone help me?
You need to provide the == operator for your vlan class: struct vlan { int vlanId; bool status; bool operator==(const vlan& rhs) const { return (vlanId == rhs.vlanId) && (status == rhs.status); } }; Also, as noted in the comments, you should #include <algorithm> (for the definition of std::find); some compilers may implicitly include this from other headers, but don't rely on that. Note that, as per the comment made by aschepler, if you have a compiler that conforms to the C++20 (or later) Standard, you can define the operator== for your vlan class as defaulted: struct vlan { int vlanId; bool status; bool operator==(const vlan& rhs) const = default; // C++20 }; For your vlan struct, this will perform the exact same comparison(s) as the 'explicit' version defined above. From cppreference (or the Draft C++20 Standard itself): Defaulted equality comparison A class can define operator== as defaulted, with a return value of bool. This will generate an equality comparison of each base class and member subobject, in their declaration order. Two objects are equal if the values of their base classes and members are equal. The test will short-circuit if an inequality is found in members or base classes earlier in declaration order.
69,093,021
69,094,164
g++ error in compiling while using std::string[5] as a type in std::map<>
I am fairly new to c++, I was making a encryptor to imrpove my c++, at first I kept my Cryptographer class in cryptographer.hpp and then added function body in cryptographer.cpp and then included cryptographer.hpp in main.cpp it gave me a compiler error, so I just pasted the code in main.cpp like this #include <iostream> #include <map> class Cryptographer{ public: int n_factor; std::string text; Cryptographer(std::string user_arg, int user_n_factor); struct cryptographer { std::string encrypted_text; std::string generated_key=""; }; cryptographer crypted_text; void generate_key(); void encrypt(); void decrypt(); std::string get_key(); std::string get_text(); }; using key_map = std::map<char, std::string[5]>; void Cryptographer::generate_key(){ for (int _ = 0; _ < 5; _++){ crypted_text.generated_key += rand() % 26 + 65; } } void Cryptographer::encrypt(){ generate_key(); key_map keyHashMap; for (auto key_letter: crypted_text.generated_key){ int key_letter_int = (int) key_letter; std::string key_letter_arr[5]; int memory_number = key_letter_int; for (int index=0; index < 5; index++){ if (memory_number+n_factor > 91){ memory_number = 65; }else{ key_letter_arr[5] = std::string(1, char (memory_number + n_factor)); memory_number += n_factor; } } keyHashMap.emplace(key_letter, key_letter_arr); } for(int index=0; index<text.size(); index++){ int key = index %4; int key_patter = rand()% 4; int checking_index = 0; for (auto &elem: keyHashMap){ if (checking_index == key){ std::cout << elem.second[1]; } } } crypted_text.encrypted_text = "test"; } Cryptographer::Cryptographer(std::string user_arg, int user_n_factor): text(user_arg), n_factor(user_n_factor) {} int main(){ Cryptographer crypter("hello guys", 3); crypter.encrypt(); std::cout << crypter.get_text(); return 0; } and ran this in my terminal g++ main.cpp -o test and it popped this large error https://hastebin.com/cibeyanoro.cpp I am on ubuntu 20.04, I also tried removing and reinstalling latest version of g++ but the same error pops up.
g++ error in compiling while using std::string[5] as a type in std::map<> Arrays cannot be stored as elements of std::map. You can store classes though, and arrays can be members of a class. The standard library provides a template for such array wrapper. It's called std::array. You can use that as the element of the map instead. Sidenote: std::map isn't the only standard container with such limitation. std::array is the only standard container that can itself contain arrays as elements.
69,093,694
69,093,773
Moving the input file with c++
I want to be able to enter any file in MoveFile() and it will move the file to this folder: C:\folder\fl.txt. When I enter MoveFileA("C:\\fl.txt", "C:\\folder\\fl.txt"); Then everything works, but I need to move the first file (the one that is fl.txt) to folder ... How can this be implemented so as not to always enter the file name (C:\folder\fl.txt) so that it auto inputs it? Here is my code: #include <iostream> #include <string> #include <Windows.h> #include <stdio.h> #include <cstdlib> using namespace std; int main() { MoveFileA("C:\\fl.txt", "C:\\folder\\fl.txt"); cout << "Operation Succesful" << endl; cout << endl; system("pause"); } I need something like: int main() { int path_a; cin >> path_a; MoveFileA("path_a", "C:\\folder\\path_a"); cout << "Operation Succesful" << endl; cout << endl; system("pause"); }
Perhaps you are looking for something like this: #include <iostream> #include <string> #include <cstdlib> #include <Windows.h> using namespace std; int main() { string filename; cin >> filename; if (MoveFileA(("C:\\"+filename).c_str(), ("C:\\folder\\"+filename).c_str())) cout << "Operation Successful" << endl; else cout << "Operation Failed" << endl; cout << endl; system("pause"); } Though, if you are using C++17 or later, you might consider a pure C++ solution using std::filesystem::rename() instead of the Windows-specific MoveFileA() function, eg: #include <iostream> #include <string> #include <filesystem> #include <system_error> #include <cstdlib> using namespace std; namespace fs = std::filesystem; int main() { fs::path filename; cin >> filename; fs::path root("C:\\"); error_code ec; fs::rename(root / filename, root / "folder" / filename, ec); if (ec) cout << "Operation Failed" << endl; else cout << "Operation Successful" << endl; cout << endl; system("pause"); }
69,094,044
69,094,253
Is there a way to seclude a loop in c++?
I'm trying to make an auto clicker with left and right mouse buttons but each with different delay, I'm quite familiar with lua so I'll try explain something similar in lua. So in lua you could use a corontine and your function would look something like this... coroutine.wrap(function() while (true) do --some code here end end) But this means is that we could stack them and run 2 loops simultaneously, I want to know if there's a way to do something similar in c++ so I could run 2 loops with different delays #include <iostream> #include <Windows.h> int main() { std::cout << "Hello World!\n"; while (true) { if (GetAsyncKeyState(VK_LBUTTON)) { Sleep(65); // IF BOTH BUTTONS ARE DOWN THEN DELAY WOULD BE HIGHER INPUT iNPUT = { 0 }; iNPUT.type = INPUT_MOUSE; iNPUT.mi.dwFlags = MOUSEEVENTF_LEFTDOWN; SendInput(1, &iNPUT, sizeof(iNPUT)); ZeroMemory(&iNPUT, sizeof(iNPUT)); iNPUT.type = INPUT_MOUSE;; iNPUT.mi.dwFlags = MOUSEEVENTF_LEFTUP; SendInput(1, &iNPUT, sizeof(iNPUT)); } if (GetAsyncKeyState(VK_RBUTTON)) { Sleep(200); // IF BOTH BUTTONS ARE DOWN THEN DELAY WOULD BE HIGHER INPUT iNPUT = { 0 }; iNPUT.type = INPUT_MOUSE; iNPUT.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN; SendInput(1, &iNPUT, sizeof(iNPUT)); ZeroMemory(&iNPUT, sizeof(iNPUT)); iNPUT.type = INPUT_MOUSE;; iNPUT.mi.dwFlags = MOUSEEVENTF_RIGHTUP; SendInput(1, &iNPUT, sizeof(iNPUT)); } } }
There are many ways to do that. They fall in 3 categories. Threads. They are like Lua coroutines but run in parallel instead of scheduled. That simplifies some things but requires extreme care in others. Since C++11 you can use its native threads, that’s easier than using Windows API directly. Coroutines. As pointed in the comments C++ has those since C++20, but Windows had them since ever: fibers. They work much like Lua coroutines but need a bit more setup. Action queue. Use a queue ordered on absolute time (not delay) the action should be executed. Instead of calling Sleep and doing stuff afterwards, enqueue the action; at beginning of an iteration, check which queued action should be executed first and sleep just the time remaining to it before executing it (or do some other work until it’s time to execute some queued action).
69,095,011
69,095,075
Is there anyway to get a lambda's return value by deduction without passing the argument types?
Consider the following example: template<auto const fnc> struct dummy_s { typedef std::invoke_result<decltype(fnc), std::uint8_t >::type return_t; }; int main() { dummy_s<[](std::uint8_t const& n) -> bool { return true ^ n; }>::return_t s = true; } Is there anyway to get the return type without specifying std::uint8_t or whatever the number of arguments is, as template parameter as example.
You could write a metafunction that gives you the type of the first argument template<typename Ret, typename Arg> auto arg(Ret(*)(Arg)) -> Arg; and then decay the lambda fnc to a function pointer (using + say), that you pass to arg, and then use that in the typedef. typedef std::invoke_result<decltype(fnc), decltype(arg(+fnc))>::type return_t; This will only work for lambdas that don't capture anything, and that take a single argument. You can also considerably simplify the typedef inside the struct by simply using arg directly like this using return_t = decltype(arg(+fnc)); // using is cleaner than a typedef as well This avoids using invoke_result entirely, and lets you define arg in a way that allows lambdas with multiple arguments to be passed to it template<typename Ret, typename Arg, typename ...R> auto arg(Ret(*)(Arg, R...)) -> Arg; Here's a demo
69,095,126
69,095,444
How to convert std::views::join result to string_view at compile time?
I want to make the whole code work as constexpr. Here's what works: #include <iostream> #include <ranges> #include <string_view> int main() { constexpr std::string_view words{"Just some sentence I got from a friend."}; auto rng = words | std::views::split(' ') | std::views::take(4) | std::views::join; std::string_view first_four_words{&*rng.begin(), std::ranges::distance(rng)}; std::cout << first_four_words << std::endl; } But If I add constexpr to the rng and first_four_words lines, I get compilation error. I thought maybe cbegin() would solve it, but I wasn't able to compile it with cbegin regardless of the const qualifier, since it refuses to take rng... So, is there a way to make it work as constexpr? And as an aside, is there a more elegant way to build this string_view? The &* is particularly ugly.
The right way to do this is to shove it in a function, like so: constexpr std::string_view first_n_words(std::string_view str, size_t n) { auto first_n = str | rv::split(' ') | rv::take(n) | rv::join; auto const len = std::min(str.size(), std::ranges::distance(first_n) + n - 1); return std::string_view(&*first_n.begin(), len); } This doesn't compile right now, because gcc doesn't yet implement P2231, which is required in order to for join_view to work at compile time, and then libstdc++ needs to change their implementation of emplace_deref to both mark it constexpr (as it is defined to be, filed #102236). Note that (as 康桓瑋 points out in the comments), std::ranges::distance is the wrong length for the string_view, since you're not account for the extra space delimiters that are removed by the split. The len adjustment above should account for that correctly. You cannot do it this way: constexpr auto rng = words | split(' ') | take(4) | std::views::join; Because this would be joining a range of prvalue ranges (from the split), and that case is not const-iterable (because we need to cache each sub-range that we're joining, which has to be cached into the join_view itself, which requires mutation, and so we can't do it). The resulting object has to be mutable, which means you can't declare it constexpr (which is why my way above should work, once fully implemented). And as an aside, is there a more elegant way to build this string_view? The &* is particularly ugly. Not really. In order for views::join to be able to reliably give you a contiguous range, it's not enough to know that we're joining a range of contiguous ranges, we also have to know that those contiguous pieces are themselves contiguous. And... they're not in this case (because we're dropping the space delimiter). Even if there were some mechanism to preserve contiguity (and I have no idea what such a mechanism would look like), this wouldn't even be a valid place to apply it - we do not have a contiguous range here. But in this case you know that those pieces happen to be contiguous, because you know everything about how we're constructing this pipeline and that this is a safe operation to do, because you know you want to keep in the spaces that are separating your contiguous subranges. But you're going outside of the ranges model here and doing something potentially unsafe, so that's just going to be a little ugly.
69,095,409
69,098,886
How do I calculate the opimal size of the bytes to read from a file using QIODevice:read()?
The thing is, I have to read the file and write its data to another file. But the size might be so big (larger than 8 gb) so I read the files by chunks (1 mb), but I think the optimal size of the chunks can be calculated, so how do I do this? what tools should I use? Here's the code const int BLOCK_SIZE = 1000000; if(!(fin.open(QIODevice::ReadOnly)) == false && !(fout.open(QIODevice::WriteOnly)) == false) {\ long long m_file_size = fin.size(); QDataStream in(&fin); QByteArray arrayOfBytes; int counting = 0; int check = 0; long int bytesPerSecond = 0; timer.start(); for(size_t i = 0; i <= m_file_size / BLOCK_SIZE; ++i) { arrayOfBytes = fin.read(BLOCK_SIZE); fout.write(arrayOfBytes); bytesPerSecond +=BLOCK_SIZE; if ((100 * ((timer.elapsed() + 50) / 100)) > 999 && (100 * ((timer.elapsed() + 50) / 100)) % 1000 == 0 && check != (100 * ((timer.elapsed() + 50) / 100))) { counting++; check = (100 * ((timer.elapsed() + 50) / 100));//(10 * ((timer.elapsed() + 5) / 10)); bytesPerSecond = 0; } } fin.close(); fout.close(); } else{ qDebug()<<"Failed to open"; } }
Try this: https://doc.qt.io/qt-5/qstorageinfo.html#blockSize If you are interested in tracking copying progress AND optimize the copying for speed at the same time, you might need to write platform specific code. On linux it might be sendfile(). On Windows you may need to call WinAPI... But I would start with some naive solution (like the one you have), then try to optimize buffer size (do measurements to measure the speed gains for each change) and only then try to use platform-native calls (and measure again). You may also have a look at this answer: Copy a file in a sane, safe and efficient way And also this: Why is copying a file in C so much faster than C++? PS: when measuring improvements, be careful about warm-up phase. Copying will be of course much faster if the file is already in the cache... So first copying will be always slower and subsequent copying will be usually faster regardless of the method. In other words, you must make sure to compare "apples-to-apples".
69,095,605
69,095,637
Why is *int different from []int in go
I worked with C and C++ for a while before starting to learn go, and I'm curious why *int and []int are treated as different types in golang. Whether you want to think of it as an array or not is up to you, but they should both be pointers to some location in memory indicating the beginning of a list of type int. That list may very well be of size one, but my point is, why are []int and *int not the same thing in go?
An []int has three values internally: pointer to backing array, length of backing array and capacity of backing array. The Go runtime ensures that the application does index outside the bounds of the backing array. An *int is just a pointer as in C. Because Go does not have pointer arithmetic (outside of the unsafe package), a *int cannot be used like an array as in C.
69,095,609
69,095,841
c++ Gaussian random number generator keeps generating same sequence
I'm trying to implement a C++ class that generates Gaussian (aka normal) random floats using an API similar to Python's Numpy random number generator: numpy.random.normal(loc, scale) where loc is the mean and scale is the standard deviation. Below is my attempt. #include <cstdio> #include <random> #include <ctime> class Gaussian { std::default_random_engine gen; public: Gaussian() { srand((unsigned int)time(NULL)); } double get(double mean, double std) { std::normal_distribution<double> nd(mean, std); return nd(gen); } }; The problem is that in my main() function, I generate 10 random doubles, and the sequence is always the same. I am using g++ on a Mac. int main(int argc, char**argv) { srand((unsigned int)time(NULL)); Gaussian g; int N = 10; double mean = 50.0; double std = 2.0; for (int i = 0; i < N; i++) { double value = g.get(mean, std); printf("%f\n", value); } } // Compile: g++ main.cpp Consistently produces over multiple invocations: 47.520528 53.224019 52.765603 48.191707 46.679143 50.151444 50.194442 49.542437 51.169795 51.069510 What is going on?
The std::default_random_engine gen needs to be seeded differently if you want different output. The default constructor, which is what it is constructed with in your example, will always seed with default_seed, which will always be the same. You can supply a seed using any standard C++ method to construct a class member, such as an initializer list in your constructor: public: Gaussian() : gen{ time(NULL) } { } Or you could call gen.seed() in the constructor, which would be less efficient since the generator is effectively being seeded twice, once at construction and again when seed() is called. The exact engine used by std::default_random_engine is implementation defined, but we do know that srand() has no effect on it.* This is really the fundamental flaw of the example code: The attempt to seed the random generator with srand() has no effect. It also worth noting the time(NULL) returns the time in seconds. If you initialize the generator multiple times in the same second, you'll get the same output. std::chrono::high_resolution_clock::now().time_since_epoch().count() might be a better choice for simple clock based seeding. Also note that re-creating the distribution object for each individual random number is inefficient. It would be better to keep using the same object if many random numbers of the same mean and std. dev. are needed. * This comes from C++11 §[rand.req.eng] Table 117: The default constructor "[c]reates an engine with the same initial state as all other default-constructed engines of type E." And the function call operator "[a]dvances e’s state ei to ei+1 = TA(ei) ..." This leaves no possibility for srand() to change the state of a default constructed engine nor to affect an engine's state once constructed (i.e., re-seed it).
69,095,617
69,095,698
How do I return a range view from a function?
What is the right way to implement the function below to allow the caller to iterate over the range it returns? #include <set> #include <ranges> std::set<int> set{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto find_range(int a) { //What type should I return? return std::make_tuple(set.lower_bound(a - 3), set.upper_bound(a + 3)); } int main() { for (int x : find_range(5)) {...} } The function returns a couple of iterators pointing to 2 and 9, so the loop should iterate over 2, 3, 4, 5, 6, 7, 8.
You can return a subrange like this auto find_range(int a) { return std::ranges::subrange(set.lower_bound(a - 3), set.upper_bound(a + 3)); } Here's a demo.
69,096,269
69,096,472
gnu ld treating assembly output as linker script, how to fix? or am i doing something wrong in my compiling?
i've been working on my kernel project and to simulate it (that is to run it on QEMU), i need it as a .iso file. I have an assembly file and to assemble it - as --32 boot.s -o boot.o and for the main code (which is in c++), to compile it - gcc -S kernel.cpp -lstdc++ -o kernel.o gives no error. but, while linking it with this linker script:- ENTRY(_start) SECTIONS { /* we need 1MB of space atleast */ . = 1M; /* text section */ .text BLOCK(4K) : ALIGN(4K) { *(.multiboot) *(.text) } /* read only data section */ .rodata BLOCK(4K) : ALIGN(4K) { *(.rodata) } /* data section */ .data BLOCK(4K) : ALIGN(4K) { *(.data) } /* bss section */ .bss BLOCK(4K) : ALIGN(4K) { *(COMMON) *(.bss) } } (the linking command i'm using is ld -T linker.ld kernel.o boot.o -o OS.bin) it says:- ld:kernel.o: file format not recognized; treating as linker script ld:kernel.o:1: syntax error am i doing something wrong with linking or assembling boot.s or compiling kernel.cpp?
gcc -S produces assembly language, but ld expects an object file. Somewhere in between you have to run the assembler. There's no particular need to use the assembler output, so most likely you want to use -c, which does compilation and then assembly to produce an object file, instead of -S: gcc -c kernel.cpp -o kernel.o The -lstdc++ is useless because it only applies when linking, and anyway it seems unlikely that you can successfully use the standard C++ library in a kernel.
69,096,279
69,096,391
Can't compare two ranges
Can't figure out why std::ranges::equal in the code below does not compile: struct A { int x; }; using Map = std::map<int, A>; void some_func() { std::vector<A> v{ {0}, {1}, {2}, {3} }; auto v2m = [](const A& a) { return std::pair<int, A>(a.x, a); }; const auto actual = std::ranges::single_view(v[2]) | std::views::transform(v2m); Map expected{ {v[2].x, v[2]} }; //Does not compile. bool equals = std::ranges::equal(actual, expected); } The compiler errors with MSVC are: error C2672: 'operator __surrogate_func': no matching overloaded function found error C7602: 'std::ranges::_Equal_fn::operator ()': the associated constraints are not satisfied
Problem 1: A isn't comparable, so you cannot compare it using std::ranges::equal with the default predicate. Solution: struct A { int x; friend auto operator<=>(const A&, const A&) = default; }; Problem 2: Your transform function produces std::pair<int, A> which doesn't match with the elements of map which are std::pair<const int, A>. Solution: use std::pair<const int, A> (or just Map::value_type so that there's less room for mistakes).
69,096,334
69,096,421
Creating a randomly generated graph matrix in C++
So, I've been desperately trying to make this randomly generated graph matrix, but I cannot make it work and I don't know why, getting segfault all the time. This is my code: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; const int graph_size = 4; int main(void) { bool** graph; srand(time(0)); graph = new bool*[graph_size]; for(int i=0; i<graph_size; i++) { graph[i] = new bool[graph_size]; for(int j=0; j<graph_size; j++) { if(i==j){graph[i][j]=false;} else{ graph[j][i] = (((rand()%100)/100.0) < 0.19); graph[i][j] = graph[j][i]; } cout << graph[i][j]; } cout << endl; } }
Your problem is when you do graph[j][i] when j is bigger than i. When that happens, you didn't allocate the array for this index yet which triggers the segmentation fault. Also, as pointed out by @Jeffrey, since you construct a symmetric matrix you should only calculate the upper or lower triangular matrix You can fix it by initializing you graph at the beginning and adding a condition on i and j: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; const int graph_size = 40; int main(void) { bool **graph; graph = new bool *[graph_size]; for (int i = 0; i < graph_size; i++) graph[i] = new bool[graph_size]; srand(time(0)); for (int i = 0; i < graph_size; i++) { for (int j = 0; j < graph_size; j++) { if (i == j) graph[i][j] = false; else if (i < j) // limits to upper triangular matrix { graph[j][i] = (((rand() % 100) / 100.0) < 0.19); graph[i][j] = graph[j][i]; } cout << graph[i][j]; } cout << endl; } }
69,096,632
69,097,011
How to use factory method with multi string parameters to create a template class?
I have a factory function with two string parameters (each parameter indicates a class). How could I reduce using if branches? A create_A(string type, string order){ if (type=="LLT" && order == "AMD"){ return A<LLT, AMD>(); } elif(type=="LLT" && order=="COLAMD"){ return A<LLT, COLAMD>(); } elif(type=="LU" && order=="AMD"){ return A<LU, AMD>(); } elif(type=="LU", && order="COLAMD"){ return A<LU, COLAMD>(); } } UPDATE: I have tried this, too. But I would still like to reduce the if branches. std::unique_ptr<Base> create_A(string type, string order){ if (type=="LLT" && order == "AMD"){ return std::make_unique<Derived<LLT, AMD>>(); } else if(type=="LLT" && order=="COLAMD"){ return std::make_unique<Derived<LLT, COLAMD>>(); } else if(type=="LU" && order=="AMD"){ return std::make_unique<Derived<LU, AMD>>(); } else if(type=="LU", && order="COLAMD"){ return std::make_unique<Derived<LU, COLAMD>>(); } }
One way to reduce this code would be to use a std::(unsorted_)map with a std::pair<std::string,std::string> as the key type, and lambdas or free functions as the value type. However, a function can't return different types, and A<w,x> is a distinct type from A<y,z>. If you really want this to work, you should derive A from a non-template base class, return a pointer to that base class, and then create your A objects dynamically, eg: using key_type = std::pair<std::string, std::string>; using func_type = std::unique_ptr<Base> (*)(); #define MAKE_ENTRY(type, order) {{#type, #order}, []() -> std::unique_ptr<Base> { return std::make_unique<Derived<type, order>>(); } std::unique_ptr<Base> create_A(string type, string order){ static std::unordered_map<key_type, func_type> A_types = { MAKE_ENTRY(LLT, AMD), MAKE_ENTRY(LLT, COLAMD), MAKE_ENTRY(LU,AMD), MAKE_ENTRY(LU, COLAMD) }: auto func = A_types.at(std::make_pair(type, order)); return func(); }
69,097,191
69,097,300
Variable pack in C++
There is already parameter pack in C++, can i declare a variable pack based on the parameter pack? E.g., template<typename... Args> bool all(Args... args) { // Is the following definition of member_a possible? auto const & member_a = args.a; ... return (... (member_a.isValidState() && member_a.isStateStable())); } EDIT Or a little bit more complex, template<typename... Args> bool all(Args... args) { // function returnCurrentOrLast can be expensive, so it's // desired to call it once. auto const & a = args.returnCurrentOrLast(true); ... return (... (a.isValidState() && a.isStateStable())); }
Yes, you can use pack expansion in lambda init-capture to do this. #include <utility> template<typename... Args> bool all(Args... args) { return [&...member_a = std::as_const(args.a)] { return (... && (member_a.isValidState() && member_a.isStateStable())); }(); } Demo.
69,097,245
69,097,325
How does the compiler evaluates expression with multilple comparison operators inside of the if-statement?
So I have this program that returns "result: true" if (true == false != true) { cout << "result: true"; } else { cout << "result: false"; } even if we flip the comparison operators inside of the if-statement, the compiler still evaluates the expression to be true if (true != false == true) My question is: How does the compiler actually evaluates the expression? and to which comparison operator out of the two present inside of the if-statement, preference is given?
The answer to both of your questions is operator precedence. The == and != operators get the same precedence, meaning they will be evaluated in the order given. So in true == false != true, is evaluated as (true == false) != true first statement true==false being false, the full statement now becomes false!=true which evaluates to true Similarly, 2nd statement true != false == true becomes (true != false) == true which evaluates to true at the end EDIT: After reading @Pete's comment, I did some more reading. Apparently there is an associativity property related to these kinds of situations From https://en.cppreference.com/w/cpp/language/operator_precedence Operators that have the same precedence are bound to their arguments in the direction of their associativity. For example, the expression a = b = c is parsed as a = (b = c), and not as (a = b) = c because of right-to-left associativity of assignment, but a + b - c is parsed (a + b) - c and not a + (b - c) because of left-to-right associativity of addition and subtraction.
69,097,568
69,099,210
Back-face culling, does chosen vertex for view vector on triangle matter?
I want to hand implement back-face culling, before passing the tris to the GPU. So I am trying to understand the algorithm. So Wikipedia says for back-face culling to use the first vertex in the triangle: Does the vertex on the triangle chosen to create the view vector (the view vector in the Wikipedia picture is (V_0-P)) matter for back-face culling though? Like is there potential edge cases when choosing the first vertex actually culls a visible triangle? So another question, if it actually does matter, is there an optimal point somewhere in the triangle that will always cull face that are only not visible (could be a vertex, on the edge of the triangle, or in the interior)?
Your questions: Does the vertex on the triangle chosen to create the view vector (the view vector in the Wikipedia picture is V_0 - P) matter for back-face culling though? No, V0 ("the first vertex") is chosen arbitrarily. The math also holds for any other choice of V0, V1 and V2. Like is there potential edge cases when choosing the first vertex actually culls a visible triangle? Mathematically, this is not possible. In practice, this may happen if P lies in the plane the triangle is in (i.e. dot(-V0, N) is very close to 0.0) due to the rounding errors of floating point math. This may show up during rendering as a flickering line depending on your model, camera position, algorithms, implementations, etc. I don't think these cases generally pose an actual problem in such a way that they need handled differently. One issue is that it is difficult to detect if a triangle is visible but shouldn't have been (or vice versa). Another issue is that handling these cases requires more computations. E.g. computing dot(-V0, N) for all six possible choices for V0, V1 and V2, doing a majority vote, and then there still is no guarantee that the result is correct.